diff
stringlengths
262
553k
is_single_chunk
bool
2 classes
is_single_function
bool
1 class
buggy_function
stringlengths
20
391k
fixed_function
stringlengths
0
392k
diff --git a/tests/testbench/com/vaadin/tests/components/table/TableSingleSelect.java b/tests/testbench/com/vaadin/tests/components/table/TableSingleSelect.java index edde28484..8a37c10b6 100644 --- a/tests/testbench/com/vaadin/tests/components/table/TableSingleSelect.java +++ b/tests/testbench/com/vaadin/tests/components/table/TableSingleSelect.java @@ -1,54 +1,54 @@ package com.vaadin.tests.components.table; import com.vaadin.data.Property.ValueChangeEvent; import com.vaadin.data.Property.ValueChangeListener; import com.vaadin.tests.components.TestBase; import com.vaadin.tests.util.Log; import com.vaadin.ui.Button; import com.vaadin.ui.Component; import com.vaadin.ui.Table; public class TableSingleSelect extends TestBase { Log log = new Log(3); @Override protected void setup() { log.setDebugId("eventlog"); Table t = new Table(); t.setSelectable(true); t.setNullSelectionAllowed(true); t.setImmediate(true); t.addListener(new ValueChangeListener() { public void valueChange(ValueChangeEvent event) { log.log("Selected value: " + event.getProperty().getValue()); } }); t.addContainerProperty("string", String.class, null); t.addContainerProperty("button", Component.class, null); for (int i = 0; i < 10; i++) { t.addItem(i); - t.getContainerProperty(i, "string").setValue(i); + t.getContainerProperty(i, "string").setValue(String.valueOf(i)); t.getContainerProperty(i, "button") .setValue(new Button("Click me")); } addComponent(log); addComponent(t); } @Override protected String getDescription() { return "Table in single-select mode with null selection allowed. Tests that single select does not select multiple items, selects and deselects properly."; } @Override protected Integer getTicketNumber() { return 5431; } }
true
true
protected void setup() { log.setDebugId("eventlog"); Table t = new Table(); t.setSelectable(true); t.setNullSelectionAllowed(true); t.setImmediate(true); t.addListener(new ValueChangeListener() { public void valueChange(ValueChangeEvent event) { log.log("Selected value: " + event.getProperty().getValue()); } }); t.addContainerProperty("string", String.class, null); t.addContainerProperty("button", Component.class, null); for (int i = 0; i < 10; i++) { t.addItem(i); t.getContainerProperty(i, "string").setValue(i); t.getContainerProperty(i, "button") .setValue(new Button("Click me")); } addComponent(log); addComponent(t); }
protected void setup() { log.setDebugId("eventlog"); Table t = new Table(); t.setSelectable(true); t.setNullSelectionAllowed(true); t.setImmediate(true); t.addListener(new ValueChangeListener() { public void valueChange(ValueChangeEvent event) { log.log("Selected value: " + event.getProperty().getValue()); } }); t.addContainerProperty("string", String.class, null); t.addContainerProperty("button", Component.class, null); for (int i = 0; i < 10; i++) { t.addItem(i); t.getContainerProperty(i, "string").setValue(String.valueOf(i)); t.getContainerProperty(i, "button") .setValue(new Button("Click me")); } addComponent(log); addComponent(t); }
diff --git a/deegree-core/deegree-core-protocol/deegree-protocol-wms/src/main/java/org/deegree/protocol/wms/ops/GetMap.java b/deegree-core/deegree-core-protocol/deegree-protocol-wms/src/main/java/org/deegree/protocol/wms/ops/GetMap.java index f3094dbff6..e47efacfe3 100644 --- a/deegree-core/deegree-core-protocol/deegree-protocol-wms/src/main/java/org/deegree/protocol/wms/ops/GetMap.java +++ b/deegree-core/deegree-core-protocol/deegree-protocol-wms/src/main/java/org/deegree/protocol/wms/ops/GetMap.java @@ -1,746 +1,746 @@ //$HeadURL: svn+ssh://[email protected]/deegree/base/trunk/resources/eclipse/files_template.xml $ /*---------------------------------------------------------------------------- This file is part of deegree, http://deegree.org/ Copyright (C) 2001-2011 by: - Department of Geography, University of Bonn - and - lat/lon GmbH - This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact information: lat/lon GmbH Aennchenstr. 19, 53177 Bonn Germany http://lat-lon.de/ Department of Geography, University of Bonn Prof. Dr. Klaus Greve Postfach 1147, 53001 Bonn Germany http://www.geographie.uni-bonn.de/deegree/ e-mail: [email protected] ----------------------------------------------------------------------------*/ package org.deegree.protocol.wms.ops; import static java.awt.Color.decode; import static java.awt.Color.white; import static java.lang.Double.parseDouble; import static java.lang.Integer.parseInt; import static java.lang.Math.max; import static java.lang.Math.min; import static org.deegree.commons.utils.ArrayUtils.splitAsDoubles; import static org.deegree.commons.utils.CollectionUtils.map; import static org.deegree.layer.LayerRef.FROM_NAMES; import static org.deegree.layer.dims.Dimension.parseTyped; import static org.deegree.protocol.wms.WMSConstants.VERSION_111; import static org.deegree.protocol.wms.WMSConstants.VERSION_130; import static org.deegree.rendering.r2d.context.MapOptions.getAntialiasGetter; import static org.deegree.rendering.r2d.context.MapOptions.getAntialiasSetter; import static org.deegree.rendering.r2d.context.MapOptions.getInterpolationGetter; import static org.deegree.rendering.r2d.context.MapOptions.getInterpolationSetter; import static org.deegree.rendering.r2d.context.MapOptions.getQualityGetter; import static org.deegree.rendering.r2d.context.MapOptions.getQualitySetter; import static org.deegree.rendering.r2d.context.MapOptions.Antialias.BOTH; import static org.deegree.rendering.r2d.context.MapOptions.Interpolation.NEARESTNEIGHBOR; import static org.deegree.rendering.r2d.context.MapOptions.Quality.NORMAL; import static org.slf4j.LoggerFactory.getLogger; import java.awt.Color; import java.io.StringReader; import java.text.ParseException; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java_cup.runtime.Symbol; import org.deegree.commons.tom.ReferenceResolvingException; import org.deegree.commons.tom.ows.Version; import org.deegree.commons.utils.CollectionUtils; import org.deegree.commons.utils.Pair; import org.deegree.cs.coordinatesystems.ICRS; import org.deegree.cs.persistence.CRSManager; import org.deegree.geometry.Envelope; import org.deegree.geometry.GeometryFactory; import org.deegree.layer.LayerRef; import org.deegree.layer.dims.DimensionLexer; import org.deegree.layer.dims.parser; import org.deegree.protocol.ows.exception.OWSException; import org.deegree.protocol.wms.Utils; import org.deegree.rendering.r2d.RenderHelper; import org.deegree.rendering.r2d.context.MapOptions.Antialias; import org.deegree.rendering.r2d.context.MapOptions.Interpolation; import org.deegree.rendering.r2d.context.MapOptions.MapOptionsGetter; import org.deegree.rendering.r2d.context.MapOptions.MapOptionsSetter; import org.deegree.rendering.r2d.context.MapOptions.Quality; import org.deegree.rendering.r2d.context.MapOptionsMaps; import org.deegree.style.StyleRef; import org.slf4j.Logger; /** * * @author <a href="mailto:[email protected]">Andreas Schmitz</a> * @author last edited by: $Author: stranger $ * * @version $Revision: $, $Date: $ */ public class GetMap extends RequestBase { private static final Logger LOG = getLogger( GetMap.class ); private static GeometryFactory fac = new GeometryFactory(); private ICRS crs; private Envelope bbox; private String format; private int width, height; private boolean transparent; private Color bgcolor = white; private double scale; private double pixelSize = 0.00028; private double resolution; private MapOptionsMaps extensions; private double queryBoxSize = -1; private Map<String, String> parameterMap = new HashMap<String, String>(); /** * @param map * @param version * @param service * @throws OWSException */ public GetMap( Map<String, String> map, Version version, MapOptionsMaps exts ) throws OWSException { if ( version.equals( VERSION_111 ) ) { parse111( map, exts ); } if ( version.equals( VERSION_130 ) ) { parse130( map, exts ); } parameterMap.putAll( map ); try { scale = RenderHelper.calcScaleWMS130( width, height, bbox, crs, pixelSize ); LOG.debug( "GetMap request has a WMS 1.3.0/SLD scale of '{}' (adapted to pixel size of {}).", scale, pixelSize ); resolution = max( bbox.getSpan0() / width, bbox.getSpan1() / height ); LOG.debug( "Resolution per pixel is {}.", resolution ); } catch ( ReferenceResolvingException e ) { LOG.trace( "Stack trace:", e ); LOG.warn( "The scale of a GetMap request could not be calculated: '{}'.", e.getLocalizedMessage() ); } } /** * @param service * @param layers * @param styles * @param width * @param height * @param boundingBox * @throws OWSException */ public GetMap( Collection<LayerRef> layers, Collection<StyleRef> styles, int width, int height, Envelope boundingBox, MapOptionsMaps exts ) throws OWSException { this.layers.addAll( layers ); this.styles.addAll( styles ); this.width = width; this.height = height; this.bbox = boundingBox; this.crs = boundingBox.getCoordinateSystem(); this.bgcolor = white; format = "image/png"; transparent = false; handleVSPs( new HashMap<String, String>(), exts ); try { scale = RenderHelper.calcScaleWMS130( width, height, bbox, crs, pixelSize ); LOG.debug( "GetMap request has a WMS 1.3.0/SLD scale of '{}' (adapted to pixel size of {}).", scale, pixelSize ); resolution = max( bbox.getSpan0() / width, bbox.getSpan1() / height ); LOG.debug( "Resolution per pixel is {}.", resolution ); } catch ( ReferenceResolvingException e ) { LOG.trace( "Stack trace:", e ); throw new OWSException( e.getLocalizedMessage(), "InvalidParameterValue" ); } } public GetMap( List<String> layers, int width, int height, Envelope envelope, ICRS crs, String format, boolean transparent ) { this.layers = map( layers, FROM_NAMES ); this.width = width; this.height = height; this.bbox = envelope; this.crs = crs; this.format = format; this.transparent = transparent; } public GetMap( List<String> layers, List<String> styles, int width, int height, Envelope envelope, ICRS crs, String format, boolean transparent ) { this( layers, width, height, envelope, crs, format, transparent ); this.styles = map( styles, StyleRef.FROM_NAMES ); } public GetMap( List<Pair<String, String>> layers, int width, int height, Envelope boundingBox, String format, boolean transparent ) throws OWSException { for ( Pair<String, String> layer : layers ) { this.layers.add( new LayerRef( layer.first ) ); this.styles.add( layer.second != null ? new StyleRef( layer.second ) : null ); } this.width = width; this.height = height; this.bbox = boundingBox; this.crs = boundingBox.getCoordinateSystem(); this.bgcolor = white; this.format = format; this.transparent = transparent; try { scale = RenderHelper.calcScaleWMS130( width, height, bbox, crs, pixelSize ); LOG.debug( "GetMap request has a WMS 1.3.0/SLD scale of '{}' (adapted to pixel size of {}).", scale, pixelSize ); resolution = max( bbox.getSpan0() / width, bbox.getSpan1() / height ); LOG.debug( "Resolution per pixel is {}.", resolution ); } catch ( ReferenceResolvingException e ) { LOG.trace( "Stack trace:", e ); throw new OWSException( e.getLocalizedMessage(), "InvalidParameterValue" ); } } private void parse111( Map<String, String> map, MapOptionsMaps exts ) throws OWSException { String c = map.get( "SRS" ); if ( c == null || c.trim().isEmpty() ) { throw new OWSException( "The SRS parameter is missing.", OWSException.MISSING_PARAMETER_VALUE ); } crs = getCRS111( c ); String box = map.get( "BBOX" ); if ( box == null || box.trim().isEmpty() ) { throw new OWSException( "The BBOX parameter is missing.", OWSException.MISSING_PARAMETER_VALUE ); } double[] vals = splitAsDoubles( box, "," ); // hack to work around ESRI ArcGIS Explorer localized bboxes... if ( vals.length == 8 ) { String[] ss = box.split( "," ); vals = new double[] { parseDouble( ss[0] + "." + ss[1] ), parseDouble( ss[2] + "." + ss[3] ), parseDouble( ss[4] + "." + ss[5] ), parseDouble( ss[6] + "." + ss[7] ) }; } if ( vals.length != 4 ) { throw new OWSException( "The bounding box parameter value " + box + " is in the wrong format (too many values).", OWSException.INVALID_PARAMETER_VALUE ); } if ( vals[2] <= vals[0] ) { throw new OWSException( "The maxx component of the bounding box is smaller than the minx component.", OWSException.INVALID_PARAMETER_VALUE ); } if ( vals[3] <= vals[1] ) { throw new OWSException( "The maxy component of the bounding box is smaller than the miny component.", OWSException.INVALID_PARAMETER_VALUE ); } bbox = fac.createEnvelope( new double[] { vals[0], vals[1] }, new double[] { vals[2], vals[3] }, crs ); handleCommon( map, exts ); } static LinkedList<StyleRef> handleKVPStyles( String ss, int numLayers ) throws OWSException { LinkedList<StyleRef> styles = new LinkedList<StyleRef>(); // result is a list with 'default' where default styles were requested if ( ss.trim().isEmpty() ) { for ( int i = 0; i < numLayers; ++i ) { styles.add( new StyleRef( "default" ) ); } } else { // to work around #split limitations if ( ss.startsWith( "," ) ) { ss = "default" + ss; } if ( ss.endsWith( "," ) ) { ss = ss + "default"; } String[] styls = ss.split( "," ); if ( styls.length != numLayers ) { throw new OWSException( styls.length + "styles have been specified, and " + numLayers + " layers (should be equal).", OWSException.INVALID_PARAMETER_VALUE ); } for ( int i = 0; i < numLayers; ++i ) { if ( styls[i].isEmpty() || styls[i].equals( "default" ) ) { styles.add( new StyleRef( "default" ) ); } else { styles.add( new StyleRef( styls[i] ) ); } } } return styles; } private void handleCommon( Map<String, String> map, MapOptionsMaps exts ) throws OWSException { String ls = map.get( "LAYERS" ); String sld = map.get( "SLD" ); String sldBody = map.get( "SLD_BODY" ); if ( ( ls == null || ls.trim().isEmpty() ) && sld == null && sldBody == null ) { throw new OWSException( "The LAYERS parameter is missing.", OWSException.MISSING_PARAMETER_VALUE ); } layers = ls == null ? new LinkedList<LayerRef>() : CollectionUtils.map( ls.split( "," ), LayerRef.FROM_NAMES ); if ( layers.size() == 1 && layers.get( 0 ).getName().isEmpty() ) { layers.clear(); } String ss = map.get( "STYLES" ); if ( ss == null && sld == null && sldBody == null ) { throw new OWSException( "The STYLES parameter is missing.", OWSException.MISSING_PARAMETER_VALUE ); } if ( sld == null && sldBody == null ) { this.styles = handleKVPStyles( ss, layers.size() ); } else { // TODO think about whether STYLES has to be handled here as well handleSLD( sld, sldBody, layers ); } String psize = map.get( "PIXELSIZE" ); if ( psize != null ) { try { - pixelSize = Double.parseDouble( psize ); + pixelSize = Double.parseDouble( psize ) / 1000; } catch ( NumberFormatException e ) { LOG.warn( "The value of PIXELSIZE could not be parsed as a number." ); LOG.trace( "Stack trace:", e ); } } format = map.get( "FORMAT" ); if ( format == null ) { throw new OWSException( "The FORMAT parameter is missing.", OWSException.MISSING_PARAMETER_VALUE ); } String w = map.get( "WIDTH" ); if ( w == null ) { throw new OWSException( "The WIDTH parameter is missing.", OWSException.MISSING_PARAMETER_VALUE ); } try { width = parseInt( w ); } catch ( NumberFormatException e ) { throw new OWSException( "The WIDTH parameter value is not a number (was " + w + ").", OWSException.INVALID_PARAMETER_VALUE ); } String h = map.get( "HEIGHT" ); if ( h == null ) { throw new OWSException( "The HEIGHT parameter is missing.", OWSException.MISSING_PARAMETER_VALUE ); } try { height = parseInt( h ); } catch ( NumberFormatException e ) { throw new OWSException( "The HEIGHT parameter value is not a number (was " + h + ").", OWSException.INVALID_PARAMETER_VALUE ); } String t = map.get( "TRANSPARENT" ); transparent = t != null && t.equalsIgnoreCase( "true" ); if ( transparent && ( format.indexOf( "gif" ) != -1 || format.indexOf( "png" ) != -1 ) ) { bgcolor = new Color( 255, 255, 255, 0 ); } else { String col = map.get( "BGCOLOR" ); if ( col != null ) { bgcolor = decode( col ); } } dimensions = parseDimensionValues( map ); String q = map.get( "QUERYBOXSIZE" ); if ( q != null ) { try { queryBoxSize = Double.parseDouble( q ); System.out.println(queryBoxSize); } catch ( NumberFormatException e ) { LOG.warn( "The QUERYBOXSIZE parameter could not be parsed." ); } } handleVSPs( map, exts ); } private void handleVSPs( Map<String, String> map, MapOptionsMaps defaults ) { if ( defaults == null ) { defaults = new MapOptionsMaps(); } extensions = new MapOptionsMaps(); handleEnumVSP( Quality.class, getQualitySetter( extensions ), NORMAL, map.get( "QUALITY" ), getQualityGetter( defaults ) ); handleEnumVSP( Interpolation.class, getInterpolationSetter( extensions ), NEARESTNEIGHBOR, map.get( "INTERPOLATION" ), getInterpolationGetter( defaults ) ); handleEnumVSP( Antialias.class, getAntialiasSetter( extensions ), BOTH, map.get( "ANTIALIAS" ), getAntialiasGetter( defaults ) ); String maxFeatures = map.get( "MAX_FEATURES" ); if ( maxFeatures == null ) { for ( LayerRef l : this.layers ) { Integer max = defaults.getMaxFeatures( l.getName() ); if ( max == null ) { max = 10000; LOG.debug( "Using global max features setting of {}.", max ); } extensions.setMaxFeatures( l.getName(), max ); } } else { String[] mfs = maxFeatures.split( "," ); if ( mfs.length == this.layers.size() ) { for ( int i = 0; i < mfs.length; ++i ) { LayerRef cur = this.layers.get( i ); Integer def = defaults.getMaxFeatures( cur.getName() ); try { Integer val = Integer.valueOf( mfs[i] ); extensions.setMaxFeatures( cur.getName(), def == null ? val : min( def, val ) ); } catch ( NumberFormatException e ) { LOG.info( "The value '{}' for MAX_FEATURES can not be parsed as a number.", mfs[i] ); extensions.setMaxFeatures( cur.getName(), def == null ? 10000 : def ); } } } else { for ( int i = 0; i < mfs.length; ++i ) { LayerRef cur = this.layers.get( i ); Integer def = defaults.getMaxFeatures( cur.getName() ); if ( mfs.length <= i ) { try { Integer val = Integer.valueOf( mfs[i] ); extensions.setMaxFeatures( cur.getName(), def == null ? val : min( def, val ) ); } catch ( NumberFormatException e ) { LOG.info( "The value '{}' for MAX_FEATURES can not be parsed as a number.", mfs[i] ); extensions.setMaxFeatures( cur.getName(), def == null ? 10000 : def ); } } else { extensions.setMaxFeatures( cur.getName(), def == null ? 10000 : def ); } } } } } private <T extends Enum<T>> void handleEnumVSP( Class<T> enumType, MapOptionsSetter<T> setter, T defaultVal, String vals, MapOptionsGetter<T> defaults ) { if ( vals == null ) { for ( LayerRef l : layers ) { T val = defaults.getOption( l.getName() ); setter.setOption( l.getName(), val == null ? defaultVal : val ); } } else { String[] ss = vals.split( "," ); if ( ss.length == layers.size() ) { for ( int i = 0; i < ss.length; ++i ) { T val = defaults.getOption( layers.get( i ).getName() ); try { setter.setOption( layers.get( i ).getName(), Enum.valueOf( enumType, ss[i].toUpperCase() ) ); } catch ( IllegalArgumentException e ) { setter.setOption( layers.get( i ).getName(), val == null ? defaultVal : val ); LOG.warn( "'{}' is not a valid value for '{}'. Using default value '{}' instead.", new Object[] { ss[i], enumType.getSimpleName(), val == null ? defaultVal : val } ); } } } else { for ( int i = 0; i < layers.size(); ++i ) { T val = defaults.getOption( layers.get( i ).getName() ); if ( ss.length <= i ) { setter.setOption( layers.get( i ).getName(), val == null ? defaultVal : val ); } else { try { setter.setOption( layers.get( i ).getName(), Enum.valueOf( enumType, ss[i].toUpperCase() ) ); } catch ( IllegalArgumentException e ) { setter.setOption( layers.get( i ).getName(), val == null ? defaultVal : val ); LOG.warn( "'{}' is not a valid value for '{}'. Using default value '{}' instead.", new Object[] { ss[i], enumType.getSimpleName(), val == null ? defaultVal : val } ); } } } } } } static HashMap<String, List<?>> parseDimensionValues( Map<String, String> map ) throws OWSException { HashMap<String, List<?>> dims = new HashMap<String, List<?>>(); try { for ( Entry<String, String> entry : map.entrySet() ) { String key = entry.getKey(); String val = entry.getValue(); if ( key.equals( "TIME" ) ) { dims.put( "time", (List<?>) parseTyped( parseDimensionValues( val, "time" ), true ) ); } if ( key.equals( "ELEVATION" ) || key.startsWith( "DIM_" ) ) { String name = key.equals( "ELEVATION" ) ? "elevation" : key.substring( 4 ).toLowerCase(); dims.put( name, (List<?>) parseTyped( parseDimensionValues( val, name ), false ) ); } } return dims; } catch ( ParseException e ) { LOG.trace( "Stack trace:", e ); throw new OWSException( "The TIME parameter value was not in ISO8601 format: " + e.getLocalizedMessage(), OWSException.INVALID_PARAMETER_VALUE ); } } /** * @param value * @param name * @return the parsed list of strings or intervals * @throws OWSException */ public static LinkedList<?> parseDimensionValues( String value, String name ) throws OWSException { parser parser = new parser( new DimensionLexer( new StringReader( value ) ) ); try { Symbol sym = parser.parse(); if ( sym.value instanceof Exception ) { final String msg = "The value for the " + name + " dimension parameter was invalid: " + ( (Exception) sym.value ).getMessage(); throw new OWSException( msg, OWSException.INVALID_PARAMETER_VALUE ); } return (LinkedList<?>) sym.value; } catch ( Throwable e ) { LOG.trace( "Stack trace:", e ); throw new OWSException( "The value for the " + name + " dimension parameter was invalid: " + e.getMessage(), OWSException.INVALID_PARAMETER_VALUE ); } } private void parse130( Map<String, String> map, MapOptionsMaps exts ) throws OWSException { String c = map.get( "CRS" ); if ( c == null || c.trim().isEmpty() ) { throw new OWSException( "The CRS parameter is missing.", OWSException.MISSING_PARAMETER_VALUE ); } String box = map.get( "BBOX" ); if ( box == null || box.trim().isEmpty() ) { throw new OWSException( "The BBOX parameter is missing.", OWSException.MISSING_PARAMETER_VALUE ); } double[] vals = splitAsDoubles( box, "," ); if ( vals.length != 4 ) { throw new OWSException( "The value of the BBOX parameter had too many values: " + box, OWSException.INVALID_PARAMETER_VALUE ); } if ( vals[2] <= vals[0] ) { throw new OWSException( "The maxx component of the BBOX was smaller that the minx component.", OWSException.INVALID_PARAMETER_VALUE ); } if ( vals[3] <= vals[1] ) { throw new OWSException( "The maxy component of the BBOX was smaller that the miny component.", OWSException.INVALID_PARAMETER_VALUE ); } bbox = getCRSAndEnvelope130( c, vals ); crs = bbox.getCoordinateSystem(); handleCommon( map, exts ); } /** * @return the coordinate system of the bbox */ public ICRS getCoordinateSystem() { return crs; } /** * @return the bbox */ public Envelope getBoundingBox() { return bbox; } /** * @return a copy of the layers list */ @Override public LinkedList<LayerRef> getLayers() { return new LinkedList<LayerRef>( layers ); } /** * @return a copy of the styles list */ public LinkedList<StyleRef> getStyles() { return new LinkedList<StyleRef>( styles ); } /** * @return the image format */ public String getFormat() { return format; } /** * @return the width */ public int getWidth() { return width; } /** * @return the height */ public int getHeight() { return height; } /** * @return the transparent parameter */ public boolean getTransparent() { return transparent; } /** * @return the desired background color */ public Color getBgColor() { return bgcolor; } /** * @param crs */ public void setCoordinateSystem( ICRS crs ) { this.crs = crs; bbox = fac.createEnvelope( bbox.getMin().getAsArray(), bbox.getMax().getAsArray(), crs ); } /** * @return the scale as WMS 1.3.0/SLD scale */ @Override public double getScale() { return scale; } /** * @return the value of the pixel size parameter (default is 0.00028 m). */ public double getPixelSize() { return pixelSize; } /** * @return max(horizontal/vertical) resolution */ public double getResolution() { return resolution; } /** * @return the get map extensions for the layers */ public MapOptionsMaps getRenderingOptions() { return extensions; } /** * @return the envelope that should be used for backend queries */ public Envelope getQueryBox() { if ( queryBoxSize < 0 ) { return bbox; } double minx = bbox.getMin().get0(); double miny = bbox.getMin().get1(); double maxx = bbox.getMax().get0(); double maxy = bbox.getMax().get1(); double w = bbox.getSpan0(); double h = bbox.getSpan1(); double dx = ( w * queryBoxSize - w ) / 2; double dy = ( h * queryBoxSize - h ) / 2; minx -= dx; miny -= dy; maxx += dx; maxy += dy; return new GeometryFactory().createEnvelope( minx, miny, maxx, maxy, bbox.getCoordinateSystem() ); } /** * @return the KVP map of parameters. May not be accurate/empty, especially if this object has been created by some * other means than a KVP request. */ public Map<String, String> getParameterMap() { return parameterMap; } /** * @param crs * @return the auto crs as defined in WMS 1.1.1 spec Annex E */ public static ICRS getCRS111( String crs ) { if ( crs.startsWith( "AUTO:" ) ) { String[] cs = crs.split( ":" )[1].split( "," ); int id = Integer.parseInt( cs[0] ); // this is not supported // int units = Integer.parseInt( cs[1] ); double lon0 = Double.parseDouble( cs[2] ); double lat0 = Double.parseDouble( cs[3] ); return Utils.getAutoCRS( id, lon0, lat0 ); } return CRSManager.getCRSRef( crs, true ); } /** * @param crs * @param bbox * @return a new CRS */ public static Envelope getCRSAndEnvelope130( String crs, double[] bbox ) { if ( crs.startsWith( "AUTO2:" ) ) { String[] cs = crs.split( ":" )[1].split( "," ); int id = Integer.parseInt( cs[0] ); // this is not supported double factor = Double.parseDouble( cs[1] ); double lon0 = Double.parseDouble( cs[2] ); double lat0 = Double.parseDouble( cs[3] ); return new GeometryFactory().createEnvelope( factor * bbox[0], factor * bbox[1], factor * bbox[2], factor * bbox[3], Utils.getAutoCRS( id, lon0, lat0 ) ); } return new GeometryFactory().createEnvelope( bbox[0], bbox[1], bbox[2], bbox[3], CRSManager.getCRSRef( crs ) ); } }
true
true
private void handleCommon( Map<String, String> map, MapOptionsMaps exts ) throws OWSException { String ls = map.get( "LAYERS" ); String sld = map.get( "SLD" ); String sldBody = map.get( "SLD_BODY" ); if ( ( ls == null || ls.trim().isEmpty() ) && sld == null && sldBody == null ) { throw new OWSException( "The LAYERS parameter is missing.", OWSException.MISSING_PARAMETER_VALUE ); } layers = ls == null ? new LinkedList<LayerRef>() : CollectionUtils.map( ls.split( "," ), LayerRef.FROM_NAMES ); if ( layers.size() == 1 && layers.get( 0 ).getName().isEmpty() ) { layers.clear(); } String ss = map.get( "STYLES" ); if ( ss == null && sld == null && sldBody == null ) { throw new OWSException( "The STYLES parameter is missing.", OWSException.MISSING_PARAMETER_VALUE ); } if ( sld == null && sldBody == null ) { this.styles = handleKVPStyles( ss, layers.size() ); } else { // TODO think about whether STYLES has to be handled here as well handleSLD( sld, sldBody, layers ); } String psize = map.get( "PIXELSIZE" ); if ( psize != null ) { try { pixelSize = Double.parseDouble( psize ); } catch ( NumberFormatException e ) { LOG.warn( "The value of PIXELSIZE could not be parsed as a number." ); LOG.trace( "Stack trace:", e ); } } format = map.get( "FORMAT" ); if ( format == null ) { throw new OWSException( "The FORMAT parameter is missing.", OWSException.MISSING_PARAMETER_VALUE ); } String w = map.get( "WIDTH" ); if ( w == null ) { throw new OWSException( "The WIDTH parameter is missing.", OWSException.MISSING_PARAMETER_VALUE ); } try { width = parseInt( w ); } catch ( NumberFormatException e ) { throw new OWSException( "The WIDTH parameter value is not a number (was " + w + ").", OWSException.INVALID_PARAMETER_VALUE ); } String h = map.get( "HEIGHT" ); if ( h == null ) { throw new OWSException( "The HEIGHT parameter is missing.", OWSException.MISSING_PARAMETER_VALUE ); } try { height = parseInt( h ); } catch ( NumberFormatException e ) { throw new OWSException( "The HEIGHT parameter value is not a number (was " + h + ").", OWSException.INVALID_PARAMETER_VALUE ); } String t = map.get( "TRANSPARENT" ); transparent = t != null && t.equalsIgnoreCase( "true" ); if ( transparent && ( format.indexOf( "gif" ) != -1 || format.indexOf( "png" ) != -1 ) ) { bgcolor = new Color( 255, 255, 255, 0 ); } else { String col = map.get( "BGCOLOR" ); if ( col != null ) { bgcolor = decode( col ); } } dimensions = parseDimensionValues( map ); String q = map.get( "QUERYBOXSIZE" ); if ( q != null ) { try { queryBoxSize = Double.parseDouble( q ); System.out.println(queryBoxSize); } catch ( NumberFormatException e ) { LOG.warn( "The QUERYBOXSIZE parameter could not be parsed." ); } } handleVSPs( map, exts ); }
private void handleCommon( Map<String, String> map, MapOptionsMaps exts ) throws OWSException { String ls = map.get( "LAYERS" ); String sld = map.get( "SLD" ); String sldBody = map.get( "SLD_BODY" ); if ( ( ls == null || ls.trim().isEmpty() ) && sld == null && sldBody == null ) { throw new OWSException( "The LAYERS parameter is missing.", OWSException.MISSING_PARAMETER_VALUE ); } layers = ls == null ? new LinkedList<LayerRef>() : CollectionUtils.map( ls.split( "," ), LayerRef.FROM_NAMES ); if ( layers.size() == 1 && layers.get( 0 ).getName().isEmpty() ) { layers.clear(); } String ss = map.get( "STYLES" ); if ( ss == null && sld == null && sldBody == null ) { throw new OWSException( "The STYLES parameter is missing.", OWSException.MISSING_PARAMETER_VALUE ); } if ( sld == null && sldBody == null ) { this.styles = handleKVPStyles( ss, layers.size() ); } else { // TODO think about whether STYLES has to be handled here as well handleSLD( sld, sldBody, layers ); } String psize = map.get( "PIXELSIZE" ); if ( psize != null ) { try { pixelSize = Double.parseDouble( psize ) / 1000; } catch ( NumberFormatException e ) { LOG.warn( "The value of PIXELSIZE could not be parsed as a number." ); LOG.trace( "Stack trace:", e ); } } format = map.get( "FORMAT" ); if ( format == null ) { throw new OWSException( "The FORMAT parameter is missing.", OWSException.MISSING_PARAMETER_VALUE ); } String w = map.get( "WIDTH" ); if ( w == null ) { throw new OWSException( "The WIDTH parameter is missing.", OWSException.MISSING_PARAMETER_VALUE ); } try { width = parseInt( w ); } catch ( NumberFormatException e ) { throw new OWSException( "The WIDTH parameter value is not a number (was " + w + ").", OWSException.INVALID_PARAMETER_VALUE ); } String h = map.get( "HEIGHT" ); if ( h == null ) { throw new OWSException( "The HEIGHT parameter is missing.", OWSException.MISSING_PARAMETER_VALUE ); } try { height = parseInt( h ); } catch ( NumberFormatException e ) { throw new OWSException( "The HEIGHT parameter value is not a number (was " + h + ").", OWSException.INVALID_PARAMETER_VALUE ); } String t = map.get( "TRANSPARENT" ); transparent = t != null && t.equalsIgnoreCase( "true" ); if ( transparent && ( format.indexOf( "gif" ) != -1 || format.indexOf( "png" ) != -1 ) ) { bgcolor = new Color( 255, 255, 255, 0 ); } else { String col = map.get( "BGCOLOR" ); if ( col != null ) { bgcolor = decode( col ); } } dimensions = parseDimensionValues( map ); String q = map.get( "QUERYBOXSIZE" ); if ( q != null ) { try { queryBoxSize = Double.parseDouble( q ); System.out.println(queryBoxSize); } catch ( NumberFormatException e ) { LOG.warn( "The QUERYBOXSIZE parameter could not be parsed." ); } } handleVSPs( map, exts ); }
diff --git a/qcadoo-view/src/main/java/com/qcadoo/view/internal/JsonMapperHttpMessageConverter.java b/qcadoo-view/src/main/java/com/qcadoo/view/internal/JsonMapperHttpMessageConverter.java index 59468d9a9..b6228703d 100644 --- a/qcadoo-view/src/main/java/com/qcadoo/view/internal/JsonMapperHttpMessageConverter.java +++ b/qcadoo-view/src/main/java/com/qcadoo/view/internal/JsonMapperHttpMessageConverter.java @@ -1,70 +1,75 @@ /** * *************************************************************************** * Copyright (c) 2010 Qcadoo Limited * Project: Qcadoo Framework * Version: 0.4.5 * * This file is part of Qcadoo. * * Qcadoo is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation; either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *************************************************************************** */ package com.qcadoo.view.internal; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.nio.charset.Charset; import org.apache.commons.io.IOUtils; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.SerializationConfig; import org.springframework.http.HttpInputMessage; import org.springframework.http.HttpOutputMessage; import org.springframework.http.MediaType; import org.springframework.http.converter.AbstractHttpMessageConverter; public final class JsonMapperHttpMessageConverter extends AbstractHttpMessageConverter<Object> { public static final Charset CHARSET = Charset.forName("UTF-8"); public static final MediaType MEDIA_TYPE = new MediaType("application", "json", CHARSET); public final ObjectMapper mapper = new ObjectMapper(); public JsonMapperHttpMessageConverter() { super(MEDIA_TYPE); mapper.getSerializationConfig().set(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false); } @Override protected boolean supports(final Class<?> clazz) { return true; } @Override protected Object readInternal(final Class<?> clazz, final HttpInputMessage inputMessage) throws IOException { String body = IOUtils.toString(inputMessage.getBody(), CHARSET.name()); return mapper.readValue(body, clazz); } @Override protected void writeInternal(final Object value, final HttpOutputMessage outputMessage) throws IOException { - Writer writer = new OutputStreamWriter(outputMessage.getBody(), CHARSET); - writer.append(mapper.writeValueAsString(value)); - writer.flush(); + Writer writer = null; + try { + writer = new OutputStreamWriter(outputMessage.getBody(), CHARSET); + writer.append(mapper.writeValueAsString(value)); + writer.flush(); + } finally { + IOUtils.closeQuietly(writer); + } } }
true
true
protected void writeInternal(final Object value, final HttpOutputMessage outputMessage) throws IOException { Writer writer = new OutputStreamWriter(outputMessage.getBody(), CHARSET); writer.append(mapper.writeValueAsString(value)); writer.flush(); }
protected void writeInternal(final Object value, final HttpOutputMessage outputMessage) throws IOException { Writer writer = null; try { writer = new OutputStreamWriter(outputMessage.getBody(), CHARSET); writer.append(mapper.writeValueAsString(value)); writer.flush(); } finally { IOUtils.closeQuietly(writer); } }
diff --git a/test/com/eteks/sweethome3d/junit/PrintTest.java b/test/com/eteks/sweethome3d/junit/PrintTest.java index d80be6bc..07b81c64 100644 --- a/test/com/eteks/sweethome3d/junit/PrintTest.java +++ b/test/com/eteks/sweethome3d/junit/PrintTest.java @@ -1,294 +1,298 @@ /* * PrintTest.java 27 aout 2007 * * Copyright (c) 2007 Emmanuel PUYBARET / eTeks <[email protected]>. All Rights Reserved. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., 59 Temple * Place, Suite 330, Boston, MA 02111-1307 USA */ package com.eteks.sweethome3d.junit; import java.awt.Dialog; import java.awt.print.PageFormat; import java.awt.print.PrinterJob; import java.io.File; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.Arrays; import java.util.List; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JToolBar; import junit.extensions.abbot.ComponentTestFixture; import abbot.finder.AWTHierarchy; import abbot.finder.BasicFinder; import abbot.finder.ComponentSearchException; import abbot.finder.matchers.ClassMatcher; import abbot.tester.JComponentTester; import abbot.tester.JFileChooserTester; import com.eteks.sweethome3d.io.DefaultUserPreferences; import com.eteks.sweethome3d.model.CatalogPieceOfFurniture; import com.eteks.sweethome3d.model.Home; import com.eteks.sweethome3d.model.HomePrint; import com.eteks.sweethome3d.model.UserPreferences; import com.eteks.sweethome3d.swing.FileContentManager; import com.eteks.sweethome3d.swing.HomePane; import com.eteks.sweethome3d.swing.HomePrintableComponent; import com.eteks.sweethome3d.swing.PageSetupPanel; import com.eteks.sweethome3d.swing.PrintPreviewPanel; import com.eteks.sweethome3d.swing.SwingViewFactory; import com.eteks.sweethome3d.tools.OperatingSystem; import com.eteks.sweethome3d.viewcontroller.ContentManager; import com.eteks.sweethome3d.viewcontroller.HomeController; import com.eteks.sweethome3d.viewcontroller.View; import com.eteks.sweethome3d.viewcontroller.ViewFactory; /** * Tests page setup and print preview panes in home. * @author Emmanuel Puybaret */ public class PrintTest extends ComponentTestFixture { public void testPageSetupAndPrintPreview() throws ComponentSearchException, InterruptedException, NoSuchFieldException, IllegalAccessException, InvocationTargetException, IOException { UserPreferences preferences = new DefaultUserPreferences(); ViewFactory viewFactory = new SwingViewFactory(); Home home = new Home(); ContentManager contentManager = new FileContentManager(preferences) { @Override public String showSaveDialog(View parentView, String dialogTitle, ContentType contentType, String name) { String os = System.getProperty("os.name"); if (OperatingSystem.isMacOSX()) { // Let's pretend the OS isn't Mac OS X to get a JFileChooser instance that works better in test System.setProperty("os.name", "dummy"); } try { return super.showSaveDialog(parentView, dialogTitle, contentType, name); } finally { System.setProperty("os.name", os); } } }; final HomeController controller = new HomeController(home, preferences, viewFactory, contentManager); // 1. Create a frame that displays a home view JFrame frame = new JFrame("Home Print Test"); frame.add((JComponent)controller.getView()); frame.pack(); // Show home frame showWindow(frame); JComponentTester tester = new JComponentTester(); tester.waitForIdle(); // Add a piece of furniture to home List<CatalogPieceOfFurniture> selectedPieces = Arrays.asList( new CatalogPieceOfFurniture [] {preferences.getFurnitureCatalog().getCategories().get(0).getFurniture().get(0)}); controller.getFurnitureCatalogController().setSelectedFurniture(selectedPieces); tester.invokeAndWait(new Runnable() { public void run() { runAction(controller, HomePane.ActionType.ADD_HOME_FURNITURE); } }); // Check home contains one piece assertEquals("Home doesn't contain any furniture", 1, home.getFurniture().size()); // 2. Edit page setup dialog box tester.invokeLater(new Runnable() { public void run() { // Display dialog box later in Event Dispatch Thread to avoid blocking test thread runAction(controller, HomePane.ActionType.PAGE_SETUP); } }); // Wait for page setup to be shown tester.waitForFrameShowing(new AWTHierarchy(), preferences.getLocalizedString( PageSetupPanel.class, "pageSetup.title")); // Check dialog box is displayed JDialog pageSetupDialog = (JDialog)TestUtilities.findComponent( frame, JDialog.class); assertTrue("Page setup dialog not showing", pageSetupDialog.isShowing()); // Retrieve PageSetupPanel components PageSetupPanel pageSetupPanel = (PageSetupPanel)TestUtilities.findComponent( frame, PageSetupPanel.class); JCheckBox furniturePrintedCheckBox = (JCheckBox)TestUtilities.getField(pageSetupPanel, "furniturePrintedCheckBox"); JCheckBox planPrintedCheckBox = (JCheckBox)TestUtilities.getField(pageSetupPanel, "planPrintedCheckBox");; JCheckBox view3DPrintedCheckBox = (JCheckBox)TestUtilities.getField(pageSetupPanel, "view3DPrintedCheckBox"); // Check default edited values assertTrue("Furniture printed not checked", furniturePrintedCheckBox.isSelected()); assertTrue("Plan printed not checked", planPrintedCheckBox.isSelected()); assertTrue("View 3D printed not checked", view3DPrintedCheckBox.isSelected()); // 3. Change dialog box values planPrintedCheckBox.setSelected(false); // Click on Ok in dialog box final JOptionPane pageSetupOptionPane = (JOptionPane)TestUtilities.findComponent( pageSetupDialog, JOptionPane.class); tester.invokeAndWait(new Runnable() { public void run() { // Select Ok option to hide dialog box in Event Dispatch Thread pageSetupOptionPane.setValue(JOptionPane.OK_OPTION); } }); assertFalse("Page setup dialog still showing", pageSetupDialog.isShowing()); PageFormat pageFormat = PrinterJob.getPrinterJob().defaultPage(); // Check home print attributes are modified accordingly assertHomePrintEqualPrintAttributes(pageFormat, true, false, true, home); // 4. Undo changes runAction(controller, HomePane.ActionType.UNDO); // Check home attributes have previous values assertEquals("Home print set", null, home.getPrint()); // Redo runAction(controller, HomePane.ActionType.REDO); // Check home attributes are modified accordingly assertHomePrintEqualPrintAttributes(pageFormat, true, false, true, home); // 5. Show print preview dialog box tester.invokeLater(new Runnable() { public void run() { // Display dialog box later in Event Dispatch Thread to avoid blocking test thread runAction(controller, HomePane.ActionType.PRINT_PREVIEW); } }); // Wait for print preview to be shown tester.waitForFrameShowing(new AWTHierarchy(), preferences.getLocalizedString( PrintPreviewPanel.class, "printPreview.title")); // Check dialog box is displayed JDialog printPreviewDialog = (JDialog)new BasicFinder().find(frame, new ClassMatcher (JDialog.class, true)); assertTrue("Print preview dialog not showing", printPreviewDialog.isShowing()); // Retrieve PageSetupPanel components PrintPreviewPanel printPreviewPanel = (PrintPreviewPanel)TestUtilities.findComponent( frame, PrintPreviewPanel.class); JToolBar toolBar = (JToolBar)TestUtilities.getField(printPreviewPanel, "toolBar"); JButton previousButton = (JButton)toolBar.getComponent(0); - JButton nextButton = (JButton)toolBar.getComponent(1); + final JButton nextButton = (JButton)toolBar.getComponent(1); HomePrintableComponent printableComponent = (HomePrintableComponent)TestUtilities.getField(printPreviewPanel, "printableComponent");; // Check if buttons are enabled and if printable component displays the first page assertFalse("Previous button is enabled", previousButton.isEnabled()); assertTrue("Next button is disabled", nextButton.isEnabled()); assertEquals("Printable component doesn't display first page", 0, printableComponent.getPage()); assertEquals("Wrong printable component page count", 2, printableComponent.getPageCount()); // 6. Click on next page button - tester.click(nextButton); + tester.invokeAndWait(new Runnable() { + public void run() { + nextButton.doClick(); + } + }); // Check if buttons are enabled and if printable component displays the second page assertTrue("Previous button is enabled", previousButton.isEnabled()); assertFalse("Next button is disabled", nextButton.isEnabled()); assertEquals("Printable component doesn't display second page", 1, printableComponent.getPage()); // Click on Ok in dialog box final JOptionPane printPreviewOptionPane = (JOptionPane)TestUtilities.findComponent( printPreviewDialog, JOptionPane.class); tester.invokeAndWait(new Runnable() { public void run() { // Select Ok option to hide dialog box in Event Dispatch Thread printPreviewOptionPane.setValue(JOptionPane.OK_OPTION); } }); assertFalse("Print preview dialog still showing", printPreviewDialog.isShowing()); // 7. Check the created PDF file doesn't exist String pdfFileBase = "testsdfghjk"; File pdfFile = new File(pdfFileBase + ".pdf"); assertFalse("PDF file already exists, delete it first", pdfFile.exists()); // Show print to PDF dialog box tester.invokeLater(new Runnable() { public void run() { // Display dialog box later in Event Dispatch Thread to avoid blocking test thread runAction(controller, HomePane.ActionType.PRINT_TO_PDF); } }); // Wait for print to PDF file chooser to be shown tester.waitForFrameShowing(new AWTHierarchy(), preferences.getLocalizedString( HomePane.class, "printToPDFDialog.title")); // Check dialog box is displayed final Dialog printToPdfDialog = (Dialog)new BasicFinder().find(frame, new ClassMatcher (Dialog.class, true)); assertTrue("Print to pdf dialog not showing", printToPdfDialog.isShowing()); // Change file in print to PDF file chooser final JFileChooserTester fileChooserTester = new JFileChooserTester(); final JFileChooser fileChooser = (JFileChooser)new BasicFinder().find(printToPdfDialog, new ClassMatcher(JFileChooser.class)); fileChooserTester.actionSetDirectory(fileChooser, System.getProperty("user.dir")); fileChooserTester.actionSetFilename(fileChooser, pdfFileBase); // Select Ok option to hide dialog box fileChooserTester.actionApprove(fileChooser); // Wait PDF generation Thread.sleep(2000); assertFalse("Print to pdf dialog still showing", printToPdfDialog.isShowing()); assertTrue("PDF file doesn't exist", pdfFile.exists()); assertTrue("PDF file is empty", pdfFile.length() > 0); pdfFile.delete(); } /** * Runs <code>actionPerformed</code> method matching <code>actionType</code> * in <code>HomePane</code>. */ private void runAction(HomeController controller, HomePane.ActionType actionType) { ((JComponent)controller.getView()).getActionMap().get(actionType).actionPerformed(null); } /** * Asserts the print attributes given in parameter match <code>home</code> print. */ private void assertHomePrintEqualPrintAttributes(PageFormat pageFormat, boolean furniturePrinted, boolean planPrinted, boolean view3DPrinted, Home home) { HomePrint homePrint = home.getPrint(); assertEquals("Wrong paper width", (float)pageFormat.getWidth(), homePrint.getPaperWidth()); assertEquals("Wrong paper height", (float)pageFormat.getHeight(), homePrint.getPaperHeight()); assertEquals("Wrong paper left margin", (float)pageFormat.getImageableX(), homePrint.getPaperLeftMargin()); assertEquals("Wrong paper top margin", (float)pageFormat.getImageableY(), homePrint.getPaperTopMargin()); assertEquals("Wrong paper right margin", (float)(pageFormat.getWidth() - pageFormat.getImageableX() - pageFormat.getImageableWidth()), homePrint.getPaperRightMargin()); assertEquals("Wrong paper bottom margin", (float)(pageFormat.getHeight() - pageFormat.getImageableY() - pageFormat.getImageableHeight()), homePrint.getPaperBottomMargin()); switch (pageFormat.getOrientation()) { case PageFormat.PORTRAIT : assertEquals("Wrong paper orientation", HomePrint.PaperOrientation.PORTRAIT, homePrint.getPaperOrientation()); break; case PageFormat.LANDSCAPE : assertEquals("Wrong paper orientation", HomePrint.PaperOrientation.LANDSCAPE, homePrint.getPaperOrientation()); break; case PageFormat.REVERSE_LANDSCAPE : assertEquals("Wrong paper orientation", HomePrint.PaperOrientation.REVERSE_LANDSCAPE, homePrint.getPaperOrientation()); break; } assertEquals("Wrong furniture printed", furniturePrinted, homePrint.isFurniturePrinted()); assertEquals("Wrong plan printed", planPrinted, homePrint.isPlanPrinted()); assertEquals("Wrong view 3D printed", view3DPrinted, homePrint.isView3DPrinted()); } }
false
true
public void testPageSetupAndPrintPreview() throws ComponentSearchException, InterruptedException, NoSuchFieldException, IllegalAccessException, InvocationTargetException, IOException { UserPreferences preferences = new DefaultUserPreferences(); ViewFactory viewFactory = new SwingViewFactory(); Home home = new Home(); ContentManager contentManager = new FileContentManager(preferences) { @Override public String showSaveDialog(View parentView, String dialogTitle, ContentType contentType, String name) { String os = System.getProperty("os.name"); if (OperatingSystem.isMacOSX()) { // Let's pretend the OS isn't Mac OS X to get a JFileChooser instance that works better in test System.setProperty("os.name", "dummy"); } try { return super.showSaveDialog(parentView, dialogTitle, contentType, name); } finally { System.setProperty("os.name", os); } } }; final HomeController controller = new HomeController(home, preferences, viewFactory, contentManager); // 1. Create a frame that displays a home view JFrame frame = new JFrame("Home Print Test"); frame.add((JComponent)controller.getView()); frame.pack(); // Show home frame showWindow(frame); JComponentTester tester = new JComponentTester(); tester.waitForIdle(); // Add a piece of furniture to home List<CatalogPieceOfFurniture> selectedPieces = Arrays.asList( new CatalogPieceOfFurniture [] {preferences.getFurnitureCatalog().getCategories().get(0).getFurniture().get(0)}); controller.getFurnitureCatalogController().setSelectedFurniture(selectedPieces); tester.invokeAndWait(new Runnable() { public void run() { runAction(controller, HomePane.ActionType.ADD_HOME_FURNITURE); } }); // Check home contains one piece assertEquals("Home doesn't contain any furniture", 1, home.getFurniture().size()); // 2. Edit page setup dialog box tester.invokeLater(new Runnable() { public void run() { // Display dialog box later in Event Dispatch Thread to avoid blocking test thread runAction(controller, HomePane.ActionType.PAGE_SETUP); } }); // Wait for page setup to be shown tester.waitForFrameShowing(new AWTHierarchy(), preferences.getLocalizedString( PageSetupPanel.class, "pageSetup.title")); // Check dialog box is displayed JDialog pageSetupDialog = (JDialog)TestUtilities.findComponent( frame, JDialog.class); assertTrue("Page setup dialog not showing", pageSetupDialog.isShowing()); // Retrieve PageSetupPanel components PageSetupPanel pageSetupPanel = (PageSetupPanel)TestUtilities.findComponent( frame, PageSetupPanel.class); JCheckBox furniturePrintedCheckBox = (JCheckBox)TestUtilities.getField(pageSetupPanel, "furniturePrintedCheckBox"); JCheckBox planPrintedCheckBox = (JCheckBox)TestUtilities.getField(pageSetupPanel, "planPrintedCheckBox");; JCheckBox view3DPrintedCheckBox = (JCheckBox)TestUtilities.getField(pageSetupPanel, "view3DPrintedCheckBox"); // Check default edited values assertTrue("Furniture printed not checked", furniturePrintedCheckBox.isSelected()); assertTrue("Plan printed not checked", planPrintedCheckBox.isSelected()); assertTrue("View 3D printed not checked", view3DPrintedCheckBox.isSelected()); // 3. Change dialog box values planPrintedCheckBox.setSelected(false); // Click on Ok in dialog box final JOptionPane pageSetupOptionPane = (JOptionPane)TestUtilities.findComponent( pageSetupDialog, JOptionPane.class); tester.invokeAndWait(new Runnable() { public void run() { // Select Ok option to hide dialog box in Event Dispatch Thread pageSetupOptionPane.setValue(JOptionPane.OK_OPTION); } }); assertFalse("Page setup dialog still showing", pageSetupDialog.isShowing()); PageFormat pageFormat = PrinterJob.getPrinterJob().defaultPage(); // Check home print attributes are modified accordingly assertHomePrintEqualPrintAttributes(pageFormat, true, false, true, home); // 4. Undo changes runAction(controller, HomePane.ActionType.UNDO); // Check home attributes have previous values assertEquals("Home print set", null, home.getPrint()); // Redo runAction(controller, HomePane.ActionType.REDO); // Check home attributes are modified accordingly assertHomePrintEqualPrintAttributes(pageFormat, true, false, true, home); // 5. Show print preview dialog box tester.invokeLater(new Runnable() { public void run() { // Display dialog box later in Event Dispatch Thread to avoid blocking test thread runAction(controller, HomePane.ActionType.PRINT_PREVIEW); } }); // Wait for print preview to be shown tester.waitForFrameShowing(new AWTHierarchy(), preferences.getLocalizedString( PrintPreviewPanel.class, "printPreview.title")); // Check dialog box is displayed JDialog printPreviewDialog = (JDialog)new BasicFinder().find(frame, new ClassMatcher (JDialog.class, true)); assertTrue("Print preview dialog not showing", printPreviewDialog.isShowing()); // Retrieve PageSetupPanel components PrintPreviewPanel printPreviewPanel = (PrintPreviewPanel)TestUtilities.findComponent( frame, PrintPreviewPanel.class); JToolBar toolBar = (JToolBar)TestUtilities.getField(printPreviewPanel, "toolBar"); JButton previousButton = (JButton)toolBar.getComponent(0); JButton nextButton = (JButton)toolBar.getComponent(1); HomePrintableComponent printableComponent = (HomePrintableComponent)TestUtilities.getField(printPreviewPanel, "printableComponent");; // Check if buttons are enabled and if printable component displays the first page assertFalse("Previous button is enabled", previousButton.isEnabled()); assertTrue("Next button is disabled", nextButton.isEnabled()); assertEquals("Printable component doesn't display first page", 0, printableComponent.getPage()); assertEquals("Wrong printable component page count", 2, printableComponent.getPageCount()); // 6. Click on next page button tester.click(nextButton); // Check if buttons are enabled and if printable component displays the second page assertTrue("Previous button is enabled", previousButton.isEnabled()); assertFalse("Next button is disabled", nextButton.isEnabled()); assertEquals("Printable component doesn't display second page", 1, printableComponent.getPage()); // Click on Ok in dialog box final JOptionPane printPreviewOptionPane = (JOptionPane)TestUtilities.findComponent( printPreviewDialog, JOptionPane.class); tester.invokeAndWait(new Runnable() { public void run() { // Select Ok option to hide dialog box in Event Dispatch Thread printPreviewOptionPane.setValue(JOptionPane.OK_OPTION); } }); assertFalse("Print preview dialog still showing", printPreviewDialog.isShowing()); // 7. Check the created PDF file doesn't exist String pdfFileBase = "testsdfghjk"; File pdfFile = new File(pdfFileBase + ".pdf"); assertFalse("PDF file already exists, delete it first", pdfFile.exists()); // Show print to PDF dialog box tester.invokeLater(new Runnable() { public void run() { // Display dialog box later in Event Dispatch Thread to avoid blocking test thread runAction(controller, HomePane.ActionType.PRINT_TO_PDF); } }); // Wait for print to PDF file chooser to be shown tester.waitForFrameShowing(new AWTHierarchy(), preferences.getLocalizedString( HomePane.class, "printToPDFDialog.title")); // Check dialog box is displayed final Dialog printToPdfDialog = (Dialog)new BasicFinder().find(frame, new ClassMatcher (Dialog.class, true)); assertTrue("Print to pdf dialog not showing", printToPdfDialog.isShowing()); // Change file in print to PDF file chooser final JFileChooserTester fileChooserTester = new JFileChooserTester(); final JFileChooser fileChooser = (JFileChooser)new BasicFinder().find(printToPdfDialog, new ClassMatcher(JFileChooser.class)); fileChooserTester.actionSetDirectory(fileChooser, System.getProperty("user.dir")); fileChooserTester.actionSetFilename(fileChooser, pdfFileBase); // Select Ok option to hide dialog box fileChooserTester.actionApprove(fileChooser); // Wait PDF generation Thread.sleep(2000); assertFalse("Print to pdf dialog still showing", printToPdfDialog.isShowing()); assertTrue("PDF file doesn't exist", pdfFile.exists()); assertTrue("PDF file is empty", pdfFile.length() > 0); pdfFile.delete(); }
public void testPageSetupAndPrintPreview() throws ComponentSearchException, InterruptedException, NoSuchFieldException, IllegalAccessException, InvocationTargetException, IOException { UserPreferences preferences = new DefaultUserPreferences(); ViewFactory viewFactory = new SwingViewFactory(); Home home = new Home(); ContentManager contentManager = new FileContentManager(preferences) { @Override public String showSaveDialog(View parentView, String dialogTitle, ContentType contentType, String name) { String os = System.getProperty("os.name"); if (OperatingSystem.isMacOSX()) { // Let's pretend the OS isn't Mac OS X to get a JFileChooser instance that works better in test System.setProperty("os.name", "dummy"); } try { return super.showSaveDialog(parentView, dialogTitle, contentType, name); } finally { System.setProperty("os.name", os); } } }; final HomeController controller = new HomeController(home, preferences, viewFactory, contentManager); // 1. Create a frame that displays a home view JFrame frame = new JFrame("Home Print Test"); frame.add((JComponent)controller.getView()); frame.pack(); // Show home frame showWindow(frame); JComponentTester tester = new JComponentTester(); tester.waitForIdle(); // Add a piece of furniture to home List<CatalogPieceOfFurniture> selectedPieces = Arrays.asList( new CatalogPieceOfFurniture [] {preferences.getFurnitureCatalog().getCategories().get(0).getFurniture().get(0)}); controller.getFurnitureCatalogController().setSelectedFurniture(selectedPieces); tester.invokeAndWait(new Runnable() { public void run() { runAction(controller, HomePane.ActionType.ADD_HOME_FURNITURE); } }); // Check home contains one piece assertEquals("Home doesn't contain any furniture", 1, home.getFurniture().size()); // 2. Edit page setup dialog box tester.invokeLater(new Runnable() { public void run() { // Display dialog box later in Event Dispatch Thread to avoid blocking test thread runAction(controller, HomePane.ActionType.PAGE_SETUP); } }); // Wait for page setup to be shown tester.waitForFrameShowing(new AWTHierarchy(), preferences.getLocalizedString( PageSetupPanel.class, "pageSetup.title")); // Check dialog box is displayed JDialog pageSetupDialog = (JDialog)TestUtilities.findComponent( frame, JDialog.class); assertTrue("Page setup dialog not showing", pageSetupDialog.isShowing()); // Retrieve PageSetupPanel components PageSetupPanel pageSetupPanel = (PageSetupPanel)TestUtilities.findComponent( frame, PageSetupPanel.class); JCheckBox furniturePrintedCheckBox = (JCheckBox)TestUtilities.getField(pageSetupPanel, "furniturePrintedCheckBox"); JCheckBox planPrintedCheckBox = (JCheckBox)TestUtilities.getField(pageSetupPanel, "planPrintedCheckBox");; JCheckBox view3DPrintedCheckBox = (JCheckBox)TestUtilities.getField(pageSetupPanel, "view3DPrintedCheckBox"); // Check default edited values assertTrue("Furniture printed not checked", furniturePrintedCheckBox.isSelected()); assertTrue("Plan printed not checked", planPrintedCheckBox.isSelected()); assertTrue("View 3D printed not checked", view3DPrintedCheckBox.isSelected()); // 3. Change dialog box values planPrintedCheckBox.setSelected(false); // Click on Ok in dialog box final JOptionPane pageSetupOptionPane = (JOptionPane)TestUtilities.findComponent( pageSetupDialog, JOptionPane.class); tester.invokeAndWait(new Runnable() { public void run() { // Select Ok option to hide dialog box in Event Dispatch Thread pageSetupOptionPane.setValue(JOptionPane.OK_OPTION); } }); assertFalse("Page setup dialog still showing", pageSetupDialog.isShowing()); PageFormat pageFormat = PrinterJob.getPrinterJob().defaultPage(); // Check home print attributes are modified accordingly assertHomePrintEqualPrintAttributes(pageFormat, true, false, true, home); // 4. Undo changes runAction(controller, HomePane.ActionType.UNDO); // Check home attributes have previous values assertEquals("Home print set", null, home.getPrint()); // Redo runAction(controller, HomePane.ActionType.REDO); // Check home attributes are modified accordingly assertHomePrintEqualPrintAttributes(pageFormat, true, false, true, home); // 5. Show print preview dialog box tester.invokeLater(new Runnable() { public void run() { // Display dialog box later in Event Dispatch Thread to avoid blocking test thread runAction(controller, HomePane.ActionType.PRINT_PREVIEW); } }); // Wait for print preview to be shown tester.waitForFrameShowing(new AWTHierarchy(), preferences.getLocalizedString( PrintPreviewPanel.class, "printPreview.title")); // Check dialog box is displayed JDialog printPreviewDialog = (JDialog)new BasicFinder().find(frame, new ClassMatcher (JDialog.class, true)); assertTrue("Print preview dialog not showing", printPreviewDialog.isShowing()); // Retrieve PageSetupPanel components PrintPreviewPanel printPreviewPanel = (PrintPreviewPanel)TestUtilities.findComponent( frame, PrintPreviewPanel.class); JToolBar toolBar = (JToolBar)TestUtilities.getField(printPreviewPanel, "toolBar"); JButton previousButton = (JButton)toolBar.getComponent(0); final JButton nextButton = (JButton)toolBar.getComponent(1); HomePrintableComponent printableComponent = (HomePrintableComponent)TestUtilities.getField(printPreviewPanel, "printableComponent");; // Check if buttons are enabled and if printable component displays the first page assertFalse("Previous button is enabled", previousButton.isEnabled()); assertTrue("Next button is disabled", nextButton.isEnabled()); assertEquals("Printable component doesn't display first page", 0, printableComponent.getPage()); assertEquals("Wrong printable component page count", 2, printableComponent.getPageCount()); // 6. Click on next page button tester.invokeAndWait(new Runnable() { public void run() { nextButton.doClick(); } }); // Check if buttons are enabled and if printable component displays the second page assertTrue("Previous button is enabled", previousButton.isEnabled()); assertFalse("Next button is disabled", nextButton.isEnabled()); assertEquals("Printable component doesn't display second page", 1, printableComponent.getPage()); // Click on Ok in dialog box final JOptionPane printPreviewOptionPane = (JOptionPane)TestUtilities.findComponent( printPreviewDialog, JOptionPane.class); tester.invokeAndWait(new Runnable() { public void run() { // Select Ok option to hide dialog box in Event Dispatch Thread printPreviewOptionPane.setValue(JOptionPane.OK_OPTION); } }); assertFalse("Print preview dialog still showing", printPreviewDialog.isShowing()); // 7. Check the created PDF file doesn't exist String pdfFileBase = "testsdfghjk"; File pdfFile = new File(pdfFileBase + ".pdf"); assertFalse("PDF file already exists, delete it first", pdfFile.exists()); // Show print to PDF dialog box tester.invokeLater(new Runnable() { public void run() { // Display dialog box later in Event Dispatch Thread to avoid blocking test thread runAction(controller, HomePane.ActionType.PRINT_TO_PDF); } }); // Wait for print to PDF file chooser to be shown tester.waitForFrameShowing(new AWTHierarchy(), preferences.getLocalizedString( HomePane.class, "printToPDFDialog.title")); // Check dialog box is displayed final Dialog printToPdfDialog = (Dialog)new BasicFinder().find(frame, new ClassMatcher (Dialog.class, true)); assertTrue("Print to pdf dialog not showing", printToPdfDialog.isShowing()); // Change file in print to PDF file chooser final JFileChooserTester fileChooserTester = new JFileChooserTester(); final JFileChooser fileChooser = (JFileChooser)new BasicFinder().find(printToPdfDialog, new ClassMatcher(JFileChooser.class)); fileChooserTester.actionSetDirectory(fileChooser, System.getProperty("user.dir")); fileChooserTester.actionSetFilename(fileChooser, pdfFileBase); // Select Ok option to hide dialog box fileChooserTester.actionApprove(fileChooser); // Wait PDF generation Thread.sleep(2000); assertFalse("Print to pdf dialog still showing", printToPdfDialog.isShowing()); assertTrue("PDF file doesn't exist", pdfFile.exists()); assertTrue("PDF file is empty", pdfFile.length() > 0); pdfFile.delete(); }
diff --git a/jsword/src/main/java/org/crosswire/jsword/passage/AccuracyType.java b/jsword/src/main/java/org/crosswire/jsword/passage/AccuracyType.java index 210fa0e9..5513e1aa 100644 --- a/jsword/src/main/java/org/crosswire/jsword/passage/AccuracyType.java +++ b/jsword/src/main/java/org/crosswire/jsword/passage/AccuracyType.java @@ -1,817 +1,817 @@ /** * Distribution License: * JSword is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License, version 2.1 as published by * the Free Software Foundation. This program is distributed in the hope * that it will be useful, but WITHOUT ANY WARRANTY; without even the * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * The License is available on the internet at: * http://www.gnu.org/copyleft/lgpl.html * or by writing to: * Free Software Foundation, Inc. * 59 Temple Place - Suite 330 * Boston, MA 02111-1307, USA * * Copyright: 2005 * The copyright to this program is held by it's authors. * * ID: $Id$ */ package org.crosswire.jsword.passage; import java.io.Serializable; import org.crosswire.jsword.versification.BibleInfo; /** * Types of Accuracy for verse references. * For example: * <ul> * <li>Gen == BOOK_ONLY; * <li>Gen 1 == BOOK_CHAPTER; * <li>Gen 1:1 == BOOK_VERSE; * <li>Jude 1 == BOOK_VERSE; * <li>Jude 1:1 == BOOK_VERSE; * <li>1:1 == CHAPTER_VERSE; * <li>10 == BOOK_ONLY, CHAPTER_ONLY, or VERSE_ONLY * <ul> * * With the last one, you will note that there is a choice. By itself there is not * enough information to determine which one it is. There has to be a context in * which it is used. * <p> * It may be found in a verse range like: Gen 1:2 - 10. In this case the context of 10 * is Gen 1:2, which is BOOK_VERSE. So in this case, 10 is VERSE_ONLY. * <p> * If it is at the beginning of a range like 10 - 22:3, it has to have more context. * If the context is a prior entry like Gen 2:5, 10 - 22:3, then its context is Gen 2:5, * which is BOOK_VERSE and 10 is VERSE_ONLY. * <p> * However if it is Gen 2, 10 - 22:3 then the context is Gen 2, BOOK_CHAPTER so 10 is * understood as BOOK_CHAPTER. * <p> * As a special case, if the preceeding range is an entire chapter or book then 10 would * understood as CHAPTER_ONLY or BOOK_ONLY (respectively) * <p> * If the number has no preceeding context, then it is understood as being BOOK_ONLY. * <p> * In all of these examples, the start verse was being interpreted. In the case of a * verse that is the end of a range, it is interpreted in the context of the range's * start. * * @see gnu.lgpl.License for license details. * The copyright to this program is held by it's authors. * @author Joe Walker [joe at eireneh dot com] * @author DM Smith [dmsmith555 at yahoo dot com] */ public abstract class AccuracyType implements Serializable { /** * The verse was specified as book, chapter and verse. For example, Gen 1:1, Jude 3 (which only has one chapter) */ public static final AccuracyType BOOK_VERSE = new AccuracyType("BOOK_VERSE") //$NON-NLS-1$ { /* (non-Javadoc) * @see org.crosswire.jsword.passage.AccuracyType#isVerse() */ public boolean isVerse() { return true; } /* (non-Javadoc) * @see org.crosswire.jsword.passage.AccuracyType#createStartVerse(java.lang.String, org.crosswire.jsword.passage.VerseRange, java.lang.String[]) */ public Verse createStartVerse(String original, VerseRange verseRangeBasis, String[] parts) throws NoSuchVerseException { int book = BibleInfo.getBookNumber(parts[0]); int chapter = 1; int verse = 1; if (parts.length == 3) { chapter = getChapter(book, parts[1]); verse = getVerse(book, chapter, parts[2]); } else { // Some books only have 1 chapter verse = getVerse(book, chapter, parts[1]); } return new Verse(original, book, chapter, verse); } /* (non-Javadoc) * @see org.crosswire.jsword.passage.AccuracyType#createEndVerse(java.lang.String, org.crosswire.jsword.passage.Verse, java.lang.String[]) */ public Verse createEndVerse(String endVerseDesc, Verse verseBasis, String[] endParts) throws NoSuchVerseException { // A fully specified verse is the same regardless of whether it is a start or an end to a range. return createStartVerse(endVerseDesc, null, endParts); } /** * Serialization ID */ private static final long serialVersionUID = 3256719589483165495L; }; /** * The passage was specified to a book and chapter (no verse). For example, Gen 1 */ public static final AccuracyType BOOK_CHAPTER = new AccuracyType("BOOK_CHAPTER") //$NON-NLS-1$ { /* (non-Javadoc) * @see org.crosswire.jsword.passage.AccuracyType#isChapter() */ public boolean isChapter() { return true; } /* (non-Javadoc) * @see org.crosswire.jsword.passage.AccuracyType#createStartVerse(java.lang.String, org.crosswire.jsword.passage.VerseRange, java.lang.String[]) */ public Verse createStartVerse(String original, VerseRange verseRangeBasis, String[] parts) throws NoSuchVerseException { int book = BibleInfo.getBookNumber(parts[0]); int chapter = getChapter(book, parts[1]); int verse = 1; return new Verse(original, book, chapter, verse); } /* (non-Javadoc) * @see org.crosswire.jsword.passage.AccuracyType#createEndVerse(java.lang.String, org.crosswire.jsword.passage.Verse, java.lang.String[]) */ public Verse createEndVerse(String endVerseDesc, Verse verseBasis, String[] endParts) throws NoSuchVerseException { // Very similar to the start verse but we want the end of the chapter Verse end = createStartVerse(endVerseDesc, null, endParts); // except that this gives us end at verse 1, and not the book end return end.getLastVerseInChapter(); } /** * Serialization ID */ private static final long serialVersionUID = 3258125864737911609L; }; /** * The passage was specified to a book only (no chapter or verse). For example, Gen */ public static final AccuracyType BOOK_ONLY = new AccuracyType("BOOK_ONLY") //$NON-NLS-1$ { /* (non-Javadoc) * @see org.crosswire.jsword.passage.AccuracyType#isBook() */ public boolean isBook() { return true; } /* (non-Javadoc) * @see org.crosswire.jsword.passage.AccuracyType#createStartVerse(java.lang.String, org.crosswire.jsword.passage.VerseRange, java.lang.String[]) */ public Verse createStartVerse(String original, VerseRange verseRangeBasis, String[] parts) throws NoSuchVerseException { int book = BibleInfo.getBookNumber(parts[0]); return new Verse(original, book, 1, 1); } /* (non-Javadoc) * @see org.crosswire.jsword.passage.AccuracyType#createEndVerse(java.lang.String, org.crosswire.jsword.passage.Verse, java.lang.String[]) */ public Verse createEndVerse(String endVerseDesc, Verse verseBasis, String[] endParts) throws NoSuchVerseException { // And we end with a book, so we need to encompass the lot // For example "Gen 3-Exo" // Very similar to the start verse but we want the end of the book Verse end = createStartVerse(endVerseDesc, null, endParts); // except that this gives us end at 1:1, and not the book end return end.getLastVerseInBook(); } /** * Serialization ID */ private static final long serialVersionUID = 4050486707419821620L; }; /** * The passage was specified to a chapter and verse (no book). For example, 1:1 */ public static final AccuracyType CHAPTER_VERSE = new AccuracyType("CHAPTER_VERSE") //$NON-NLS-1$ { /* (non-Javadoc) * @see org.crosswire.jsword.passage.AccuracyType#isVerse() */ public boolean isVerse() { return true; } /* (non-Javadoc) * @see org.crosswire.jsword.passage.AccuracyType#createStartVerse(java.lang.String, org.crosswire.jsword.passage.VerseRange, java.lang.String[]) */ public Verse createStartVerse(String original, VerseRange verseRangeBasis, String[] parts) throws NoSuchVerseException { if (verseRangeBasis == null) { throw new NoSuchVerseException(Msg.ACCURACY_BOOK); } int book = verseRangeBasis.getEnd().getBook(); int chapter = getChapter(book, parts[0]); int verse = getVerse(book, chapter, parts[1]); return new Verse(original, book, chapter, verse); } /* (non-Javadoc) * @see org.crosswire.jsword.passage.AccuracyType#createEndVerse(java.lang.String, org.crosswire.jsword.passage.Verse, java.lang.String[]) */ public Verse createEndVerse(String endVerseDesc, Verse verseBasis, String[] endParts) throws NoSuchVerseException { // Very similar to the start verse but use the verse as a basis int book = verseBasis.getBook(); int chapter = getChapter(book, endParts[0]); int verse = getVerse(book, chapter, endParts[1]); return new Verse(endVerseDesc, book, chapter, verse); } /** * Serialization ID */ private static final long serialVersionUID = 3691040958808668471L; }; /** * There was only a chapter number */ public static final AccuracyType CHAPTER_ONLY = new AccuracyType("CHAPTER_ONLY") //$NON-NLS-1$ { /* (non-Javadoc) * @see org.crosswire.jsword.passage.AccuracyType#isChapter() */ public boolean isChapter() { return true; } /* (non-Javadoc) * @see org.crosswire.jsword.passage.AccuracyType#createStartVerse(java.lang.String, org.crosswire.jsword.passage.VerseRange, java.lang.String[]) */ public Verse createStartVerse(String original, VerseRange verseRangeBasis, String[] parts) throws NoSuchVerseException { if (verseRangeBasis == null) { throw new NoSuchVerseException(Msg.ACCURACY_BOOK); } int book = verseRangeBasis.getEnd().getBook(); int chapter = getChapter(book, parts[0]); return new Verse(original, book, chapter, 1); } /* (non-Javadoc) * @see org.crosswire.jsword.passage.AccuracyType#createEndVerse(java.lang.String, org.crosswire.jsword.passage.Verse, java.lang.String[]) */ public Verse createEndVerse(String endVerseDesc, Verse verseBasis, String[] endParts) throws NoSuchVerseException { // Very similar to the start verse but use the verse as a basis // and it gets the end of the chapter int book = verseBasis.getBook(); int chapter = getChapter(book, endParts[0]); return new Verse(endVerseDesc, book, chapter, 1).getLastVerseInChapter(); } /** * Serialization ID */ private static final long serialVersionUID = 3689918357520463409L; }; /** * There was only a verse number */ public static final AccuracyType VERSE_ONLY = new AccuracyType("VERSE_ONLY") //$NON-NLS-1$ { /* (non-Javadoc) * @see org.crosswire.jsword.passage.AccuracyType#isVerse() */ public boolean isVerse() { return true; } /* (non-Javadoc) * @see org.crosswire.jsword.passage.AccuracyType#createStartVerse(java.lang.String, org.crosswire.jsword.passage.VerseRange, java.lang.String[]) */ public Verse createStartVerse(String original, VerseRange verseRangeBasis, String[] parts) throws NoSuchVerseException { if (verseRangeBasis == null) { throw new NoSuchVerseException(Msg.ACCURACY_BOOK_CHAPTER); } int book = verseRangeBasis.getEnd().getBook(); int chapter = verseRangeBasis.getEnd().getChapter(); int verse = getVerse(book, chapter, parts[0]); return new Verse(original, book, chapter, verse); } /* (non-Javadoc) * @see org.crosswire.jsword.passage.AccuracyType#createEndVerse(java.lang.String, org.crosswire.jsword.passage.Verse, java.lang.String[]) */ public Verse createEndVerse(String endVerseDesc, Verse verseBasis, String[] endParts) throws NoSuchVerseException { // Very similar to the start verse but use the verse as a basis // and it gets the end of the chapter int book = verseBasis.getBook(); int chapter = verseBasis.getChapter(); int verse = getVerse(book, chapter, endParts[0]); return new Verse(endVerseDesc, book, chapter, verse); } /** * Serialization ID */ private static final long serialVersionUID = 3691034361722320178L; }; /** * Simple ctor */ public AccuracyType(String name) { this.name = name; } /** * @param original the original verse reference as a string * @param verseRangeBasis the range that stood before the string reference * @param parts a tokenized version of the original * @return a <code>Verse</code> for the original * @throws NoSuchVerseException */ public abstract Verse createStartVerse(String original, VerseRange verseRangeBasis, String[] parts) throws NoSuchVerseException; /** * @param endVerseDesc the original verse reference as a string * @param verseBasis the verse at the beginning of the range * @param endParts a tokenized version of the original * @return a <code>Verse</code> for the original * @throws NoSuchVerseException */ public abstract Verse createEndVerse(String endVerseDesc, Verse verseBasis, String[] endParts) throws NoSuchVerseException; /** * @return true if this AccuracyType specifies down to the book but not chapter or verse. */ public boolean isBook() { return false; } /** * @return true if this AccuracyType specifies down to the chapter but not the verse. */ public boolean isChapter() { return false; } /** * @return true if this AccuracyType specifies down to the verse. */ public boolean isVerse() { return false; } /** * Interprets the chapter value, which is either a number or "ff" or "$" (meaning "what follows") * @param lbook the integer representation of the book * @param chapter a string representation of the chapter. May be "ff" or "$" for "what follows". * @return the number of the chapter * @throws NoSuchVerseException */ public static final int getChapter(int lbook, String chapter) throws NoSuchVerseException { if (isEndMarker(chapter)) { return BibleInfo.chaptersInBook(lbook); } return parseInt(chapter); } /** * Interprets the verse value, which is either a number or "ff" or "$" (meaning "what follows") * @param lbook the integer representation of the book * @param lchapter the integer representation of the chapter * @param verse the string representation of the verse * @return the number of the verse * @throws NoSuchVerseException */ public static final int getVerse(int lbook, int lchapter, String verse) throws NoSuchVerseException { if (isEndMarker(verse)) { return BibleInfo.versesInChapter(lbook, lchapter); } return parseInt(verse); } /** * Get an integer representation for this RestrictionType */ public int toInteger() { for (int i = 0; i < VALUES.length; i++) { if (equals(VALUES[i])) { return i; } } // cannot get here assert false; return -1; } /** * Determine how closely the string defines a verse. * @param original * @param parts is a reference split into parts * @return what is the kind of accuracy of the string reference. * @throws NoSuchVerseException */ public static AccuracyType fromText(String original, String[] parts) throws NoSuchVerseException { return fromText(original, parts, null, null); } /** * @param original * @param parts * @param verseAccuracy * @return the accuracy of the parts * @throws NoSuchVerseException */ public static AccuracyType fromText(String original, String[] parts, AccuracyType verseAccuracy) throws NoSuchVerseException { return fromText(original, parts, verseAccuracy, null); } /** * @param original * @param parts * @param basis * @return the accuracy of the parts * @throws NoSuchVerseException */ public static AccuracyType fromText(String original, String[] parts, VerseRange basis) throws NoSuchVerseException { return fromText(original, parts, null, basis); } /** * Does this string exactly define a Verse. For example:<ul> * <li>fromText("Gen") == AccuracyType.BOOK_ONLY; * <li>fromText("Gen 1:1") == AccuracyType.BOOK_VERSE; * <li>fromText("Gen 1") == AccuracyType.BOOK_CHAPTER; * <li>fromText("Jude 1") == AccuracyType.BOOK_VERSE; * <li>fromText("Jude 1:1") == AccuracyType.BOOK_VERSE; * <li>fromText("1:1") == AccuracyType.CHAPTER_VERSE; * <li>fromText("1") == AccuracyType.VERSE_ONLY; * <ul> * @param parts * @param verseAccuracy * @param basis * @return the accuracy of the parts * @throws NoSuchVerseException */ public static AccuracyType fromText(String original, String[] parts, AccuracyType verseAccuracy, VerseRange basis) throws NoSuchVerseException { switch (parts.length) { case 1: if (BibleInfo.isBookName(parts[0])) { return BOOK_ONLY; } // At this point we should have a number. // But double check it checkValidChapterOrVerse(parts[0]); // What it is depends upon what stands before it. if (verseAccuracy != null) { if (verseAccuracy.isVerse()) { return VERSE_ONLY; } if (verseAccuracy.isChapter()) { return CHAPTER_ONLY; } } if (basis != null) { if (basis.isWholeChapter()) { return CHAPTER_ONLY; } return VERSE_ONLY; } throw buildVersePartsException(original, parts); case 2: // Does it start with a book? int pbook = BibleInfo.getBookNumber(parts[0]); if (pbook == -1) { checkValidChapterOrVerse(parts[0]); checkValidChapterOrVerse(parts[1]); return CHAPTER_VERSE; } if (BibleInfo.chaptersInBook(pbook) == 1) { return BOOK_VERSE; } return BOOK_CHAPTER; case 3: if (BibleInfo.getBookNumber(parts[0]) != -1) { checkValidChapterOrVerse(parts[1]); checkValidChapterOrVerse(parts[2]); return BOOK_VERSE; } throw buildVersePartsException(original, parts); default: throw buildVersePartsException(original, parts); } } private static NoSuchVerseException buildVersePartsException(String original, String[] parts) { StringBuffer buffer = new StringBuffer(original); for (int i = 0; i < parts.length; i++) { buffer.append(", ").append(parts[i]); //$NON-NLS-1$ } return new NoSuchVerseException(Msg.VERSE_PARTS, new Object[] { buffer.toString() }); } /** * Is this text valid in a chapter/verse context * @param text The string to test for validity * @throws NoSuchVerseException If the text is invalid */ private static void checkValidChapterOrVerse(String text) throws NoSuchVerseException { if (!isEndMarker(text)) { parseInt(text); } } /** * This is simply a convenience function to wrap Integer.parseInt() * and give us a reasonable exception on failure. It is called by * VerseRange hence protected, however I would prefer private * @param text The string to be parsed * @return The correctly parsed chapter or verse * @exception NoSuchVerseException If the reference is illegal */ private static int parseInt(String text) throws NoSuchVerseException { try { return Integer.parseInt(text); } catch (NumberFormatException ex) { throw new NoSuchVerseException(Msg.VERSE_PARSE, new Object[] { text }); } } /** * Is this string a legal marker for 'to the end of the chapter' * @param text The string to be checked * @return true if this is a legal marker */ private static boolean isEndMarker(String text) { if (text.equals(AccuracyType.VERSE_END_MARK1)) { return true; } if (text.equals(AccuracyType.VERSE_END_MARK2)) { return true; } return false; } /** * Take a string representation of a verse and parse it into * an Array of Strings where each part is likely to be a verse part. * The goal is to allow the greatest possible variations in user input. * <p>Parts can be separated by pretty much anything. No distinction * is made between them. While chapter and verse need to be separated, * a separator is assumed between digits and non-digits. Adjacent words, * (i.e. sequences of non-digits) are understood to be a book reference. * If a number runs up against a book name, it is considered to be either * part of the book name (i.e. it is before it) or a chapter number (i.e. * it stands after it.)</p> * <p>Note: ff and $ are considered to be digits.</p> * <p>Note: it is not necessary for this to be a BCV (book, chapter, verse), * it may just be BC, B, C, V or CV. No distinction is needed here for a * number that stands alone.</p> * @param input The string to parse. * @return The string array * @throws NoSuchVerseException */ public static String[] tokenize(String input) throws NoSuchVerseException { // The results are expected to be no more than 3 parts String [] args = { null, null, null, null, null, null, null, null}; // Normalize the input by replacing non-digits and non-letters with spaces. int length = input.length(); // Create an output array big enough to add ' ' where needed char [] normalized = new char [length * 2]; char lastChar = '0'; // start with a digit so normalized won't start with a space char curChar = ' '; // can be anything int tokenCount = 0; int normalizedLength = 0; int startIndex = 0; String token = null; boolean foundBoundary = false; for (int i = 0; i < length; i++) { curChar = input.charAt(i); - boolean charIsDigit = curChar == '$' || Character.isDigit(curChar) || (curChar == 'f' && (i + 1 < length ? input.charAt(i + 1) : ' ') == 'f'); + boolean charIsDigit = curChar == '$' || Character.isDigit(curChar) || (curChar == 'f' && (i + 1 < length ? input.charAt(i + 1) : ' ') == 'f' && !Character.isLetter(lastChar)); if (charIsDigit || Character.isLetter(curChar)) { foundBoundary = true; boolean charWasDigit = lastChar == '$' || Character.isDigit(lastChar) || (lastChar == 'f' && (i > 2 ? input.charAt(i - 2) : '0') == 'f'); if (charWasDigit || Character.isLetter(lastChar)) { foundBoundary = false; // Replace transitions between digits and letters with spaces. if (normalizedLength > 0 && charWasDigit != charIsDigit) { foundBoundary = true; } } if (foundBoundary) { // On a boundary: // Digits always start a new token // Letters always continue a previous token if (charIsDigit) { if (tokenCount >= args.length) { throw new NoSuchVerseException(Msg.VERSE_PARTS, new Object[] { input }); } token = new String(normalized, startIndex, normalizedLength - startIndex); args[tokenCount++] = token; normalizedLength = 0; } else { normalized[normalizedLength++] = ' '; } } normalized[normalizedLength++] = curChar; } // Until the first character is copied, there is no last char if (normalizedLength > 0) { lastChar = curChar; } } if (tokenCount >= args.length) { throw new NoSuchVerseException(Msg.VERSE_PARTS, new Object[] { input }); } token = new String(normalized, startIndex, normalizedLength - startIndex); args[tokenCount++] = token; String [] results = new String [tokenCount]; System.arraycopy(args, 0, results, 0, tokenCount); return results; } /** * Lookup method to convert from a String * @param name the name of the AccuracyType * @return the AccuracyType */ public static AccuracyType fromString(String name) { for (int i = 0; i < VALUES.length; i++) { AccuracyType o = VALUES[i]; if (o.name.equalsIgnoreCase(name)) { return o; } } // cannot get here assert false; return null; } /** * Lookup method to convert from an integer * @param i the i-th AccuracyType * @return the AccuracyType */ public static AccuracyType fromInteger(int i) { return VALUES[i]; } /** * Prevent subclasses from overriding canonical identity based Object methods * @see java.lang.Object#equals(java.lang.Object) */ public final boolean equals(Object o) { return super.equals(o); } /** * Prevent subclasses from overriding canonical identity based Object methods * @see java.lang.Object#hashCode() */ public final int hashCode() { return super.hashCode(); } /* (non-Javadoc) * @see java.lang.Object#toString() */ public String toString() { return name; } /** * What characters can we use to separate parts to a verse */ public static final String VERSE_ALLOWED_DELIMS = " :."; //$NON-NLS-1$ /** * The name of the object */ private String name; // Support for serialization private static int nextObj; private final int obj = nextObj++; Object readResolve() { return VALUES[obj]; } private static final AccuracyType[] VALUES = { BOOK_CHAPTER, BOOK_VERSE, BOOK_ONLY, CHAPTER_VERSE, VERSE_ONLY, }; /** * Characters that are used to indicate end of verse/chapter, part 1 */ public static final String VERSE_END_MARK1 = "$"; //$NON-NLS-1$ /** * Characters that are used to indicate end of verse/chapter, part 2 */ public static final String VERSE_END_MARK2 = "ff"; //$NON-NLS-1$ }
true
true
public static String[] tokenize(String input) throws NoSuchVerseException { // The results are expected to be no more than 3 parts String [] args = { null, null, null, null, null, null, null, null}; // Normalize the input by replacing non-digits and non-letters with spaces. int length = input.length(); // Create an output array big enough to add ' ' where needed char [] normalized = new char [length * 2]; char lastChar = '0'; // start with a digit so normalized won't start with a space char curChar = ' '; // can be anything int tokenCount = 0; int normalizedLength = 0; int startIndex = 0; String token = null; boolean foundBoundary = false; for (int i = 0; i < length; i++) { curChar = input.charAt(i); boolean charIsDigit = curChar == '$' || Character.isDigit(curChar) || (curChar == 'f' && (i + 1 < length ? input.charAt(i + 1) : ' ') == 'f'); if (charIsDigit || Character.isLetter(curChar)) { foundBoundary = true; boolean charWasDigit = lastChar == '$' || Character.isDigit(lastChar) || (lastChar == 'f' && (i > 2 ? input.charAt(i - 2) : '0') == 'f'); if (charWasDigit || Character.isLetter(lastChar)) { foundBoundary = false; // Replace transitions between digits and letters with spaces. if (normalizedLength > 0 && charWasDigit != charIsDigit) { foundBoundary = true; } } if (foundBoundary) { // On a boundary: // Digits always start a new token // Letters always continue a previous token if (charIsDigit) { if (tokenCount >= args.length) { throw new NoSuchVerseException(Msg.VERSE_PARTS, new Object[] { input }); } token = new String(normalized, startIndex, normalizedLength - startIndex); args[tokenCount++] = token; normalizedLength = 0; } else { normalized[normalizedLength++] = ' '; } } normalized[normalizedLength++] = curChar; } // Until the first character is copied, there is no last char if (normalizedLength > 0) { lastChar = curChar; } } if (tokenCount >= args.length) { throw new NoSuchVerseException(Msg.VERSE_PARTS, new Object[] { input }); } token = new String(normalized, startIndex, normalizedLength - startIndex); args[tokenCount++] = token; String [] results = new String [tokenCount]; System.arraycopy(args, 0, results, 0, tokenCount); return results; }
public static String[] tokenize(String input) throws NoSuchVerseException { // The results are expected to be no more than 3 parts String [] args = { null, null, null, null, null, null, null, null}; // Normalize the input by replacing non-digits and non-letters with spaces. int length = input.length(); // Create an output array big enough to add ' ' where needed char [] normalized = new char [length * 2]; char lastChar = '0'; // start with a digit so normalized won't start with a space char curChar = ' '; // can be anything int tokenCount = 0; int normalizedLength = 0; int startIndex = 0; String token = null; boolean foundBoundary = false; for (int i = 0; i < length; i++) { curChar = input.charAt(i); boolean charIsDigit = curChar == '$' || Character.isDigit(curChar) || (curChar == 'f' && (i + 1 < length ? input.charAt(i + 1) : ' ') == 'f' && !Character.isLetter(lastChar)); if (charIsDigit || Character.isLetter(curChar)) { foundBoundary = true; boolean charWasDigit = lastChar == '$' || Character.isDigit(lastChar) || (lastChar == 'f' && (i > 2 ? input.charAt(i - 2) : '0') == 'f'); if (charWasDigit || Character.isLetter(lastChar)) { foundBoundary = false; // Replace transitions between digits and letters with spaces. if (normalizedLength > 0 && charWasDigit != charIsDigit) { foundBoundary = true; } } if (foundBoundary) { // On a boundary: // Digits always start a new token // Letters always continue a previous token if (charIsDigit) { if (tokenCount >= args.length) { throw new NoSuchVerseException(Msg.VERSE_PARTS, new Object[] { input }); } token = new String(normalized, startIndex, normalizedLength - startIndex); args[tokenCount++] = token; normalizedLength = 0; } else { normalized[normalizedLength++] = ' '; } } normalized[normalizedLength++] = curChar; } // Until the first character is copied, there is no last char if (normalizedLength > 0) { lastChar = curChar; } } if (tokenCount >= args.length) { throw new NoSuchVerseException(Msg.VERSE_PARTS, new Object[] { input }); } token = new String(normalized, startIndex, normalizedLength - startIndex); args[tokenCount++] = token; String [] results = new String [tokenCount]; System.arraycopy(args, 0, results, 0, tokenCount); return results; }
diff --git a/KeywordSearch/src/org/sleuthkit/autopsy/keywordsearch/Ingester.java b/KeywordSearch/src/org/sleuthkit/autopsy/keywordsearch/Ingester.java index 575044726..f9d655630 100755 --- a/KeywordSearch/src/org/sleuthkit/autopsy/keywordsearch/Ingester.java +++ b/KeywordSearch/src/org/sleuthkit/autopsy/keywordsearch/Ingester.java @@ -1,326 +1,326 @@ /* * Autopsy Forensic Browser * * Copyright 2011 Basis Technology Corp. * Contact: carrier <at> sleuthkit <dot> org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sleuthkit.autopsy.keywordsearch; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.solr.client.solrj.SolrRequest.METHOD; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.request.AbstractUpdateRequest; import org.apache.solr.client.solrj.request.ContentStreamUpdateRequest; import org.apache.solr.common.SolrException; import org.apache.solr.common.SolrException.ErrorCode; import org.apache.solr.common.util.ContentStream; import org.sleuthkit.datamodel.FsContent; import org.sleuthkit.datamodel.ReadContentInputStream; /** * Handles indexing files on a Solr core. */ class Ingester { private static final Logger logger = Logger.getLogger(Ingester.class.getName()); private boolean uncommitedIngests = false; private final ExecutorService upRequestExecutor = Executors.newSingleThreadExecutor(); private final Server solrServer = KeywordSearch.getServer(); // TODO: use a more robust method than checking file extension // supported extensions list from http://www.lucidimagination.com/devzone/technical-articles/content-extraction-tika static final String[] ingestibleExtensions = {"tar", "jar", "zip", "gzip", "bzip2", "gz", "tgz", "odf", "doc", "xls", "ppt", "rtf", "pdf", "html", "htm", "xhtml", "txt", "log", "manifest", "bmp", "gif", "png", "jpeg", "tiff", "mp3", "aiff", "au", "midi", "wav", "pst", "xml", "class", "dwg", "eml", "emlx", "mbox", "mht"}; Ingester() { } @Override @SuppressWarnings("FinalizeDeclaration") protected void finalize() throws Throwable { super.finalize(); // Warn if files might have been left uncommited. if (uncommitedIngests) { logger.warning("Ingester was used to add files that it never committed."); } } /** * Sends a file to Solr to have its content extracted and added to the * index. commit() should be called once you're done ingesting files. * * @param fcs File FsContentStringStream to ingest * @throws IngesterException if there was an error processing a specific * file, but the Solr server is probably fine. */ public void ingest(FsContentStringContentStream fcs) throws IngesterException { Map<String, String> params = getFsContentFields(fcs.getFsContent()); ingest(fcs, params, fcs.getFsContent()); } /** * Sends a file to Solr to have its content extracted and added to the * index. commit() should be called once you're done ingesting files. * * @param f File to ingest * @throws IngesterException if there was an error processing a specific * file, but the Solr server is probably fine. */ public void ingest(FsContent f) throws IngesterException { ingest(new FscContentStream(f), getFsContentFields(f), f); } /** * Creates a field map from FsContent, that is later sent to Solr * @param fsc FsContent to get fields from * @return the map */ private Map<String, String> getFsContentFields(FsContent fsc) { Map<String, String> fields = new HashMap<String, String>(); fields.put("id", Long.toString(fsc.getId())); fields.put("file_name", fsc.getName()); fields.put("ctime", fsc.getCtimeAsDate()); fields.put("atime", fsc.getAtimeAsDate()); fields.put("mtime", fsc.getMtimeAsDate()); fields.put("crtime", fsc.getMtimeAsDate()); return fields; } /** * Common delegate method actually doing the work for objects implementing ContentStream * * @param ContentStream to ingest * @param fields content specific fields * @param sourceContent fsContent from which the cs content stream originated from * @throws IngesterException if there was an error processing a specific * content, but the Solr server is probably fine. */ private void ingest(ContentStream cs, Map<String, String> fields, final FsContent sourceContent) throws IngesterException { final ContentStreamUpdateRequest up = new ContentStreamUpdateRequest("/update/extract"); up.addContentStream(cs); setFields(up, fields); up.setAction(AbstractUpdateRequest.ACTION.COMMIT, true, true); final String contentType = cs.getContentType(); if (contentType != null && !contentType.trim().equals("")) { up.setParam("stream.contentType", contentType); } //logger.log(Level.INFO, "Ingesting " + fields.get("file_name")); up.setParam("commit", "false"); - final Future f = upRequestExecutor.submit(new UpRequestTask(up)); + final Future<?> f = upRequestExecutor.submit(new UpRequestTask(up)); try { f.get(getTimeout(sourceContent), TimeUnit.SECONDS); } catch (TimeoutException te) { logger.log(Level.WARNING, "Solr timeout encountered, trying to restart Solr"); //restart may be needed to recover from some error conditions hardSolrRestart(); throw new IngesterException("Solr index request time out for id: " + fields.get("id") + ", name: " + fields.get("file_name")); } catch (Exception e) { throw new IngesterException("Problem posting content to Solr, id: " + fields.get("id") + ", name: " + fields.get("file_name"), e); } uncommitedIngests = true; } /** * attempt to restart Solr and recover from its internal error */ private void hardSolrRestart() { solrServer.closeCore(); solrServer.stop(); solrServer.start(); solrServer.openCore(); } /** * return timeout that should be use to index the content * TODO adjust them more as needed, and handle file chunks * @param f the source FsContent * @return time in seconds to use a timeout */ private static int getTimeout(FsContent f) { final long size = f.getSize(); if (size < 1024 * 1024L) //1MB { return 60; } else if (size < 10 * 1024 * 1024L) //10MB { return 1200; } else if (size < 100 * 1024 * 1024L) //100MB { return 3600; } else { return 3 * 3600; } } private class UpRequestTask implements Runnable { ContentStreamUpdateRequest up; UpRequestTask(ContentStreamUpdateRequest up) { this.up = up; } @Override public void run() { try { up.setMethod(METHOD.POST); solrServer.request(up); } catch (NoOpenCoreException ex) { throw new RuntimeException("No Solr core available, cannot index the content", ex); } catch (IllegalStateException ex) { // problems with content throw new RuntimeException("Problem reading file.", ex); } catch (SolrServerException ex) { // If there's a problem talking to Solr, something is fundamentally // wrong with ingest throw new RuntimeException("Problem with Solr", ex); } catch (SolrException ex) { // Tika problems result in an unchecked SolrException ErrorCode ec = ErrorCode.getErrorCode(ex.code()); // When Tika has problems with a document, it throws a server error // but it's okay to continue with other documents if (ec.equals(ErrorCode.SERVER_ERROR)) { throw new RuntimeException("Problem posting file contents to Solr. SolrException error code: " + ec, ex); } else { // shouldn't get any other error codes throw ex; } } } } /** * Tells Solr to commit (necessary before ingested files will appear in * searches) */ void commit() { try { solrServer.commit(); uncommitedIngests = false; } catch (NoOpenCoreException ex) { logger.log(Level.WARNING, "Error commiting index", ex); } catch (SolrServerException ex) { logger.log(Level.WARNING, "Error commiting index", ex); } } /** * Helper to set document fields * @param up request with document * @param fields map of field-names->values */ private static void setFields(ContentStreamUpdateRequest up, Map<String, String> fields) { for (Entry<String, String> field : fields.entrySet()) { up.setParam("literal." + field.getKey(), field.getValue()); } } /** * ContentStream to read() the data from a FsContent object */ private static class FscContentStream implements ContentStream { FsContent f; FscContentStream(FsContent f) { this.f = f; } @Override public String getName() { return f.getName(); } @Override public String getSourceInfo() { return "File:" + f.getId(); } @Override public String getContentType() { return null; } @Override public Long getSize() { return f.getSize(); } @Override public InputStream getStream() throws IOException { return new ReadContentInputStream(f); } @Override public Reader getReader() throws IOException { throw new UnsupportedOperationException("Not supported yet."); } } /** * Indicates that there was an error with the specific ingest operation, * but it's still okay to continue ingesting files. */ static class IngesterException extends Exception { IngesterException(String message, Throwable ex) { super(message, ex); } IngesterException(String message) { super(message); } } /** * Determine if the fscontent is ingestible/indexable by keyword search * Note: currently only checks by extension, could be a more robust check. * @param fsContent * @return true if it is ingestible, false otherwise */ static boolean isIngestible(FsContent fsContent) { boolean ingestible = false; final String fileName = fsContent.getName(); for (String ext : ingestibleExtensions) { if (fileName.toLowerCase().endsWith(ext)) { ingestible = true; break; } } return ingestible; } }
true
true
private void ingest(ContentStream cs, Map<String, String> fields, final FsContent sourceContent) throws IngesterException { final ContentStreamUpdateRequest up = new ContentStreamUpdateRequest("/update/extract"); up.addContentStream(cs); setFields(up, fields); up.setAction(AbstractUpdateRequest.ACTION.COMMIT, true, true); final String contentType = cs.getContentType(); if (contentType != null && !contentType.trim().equals("")) { up.setParam("stream.contentType", contentType); } //logger.log(Level.INFO, "Ingesting " + fields.get("file_name")); up.setParam("commit", "false"); final Future f = upRequestExecutor.submit(new UpRequestTask(up)); try { f.get(getTimeout(sourceContent), TimeUnit.SECONDS); } catch (TimeoutException te) { logger.log(Level.WARNING, "Solr timeout encountered, trying to restart Solr"); //restart may be needed to recover from some error conditions hardSolrRestart(); throw new IngesterException("Solr index request time out for id: " + fields.get("id") + ", name: " + fields.get("file_name")); } catch (Exception e) { throw new IngesterException("Problem posting content to Solr, id: " + fields.get("id") + ", name: " + fields.get("file_name"), e); } uncommitedIngests = true; }
private void ingest(ContentStream cs, Map<String, String> fields, final FsContent sourceContent) throws IngesterException { final ContentStreamUpdateRequest up = new ContentStreamUpdateRequest("/update/extract"); up.addContentStream(cs); setFields(up, fields); up.setAction(AbstractUpdateRequest.ACTION.COMMIT, true, true); final String contentType = cs.getContentType(); if (contentType != null && !contentType.trim().equals("")) { up.setParam("stream.contentType", contentType); } //logger.log(Level.INFO, "Ingesting " + fields.get("file_name")); up.setParam("commit", "false"); final Future<?> f = upRequestExecutor.submit(new UpRequestTask(up)); try { f.get(getTimeout(sourceContent), TimeUnit.SECONDS); } catch (TimeoutException te) { logger.log(Level.WARNING, "Solr timeout encountered, trying to restart Solr"); //restart may be needed to recover from some error conditions hardSolrRestart(); throw new IngesterException("Solr index request time out for id: " + fields.get("id") + ", name: " + fields.get("file_name")); } catch (Exception e) { throw new IngesterException("Problem posting content to Solr, id: " + fields.get("id") + ", name: " + fields.get("file_name"), e); } uncommitedIngests = true; }
diff --git a/src/com/nadmm/airports/tfr/TfrListAdapter.java b/src/com/nadmm/airports/tfr/TfrListAdapter.java index b4b27fac..9d4c269b 100644 --- a/src/com/nadmm/airports/tfr/TfrListAdapter.java +++ b/src/com/nadmm/airports/tfr/TfrListAdapter.java @@ -1,88 +1,92 @@ /* * FlightIntel for Pilots * * Copyright 2012 Nadeem Hasan <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.nadmm.airports.tfr; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.nadmm.airports.R; import com.nadmm.airports.tfr.TfrList.Tfr; public class TfrListAdapter extends BaseAdapter { private LayoutInflater mInflater; private final TfrList mTfrList; private Context mContext; public TfrListAdapter( Context context, TfrList tfrList ) { mContext = context; mInflater = LayoutInflater.from( mContext ); mTfrList = tfrList; } @Override public int getCount() { return mTfrList.entries.size(); } @Override public Object getItem( int position ) { return mTfrList.entries.get( position ); } @Override public long getItemId( int position ) { return position; } @Override public boolean areAllItemsEnabled() { return true; } @Override public View getView( int position, View convertView, ViewGroup parent ) { if ( convertView == null ) { convertView = mInflater.inflate( R.layout.tfr_list_item, null ); } Tfr tfr = (Tfr) getItem( position ); - TextView tv = (TextView) convertView.findViewById( R.id.tfr_agency ); - tv.setText( tfr.notamId.substring( 0, tfr.notamId.indexOf( ' ' ) ) ); + TextView tv; + int index = tfr.notamId.indexOf( ' ' ); + if ( index > 0 ) { + tv = (TextView) convertView.findViewById( R.id.tfr_agency ); + tv.setText( tfr.notamId.substring( 0, index ) ); + } tv = (TextView) convertView.findViewById( R.id.tfr_name ); tv.setText( tfr.name ); tv = (TextView) convertView.findViewById( R.id.tfr_time ); tv.setText( tfr.formatTimeRange( mContext ) ); tv = (TextView) convertView.findViewById( R.id.tfr_active ); tv.setText( tfr.isExpired()? "Expired" : tfr.isActive()? "Active" : "Inactive" ); tv = (TextView) convertView.findViewById( R.id.tfr_type ); tv.setText( tfr.type ); tv = (TextView) convertView.findViewById( R.id.tfr_altitudes ); tv.setText( tfr.formatAltitudeRange() ); return convertView; } }
true
true
public View getView( int position, View convertView, ViewGroup parent ) { if ( convertView == null ) { convertView = mInflater.inflate( R.layout.tfr_list_item, null ); } Tfr tfr = (Tfr) getItem( position ); TextView tv = (TextView) convertView.findViewById( R.id.tfr_agency ); tv.setText( tfr.notamId.substring( 0, tfr.notamId.indexOf( ' ' ) ) ); tv = (TextView) convertView.findViewById( R.id.tfr_name ); tv.setText( tfr.name ); tv = (TextView) convertView.findViewById( R.id.tfr_time ); tv.setText( tfr.formatTimeRange( mContext ) ); tv = (TextView) convertView.findViewById( R.id.tfr_active ); tv.setText( tfr.isExpired()? "Expired" : tfr.isActive()? "Active" : "Inactive" ); tv = (TextView) convertView.findViewById( R.id.tfr_type ); tv.setText( tfr.type ); tv = (TextView) convertView.findViewById( R.id.tfr_altitudes ); tv.setText( tfr.formatAltitudeRange() ); return convertView; }
public View getView( int position, View convertView, ViewGroup parent ) { if ( convertView == null ) { convertView = mInflater.inflate( R.layout.tfr_list_item, null ); } Tfr tfr = (Tfr) getItem( position ); TextView tv; int index = tfr.notamId.indexOf( ' ' ); if ( index > 0 ) { tv = (TextView) convertView.findViewById( R.id.tfr_agency ); tv.setText( tfr.notamId.substring( 0, index ) ); } tv = (TextView) convertView.findViewById( R.id.tfr_name ); tv.setText( tfr.name ); tv = (TextView) convertView.findViewById( R.id.tfr_time ); tv.setText( tfr.formatTimeRange( mContext ) ); tv = (TextView) convertView.findViewById( R.id.tfr_active ); tv.setText( tfr.isExpired()? "Expired" : tfr.isActive()? "Active" : "Inactive" ); tv = (TextView) convertView.findViewById( R.id.tfr_type ); tv.setText( tfr.type ); tv = (TextView) convertView.findViewById( R.id.tfr_altitudes ); tv.setText( tfr.formatAltitudeRange() ); return convertView; }
diff --git a/src/powercrystals/minefactoryreloaded/modhelpers/biomesoplenty/BiomesOPlenty.java b/src/powercrystals/minefactoryreloaded/modhelpers/biomesoplenty/BiomesOPlenty.java index b39cd751..f311ff4b 100644 --- a/src/powercrystals/minefactoryreloaded/modhelpers/biomesoplenty/BiomesOPlenty.java +++ b/src/powercrystals/minefactoryreloaded/modhelpers/biomesoplenty/BiomesOPlenty.java @@ -1,136 +1,136 @@ package powercrystals.minefactoryreloaded.modhelpers.biomesoplenty; import powercrystals.minefactoryreloaded.MFRRegistry; import powercrystals.minefactoryreloaded.MineFactoryReloadedCore; import powercrystals.minefactoryreloaded.api.HarvestType; import powercrystals.minefactoryreloaded.api.MobDrop; import powercrystals.minefactoryreloaded.farmables.fertilizables.FertilizableSapling; import powercrystals.minefactoryreloaded.farmables.grindables.GrindableStandard; import powercrystals.minefactoryreloaded.farmables.harvestables.HarvestableStandard; import powercrystals.minefactoryreloaded.farmables.harvestables.HarvestableTreeLeaves; import powercrystals.minefactoryreloaded.farmables.plantables.PlantableStandard; import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import cpw.mods.fml.common.FMLLog; import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.Init; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.network.NetworkMod; @Mod(modid = "MineFactoryReloaded|CompatBiomesOPlenty", name = "MFR Compat: Biomes O' Plenty", version = MineFactoryReloadedCore.version, dependencies = "after:MineFactoryReloaded;after:BiomesOPlenty") @NetworkMod(clientSideRequired = false, serverSideRequired = false) public class BiomesOPlenty { @SuppressWarnings("rawtypes") @Init public static void load(FMLInitializationEvent ev) { if(!Loader.isModLoaded("BiomesOPlenty")) { FMLLog.warning("Biomes O' Plenty missing - MFR Biomes O' Plenty Compat not loading"); return; } try { // Biomes MFRRegistry.registerRubberTreeBiome("Bayou"); MFRRegistry.registerRubberTreeBiome("Birch Forest"); MFRRegistry.registerRubberTreeBiome("Bog"); MFRRegistry.registerRubberTreeBiome("Boreal Forest"); MFRRegistry.registerRubberTreeBiome("Deciduous Forest"); MFRRegistry.registerRubberTreeBiome("Forest"); MFRRegistry.registerRubberTreeBiome("Forest New"); MFRRegistry.registerRubberTreeBiome("ForestHills"); MFRRegistry.registerRubberTreeBiome("Grove"); MFRRegistry.registerRubberTreeBiome("Highland"); MFRRegistry.registerRubberTreeBiome("Jungle"); MFRRegistry.registerRubberTreeBiome("JungleHills"); MFRRegistry.registerRubberTreeBiome("Lush Swamp"); MFRRegistry.registerRubberTreeBiome("Maple Woods"); MFRRegistry.registerRubberTreeBiome("Marsh"); MFRRegistry.registerRubberTreeBiome("Moor"); MFRRegistry.registerRubberTreeBiome("Rainforest"); MFRRegistry.registerRubberTreeBiome("Seasonal Forest"); MFRRegistry.registerRubberTreeBiome("Shield"); MFRRegistry.registerRubberTreeBiome("Swampland"); MFRRegistry.registerRubberTreeBiome("Swampwoods"); MFRRegistry.registerRubberTreeBiome("Temperate Rainforest"); MFRRegistry.registerRubberTreeBiome("Thicket"); MFRRegistry.registerRubberTreeBiome("Tropical Rainforest"); MFRRegistry.registerRubberTreeBiome("Woodland"); String[] bopLeaves = {"acacia", "apple", "autumn", "bamboo", "dark", "dead", "blue", "fir", "holy", "mangrove", "orange", "origin", "palm", "pink", "red", "redwood", "white", "willow"}; - String[] bopLogs = {"acacia", "bamboo", "cherry", "dark", "dead", "fir", "holy", "magic", "mangrove", "palm", "redwood", "willow"}; + String[] bopLogs = {"acacia", "cherry", "dark", "dead", "fir", "holy", "magic", "mangrove", "palm", "redwood", "willow"}; String[] bopSaplings = {"acacia", "apple", "brown", "dark", "fir", "holy", "magic", "mangrove", "orange", "origin", "palm", "pink", "red", "redwood", "willow", "yellow"}; - String[] bopMiscTrunks = {"giantFlowerStem"}; + String[] bopMiscTrunks = {"giantFlowerStem", "bamboo"}; String[] bopMiscLeaves = {"appleLeavesFruitless", "treeMoss", "giantFlowerRed", "giantFlowerYellow"}; String[] bopMiscStandardHarvestables = {"deadGrass", "desertGrass", "whiteFlower", "blueFlower", "purpleFlower", "orangeFlower", "tinyFlower", "glowFlower", "cattail", "willow", "thorn", "toadstool", "shortGrass", "bush", "originGrass", "barley", "tinyCactus", "deathbloom", "hydrangea", "violet", "mediumGrass", "duneGrass", "desertSprouts", "holyGrass", "holyTallGrass", "moss", "algae", "smolderingGrass"}; String[] bopLeaveBottom = {"highGrassBottom", "highGrassTop"}; Class BOPBlocks = Class.forName("tdwp_ftw.biomesop.declarations.BOPBlocks"); if(BOPBlocks != null) { for(String leaves : bopLeaves) { MFRRegistry.registerHarvestable(new HarvestableTreeLeaves( ((Block)BOPBlocks.getField(leaves + "Leaves").get(null)).blockID )); } for(String log : bopLogs) { MFRRegistry.registerHarvestable(new HarvestableStandard(((Block)BOPBlocks.getField(log + "Wood").get(null)).blockID, HarvestType.Tree)); } for(String sapling : bopSaplings) { MFRRegistry.registerPlantable(new PlantableStandard(((Block)BOPBlocks.getField(sapling + "Sapling").get(null)).blockID, ((Block)BOPBlocks.getField(sapling + "Sapling").get(null)).blockID)); MFRRegistry.registerFertilizable(new FertilizableSapling(((Block)BOPBlocks.getField(sapling + "Sapling").get(null)).blockID)); } for(String trunk : bopMiscTrunks) { MFRRegistry.registerHarvestable(new HarvestableStandard(((Block)BOPBlocks.getField(trunk).get(null)).blockID, HarvestType.Tree)); } for(String leaves : bopMiscLeaves) { MFRRegistry.registerHarvestable(new HarvestableTreeLeaves(((Block)BOPBlocks.getField(leaves).get(null)).blockID)); } for(String harvestable : bopMiscStandardHarvestables) { MFRRegistry.registerHarvestable(new HarvestableStandard(((Block)BOPBlocks.getField(harvestable).get(null)).blockID, HarvestType.Normal)); } for(String harvestable : bopLeaveBottom) { MFRRegistry.registerHarvestable(new HarvestableStandard(((Block)BOPBlocks.getField(harvestable).get(null)).blockID, HarvestType.LeaveBottom)); } } Class bopJungleSpider = Class.forName("tdwp_ftw.biomesop.mobs.EntityJungleSpider"); Class bopRosester = Class.forName("tdwp_ftw.biomesop.mobs.EntityRosester"); MFRRegistry.registerGrindable(new GrindableStandard(bopJungleSpider, new MobDrop[] { new MobDrop(3, new ItemStack(Item.silk)), new MobDrop(1, new ItemStack(Item.spiderEye)) })); MFRRegistry.registerGrindable(new GrindableStandard(bopRosester, new MobDrop[] { new MobDrop(1, new ItemStack(Item.chickenRaw)), new MobDrop(1, new ItemStack(Item.dyePowder, 1, 1)) })); } catch(Exception e) { e.printStackTrace(); } } }
false
true
public static void load(FMLInitializationEvent ev) { if(!Loader.isModLoaded("BiomesOPlenty")) { FMLLog.warning("Biomes O' Plenty missing - MFR Biomes O' Plenty Compat not loading"); return; } try { // Biomes MFRRegistry.registerRubberTreeBiome("Bayou"); MFRRegistry.registerRubberTreeBiome("Birch Forest"); MFRRegistry.registerRubberTreeBiome("Bog"); MFRRegistry.registerRubberTreeBiome("Boreal Forest"); MFRRegistry.registerRubberTreeBiome("Deciduous Forest"); MFRRegistry.registerRubberTreeBiome("Forest"); MFRRegistry.registerRubberTreeBiome("Forest New"); MFRRegistry.registerRubberTreeBiome("ForestHills"); MFRRegistry.registerRubberTreeBiome("Grove"); MFRRegistry.registerRubberTreeBiome("Highland"); MFRRegistry.registerRubberTreeBiome("Jungle"); MFRRegistry.registerRubberTreeBiome("JungleHills"); MFRRegistry.registerRubberTreeBiome("Lush Swamp"); MFRRegistry.registerRubberTreeBiome("Maple Woods"); MFRRegistry.registerRubberTreeBiome("Marsh"); MFRRegistry.registerRubberTreeBiome("Moor"); MFRRegistry.registerRubberTreeBiome("Rainforest"); MFRRegistry.registerRubberTreeBiome("Seasonal Forest"); MFRRegistry.registerRubberTreeBiome("Shield"); MFRRegistry.registerRubberTreeBiome("Swampland"); MFRRegistry.registerRubberTreeBiome("Swampwoods"); MFRRegistry.registerRubberTreeBiome("Temperate Rainforest"); MFRRegistry.registerRubberTreeBiome("Thicket"); MFRRegistry.registerRubberTreeBiome("Tropical Rainforest"); MFRRegistry.registerRubberTreeBiome("Woodland"); String[] bopLeaves = {"acacia", "apple", "autumn", "bamboo", "dark", "dead", "blue", "fir", "holy", "mangrove", "orange", "origin", "palm", "pink", "red", "redwood", "white", "willow"}; String[] bopLogs = {"acacia", "bamboo", "cherry", "dark", "dead", "fir", "holy", "magic", "mangrove", "palm", "redwood", "willow"}; String[] bopSaplings = {"acacia", "apple", "brown", "dark", "fir", "holy", "magic", "mangrove", "orange", "origin", "palm", "pink", "red", "redwood", "willow", "yellow"}; String[] bopMiscTrunks = {"giantFlowerStem"}; String[] bopMiscLeaves = {"appleLeavesFruitless", "treeMoss", "giantFlowerRed", "giantFlowerYellow"}; String[] bopMiscStandardHarvestables = {"deadGrass", "desertGrass", "whiteFlower", "blueFlower", "purpleFlower", "orangeFlower", "tinyFlower", "glowFlower", "cattail", "willow", "thorn", "toadstool", "shortGrass", "bush", "originGrass", "barley", "tinyCactus", "deathbloom", "hydrangea", "violet", "mediumGrass", "duneGrass", "desertSprouts", "holyGrass", "holyTallGrass", "moss", "algae", "smolderingGrass"}; String[] bopLeaveBottom = {"highGrassBottom", "highGrassTop"}; Class BOPBlocks = Class.forName("tdwp_ftw.biomesop.declarations.BOPBlocks"); if(BOPBlocks != null) { for(String leaves : bopLeaves) { MFRRegistry.registerHarvestable(new HarvestableTreeLeaves( ((Block)BOPBlocks.getField(leaves + "Leaves").get(null)).blockID )); } for(String log : bopLogs) { MFRRegistry.registerHarvestable(new HarvestableStandard(((Block)BOPBlocks.getField(log + "Wood").get(null)).blockID, HarvestType.Tree)); } for(String sapling : bopSaplings) { MFRRegistry.registerPlantable(new PlantableStandard(((Block)BOPBlocks.getField(sapling + "Sapling").get(null)).blockID, ((Block)BOPBlocks.getField(sapling + "Sapling").get(null)).blockID)); MFRRegistry.registerFertilizable(new FertilizableSapling(((Block)BOPBlocks.getField(sapling + "Sapling").get(null)).blockID)); } for(String trunk : bopMiscTrunks) { MFRRegistry.registerHarvestable(new HarvestableStandard(((Block)BOPBlocks.getField(trunk).get(null)).blockID, HarvestType.Tree)); } for(String leaves : bopMiscLeaves) { MFRRegistry.registerHarvestable(new HarvestableTreeLeaves(((Block)BOPBlocks.getField(leaves).get(null)).blockID)); } for(String harvestable : bopMiscStandardHarvestables) { MFRRegistry.registerHarvestable(new HarvestableStandard(((Block)BOPBlocks.getField(harvestable).get(null)).blockID, HarvestType.Normal)); } for(String harvestable : bopLeaveBottom) { MFRRegistry.registerHarvestable(new HarvestableStandard(((Block)BOPBlocks.getField(harvestable).get(null)).blockID, HarvestType.LeaveBottom)); } } Class bopJungleSpider = Class.forName("tdwp_ftw.biomesop.mobs.EntityJungleSpider"); Class bopRosester = Class.forName("tdwp_ftw.biomesop.mobs.EntityRosester"); MFRRegistry.registerGrindable(new GrindableStandard(bopJungleSpider, new MobDrop[] { new MobDrop(3, new ItemStack(Item.silk)), new MobDrop(1, new ItemStack(Item.spiderEye)) })); MFRRegistry.registerGrindable(new GrindableStandard(bopRosester, new MobDrop[] { new MobDrop(1, new ItemStack(Item.chickenRaw)), new MobDrop(1, new ItemStack(Item.dyePowder, 1, 1)) })); } catch(Exception e) { e.printStackTrace(); } }
public static void load(FMLInitializationEvent ev) { if(!Loader.isModLoaded("BiomesOPlenty")) { FMLLog.warning("Biomes O' Plenty missing - MFR Biomes O' Plenty Compat not loading"); return; } try { // Biomes MFRRegistry.registerRubberTreeBiome("Bayou"); MFRRegistry.registerRubberTreeBiome("Birch Forest"); MFRRegistry.registerRubberTreeBiome("Bog"); MFRRegistry.registerRubberTreeBiome("Boreal Forest"); MFRRegistry.registerRubberTreeBiome("Deciduous Forest"); MFRRegistry.registerRubberTreeBiome("Forest"); MFRRegistry.registerRubberTreeBiome("Forest New"); MFRRegistry.registerRubberTreeBiome("ForestHills"); MFRRegistry.registerRubberTreeBiome("Grove"); MFRRegistry.registerRubberTreeBiome("Highland"); MFRRegistry.registerRubberTreeBiome("Jungle"); MFRRegistry.registerRubberTreeBiome("JungleHills"); MFRRegistry.registerRubberTreeBiome("Lush Swamp"); MFRRegistry.registerRubberTreeBiome("Maple Woods"); MFRRegistry.registerRubberTreeBiome("Marsh"); MFRRegistry.registerRubberTreeBiome("Moor"); MFRRegistry.registerRubberTreeBiome("Rainforest"); MFRRegistry.registerRubberTreeBiome("Seasonal Forest"); MFRRegistry.registerRubberTreeBiome("Shield"); MFRRegistry.registerRubberTreeBiome("Swampland"); MFRRegistry.registerRubberTreeBiome("Swampwoods"); MFRRegistry.registerRubberTreeBiome("Temperate Rainforest"); MFRRegistry.registerRubberTreeBiome("Thicket"); MFRRegistry.registerRubberTreeBiome("Tropical Rainforest"); MFRRegistry.registerRubberTreeBiome("Woodland"); String[] bopLeaves = {"acacia", "apple", "autumn", "bamboo", "dark", "dead", "blue", "fir", "holy", "mangrove", "orange", "origin", "palm", "pink", "red", "redwood", "white", "willow"}; String[] bopLogs = {"acacia", "cherry", "dark", "dead", "fir", "holy", "magic", "mangrove", "palm", "redwood", "willow"}; String[] bopSaplings = {"acacia", "apple", "brown", "dark", "fir", "holy", "magic", "mangrove", "orange", "origin", "palm", "pink", "red", "redwood", "willow", "yellow"}; String[] bopMiscTrunks = {"giantFlowerStem", "bamboo"}; String[] bopMiscLeaves = {"appleLeavesFruitless", "treeMoss", "giantFlowerRed", "giantFlowerYellow"}; String[] bopMiscStandardHarvestables = {"deadGrass", "desertGrass", "whiteFlower", "blueFlower", "purpleFlower", "orangeFlower", "tinyFlower", "glowFlower", "cattail", "willow", "thorn", "toadstool", "shortGrass", "bush", "originGrass", "barley", "tinyCactus", "deathbloom", "hydrangea", "violet", "mediumGrass", "duneGrass", "desertSprouts", "holyGrass", "holyTallGrass", "moss", "algae", "smolderingGrass"}; String[] bopLeaveBottom = {"highGrassBottom", "highGrassTop"}; Class BOPBlocks = Class.forName("tdwp_ftw.biomesop.declarations.BOPBlocks"); if(BOPBlocks != null) { for(String leaves : bopLeaves) { MFRRegistry.registerHarvestable(new HarvestableTreeLeaves( ((Block)BOPBlocks.getField(leaves + "Leaves").get(null)).blockID )); } for(String log : bopLogs) { MFRRegistry.registerHarvestable(new HarvestableStandard(((Block)BOPBlocks.getField(log + "Wood").get(null)).blockID, HarvestType.Tree)); } for(String sapling : bopSaplings) { MFRRegistry.registerPlantable(new PlantableStandard(((Block)BOPBlocks.getField(sapling + "Sapling").get(null)).blockID, ((Block)BOPBlocks.getField(sapling + "Sapling").get(null)).blockID)); MFRRegistry.registerFertilizable(new FertilizableSapling(((Block)BOPBlocks.getField(sapling + "Sapling").get(null)).blockID)); } for(String trunk : bopMiscTrunks) { MFRRegistry.registerHarvestable(new HarvestableStandard(((Block)BOPBlocks.getField(trunk).get(null)).blockID, HarvestType.Tree)); } for(String leaves : bopMiscLeaves) { MFRRegistry.registerHarvestable(new HarvestableTreeLeaves(((Block)BOPBlocks.getField(leaves).get(null)).blockID)); } for(String harvestable : bopMiscStandardHarvestables) { MFRRegistry.registerHarvestable(new HarvestableStandard(((Block)BOPBlocks.getField(harvestable).get(null)).blockID, HarvestType.Normal)); } for(String harvestable : bopLeaveBottom) { MFRRegistry.registerHarvestable(new HarvestableStandard(((Block)BOPBlocks.getField(harvestable).get(null)).blockID, HarvestType.LeaveBottom)); } } Class bopJungleSpider = Class.forName("tdwp_ftw.biomesop.mobs.EntityJungleSpider"); Class bopRosester = Class.forName("tdwp_ftw.biomesop.mobs.EntityRosester"); MFRRegistry.registerGrindable(new GrindableStandard(bopJungleSpider, new MobDrop[] { new MobDrop(3, new ItemStack(Item.silk)), new MobDrop(1, new ItemStack(Item.spiderEye)) })); MFRRegistry.registerGrindable(new GrindableStandard(bopRosester, new MobDrop[] { new MobDrop(1, new ItemStack(Item.chickenRaw)), new MobDrop(1, new ItemStack(Item.dyePowder, 1, 1)) })); } catch(Exception e) { e.printStackTrace(); } }
diff --git a/java/src/collections/MaxIterator.java b/java/src/collections/MaxIterator.java index 99424f4..190dfbd 100644 --- a/java/src/collections/MaxIterator.java +++ b/java/src/collections/MaxIterator.java @@ -1,74 +1,76 @@ package collections; import java.util.Comparator; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Vector; /** * Implement a max iterator i.e. it always returns the next item in the list * bigger than the last item returned. */ public class MaxIterator<T> implements Iterator<T> { private final Iterator<T> iterator; private T nextItem; private T lastItem; private final Comparator<T> comparator; public MaxIterator(Iterator<T> iterator, Comparator<T> comparator) { this.iterator = iterator; this.comparator = comparator; } @Override public boolean hasNext() { if (nextItem != null) { return true; } while (nextItem == null && iterator.hasNext()) { T item = iterator.next(); if (lastItem == null || comparator.compare(item, lastItem) > 0) { nextItem = item; } } return nextItem != null; } @Override public T next() { if (!hasNext()) { throw new NoSuchElementException(); } lastItem = nextItem; nextItem = null; return lastItem; } @Override public void remove() { throw new UnsupportedOperationException(); } public static void main(String[] args) { Vector<Integer> vec = new Vector<Integer>(); vec.add(3); - vec.add(5); + vec.add(2); vec.add(9); + vec.add(8); + vec.add(11); MaxIterator<Integer> mi = new MaxIterator<Integer>(vec.iterator(), new Comparator<Integer>() { @Override public int compare(Integer a, Integer b) { return a - b; } }); System.out.println(mi.next()); System.out.println(mi.next()); System.out.println(mi.next()); } }
false
true
public static void main(String[] args) { Vector<Integer> vec = new Vector<Integer>(); vec.add(3); vec.add(5); vec.add(9); MaxIterator<Integer> mi = new MaxIterator<Integer>(vec.iterator(), new Comparator<Integer>() { @Override public int compare(Integer a, Integer b) { return a - b; } }); System.out.println(mi.next()); System.out.println(mi.next()); System.out.println(mi.next()); }
public static void main(String[] args) { Vector<Integer> vec = new Vector<Integer>(); vec.add(3); vec.add(2); vec.add(9); vec.add(8); vec.add(11); MaxIterator<Integer> mi = new MaxIterator<Integer>(vec.iterator(), new Comparator<Integer>() { @Override public int compare(Integer a, Integer b) { return a - b; } }); System.out.println(mi.next()); System.out.println(mi.next()); System.out.println(mi.next()); }
diff --git a/src/main/java/org/spout/engine/world/SpoutBlock.java b/src/main/java/org/spout/engine/world/SpoutBlock.java index c8eb3b207..ab1701cd4 100644 --- a/src/main/java/org/spout/engine/world/SpoutBlock.java +++ b/src/main/java/org/spout/engine/world/SpoutBlock.java @@ -1,308 +1,308 @@ /* * This file is part of SpoutAPI (http://www.spout.org/). * * SpoutAPI is licensed under the SpoutDev License Version 1. * * SpoutAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * In addition, 180 days after any changes are published, you can use the * software, incorporating those changes, under the terms of the MIT license, * as described in the SpoutDev License Version 1. * * SpoutAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License, * the MIT license and the SpoutDev License Version 1 along with this program. * If not, see <http://www.gnu.org/licenses/> for the GNU Lesser General Public * License and see <http://www.spout.org/SpoutDevLicenseV1.txt> for the full license, * including the MIT license. */ package org.spout.engine.world; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.spout.api.Source; import org.spout.api.entity.BlockController; import org.spout.api.generator.biome.Biome; import org.spout.api.geo.World; import org.spout.api.geo.cuboid.Block; import org.spout.api.geo.cuboid.Chunk; import org.spout.api.geo.cuboid.Region; import org.spout.api.geo.discrete.Point; import org.spout.api.material.BlockMaterial; import org.spout.api.material.block.BlockFace; import org.spout.api.material.source.DataSource; import org.spout.api.material.source.MaterialSource; import org.spout.api.math.Vector3; import org.spout.api.util.StringUtil; public class SpoutBlock implements Block { private int x, y, z; private World world; private Source source; private Chunk chunk; public SpoutBlock(Block source) { this(source.getWorld(), source.getX(), source.getY(), source.getZ(), source.getSource()); if (source instanceof SpoutBlock) { this.chunk = ((SpoutBlock) source).chunk; } } public SpoutBlock(Point position, Source source) { this(position.getWorld(), position.getBlockX(), position.getBlockY(), position.getBlockZ(), source); } public SpoutBlock(World world, int x, int y, int z, Source source) { this(world, x, y, z, null, source); } public SpoutBlock(World world, int x, int y, int z, Chunk chunk, Source source) { this.x = x; this.y = y; this.z = z; this.world = world; this.source = source == null ? world : source; this.chunk = chunk != null && chunk.containsBlock(x, y, z) ? chunk : null; } @Override public Point getPosition() { return new Point(this.world, this.x + 0.5f, this.y + 0.5f, this.z + 0.5f); } @Override public Chunk getChunk() { if (this.chunk == null || !this.chunk.isLoaded()) { this.chunk = this.world.getChunkFromBlock(this.x, this.y, this.z, true); } return this.chunk; } @Override public World getWorld() { return this.world; } @Override public int getX() { return this.x; } @Override public int getY() { return this.y; } @Override public int getZ() { return this.z; } @Override public Block setX(int x) { SpoutBlock sb = this.clone(); sb.x = x; sb.chunk = null; return sb; } @Override public Block setY(int y) { SpoutBlock sb = this.clone(); sb.y = y; sb.chunk = null; return sb; } @Override public Block setZ(int z) { SpoutBlock sb = this.clone(); sb.z = z; sb.chunk = null; return sb; } @Override public Block translate(BlockFace offset) { return this.translate(offset.getOffset()); } @Override public Block translate(Vector3 offset) { return this.translate((int) offset.getX(), (int) offset.getY(), (int) offset.getZ()); } @Override public Block translate(int dx, int dy, int dz) { SpoutBlock sb = this.clone(); sb.x += dx; sb.y += dy; sb.z += dz; sb.chunk = null; return sb; } @Override public boolean equals(Object other) { if (other == this) { return true; } else if (other != null && other instanceof Block) { Block b = (Block) other; return b.getWorld() == this.getWorld() && b.getX() == this.getX() && b.getY() == this.getY() && b.getZ() == this.getZ(); } else { return false; } } @Override public int hashCode() { return new HashCodeBuilder().append(getWorld()).append(getX()).append(getY()).append(getZ()).toHashCode(); } @Override public SpoutBlock clone() { return new SpoutBlock(this); } @Override public String toString() { return StringUtil.toNamedString(this, this.world, this.x, this.y, this.z); } @Override public SpoutBlock setMaterial(MaterialSource material, int data) { if (material.getMaterial() instanceof BlockMaterial) { this.getChunk().setBlockMaterial(this.x, y, z, (BlockMaterial) material.getMaterial(), (short) data, this.source); } else { throw new IllegalArgumentException("Can't set a block to a non-block material!"); } return this; } @Override public SpoutBlock setData(DataSource data) { return this.setData(data.getData()); } @Override public SpoutBlock setData(int data) { this.getChunk().setBlockData(this.x, this.y, this.z, (short) data, this.source); return this; } @Override public short getData() { return this.getChunk().getBlockData(this.x, this.y, this.z); } @Override public Source getSource() { return this.source; } @Override public Block setSource(Source source) { SpoutBlock block = this.clone(); block.source = source == null ? block.world : source; return block; } @Override public BlockMaterial getSubMaterial() { return this.getMaterial().getSubMaterial(this.getData()); } @Override public Region getRegion() { return this.getChunk().getRegion(); } @Override public BlockMaterial getMaterial() { return this.getChunk().getBlockMaterial(this.x, this.y, this.z); } @Override public Block setMaterial(MaterialSource material) { return this.setMaterial(material, material.getData()); } @Override public Block setMaterial(MaterialSource material, DataSource data) { return this.setMaterial(material, data.getData()); } @Override public byte getLight() { return this.getChunk().getBlockLight(this.x, this.y, this.z); } @Override public Block setLight(byte level) { this.getChunk().setBlockLight(this.x, this.y, this.z, level, this.source); return this; } @Override public byte getSkyLight() { return this.getChunk().getBlockSkyLight(this.x, this.y, this.z); } @Override public Block setSkyLight(byte level) { this.getChunk().setBlockSkyLight(this.x, this.y, this.z, level, this.source); return this; } @Override public BlockController getController() { return getRegion().getBlockController(x, y, z); } @Override public Block setController(BlockController controller) { getRegion().setBlockController(x, y, z, controller); return this; } @Override public boolean hasController() { return getController() != null; } @Override public Block update() { return this.update(true); } @Override public Block update(boolean around) { - Chunk chunk = this.getChunk(); - chunk.updateBlockPhysics(this.x, this.y, this.z, this.source); + World world = this.getWorld(); + world.updateBlockPhysics(this.x, this.y, this.z, this.source); if (around) { //South and North - chunk.updateBlockPhysics(this.x + 1, this.y, this.z, this.source); - chunk.updateBlockPhysics(this.x - 1, this.y, this.z, this.source); + world.updateBlockPhysics(this.x + 1, this.y, this.z, this.source); + world.updateBlockPhysics(this.x - 1, this.y, this.z, this.source); //West and East - chunk.updateBlockPhysics(this.x, this.y, this.z + 1, this.source); - chunk.updateBlockPhysics(this.x, this.y, this.z - 1, this.source); + world.updateBlockPhysics(this.x, this.y, this.z + 1, this.source); + world.updateBlockPhysics(this.x, this.y, this.z - 1, this.source); //Above and Below - chunk.updateBlockPhysics(this.x, this.y + 1, this.z, this.source); - chunk.updateBlockPhysics(this.x, this.y - 1, this.z, this.source); + world.updateBlockPhysics(this.x, this.y + 1, this.z, this.source); + world.updateBlockPhysics(this.x, this.y - 1, this.z, this.source); } return this; } @Override public Biome getBiomeType() { return world.getBiomeType(x, y, z); } }
false
true
public Block update(boolean around) { Chunk chunk = this.getChunk(); chunk.updateBlockPhysics(this.x, this.y, this.z, this.source); if (around) { //South and North chunk.updateBlockPhysics(this.x + 1, this.y, this.z, this.source); chunk.updateBlockPhysics(this.x - 1, this.y, this.z, this.source); //West and East chunk.updateBlockPhysics(this.x, this.y, this.z + 1, this.source); chunk.updateBlockPhysics(this.x, this.y, this.z - 1, this.source); //Above and Below chunk.updateBlockPhysics(this.x, this.y + 1, this.z, this.source); chunk.updateBlockPhysics(this.x, this.y - 1, this.z, this.source); } return this; }
public Block update(boolean around) { World world = this.getWorld(); world.updateBlockPhysics(this.x, this.y, this.z, this.source); if (around) { //South and North world.updateBlockPhysics(this.x + 1, this.y, this.z, this.source); world.updateBlockPhysics(this.x - 1, this.y, this.z, this.source); //West and East world.updateBlockPhysics(this.x, this.y, this.z + 1, this.source); world.updateBlockPhysics(this.x, this.y, this.z - 1, this.source); //Above and Below world.updateBlockPhysics(this.x, this.y + 1, this.z, this.source); world.updateBlockPhysics(this.x, this.y - 1, this.z, this.source); } return this; }
diff --git a/src/java/org/jruby/ext/openssl/Request.java b/src/java/org/jruby/ext/openssl/Request.java index 9d350a1..746192b 100644 --- a/src/java/org/jruby/ext/openssl/Request.java +++ b/src/java/org/jruby/ext/openssl/Request.java @@ -1,328 +1,339 @@ /***** BEGIN LICENSE BLOCK ***** * Version: CPL 1.0/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Common Public * License Version 1.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.eclipse.org/legal/cpl-v10.html * * Software distributed under the License is distributed on an "AS * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or * implied. See the License for the specific language governing * rights and limitations under the License. * * Copyright (C) 2006, 2007 Ola Bini <[email protected]> * * Alternatively, the contents of this file may be used under the terms of * either of the GNU General Public License Version 2 or later (the "GPL"), * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the CPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the CPL, the GPL or the LGPL. ***** END LICENSE BLOCK *****/ package org.jruby.ext.openssl; import java.util.ArrayList; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.io.IOException; import java.io.StringWriter; import java.security.GeneralSecurityException; import java.security.PublicKey; import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Set; import org.bouncycastle.asn1.DERObject; import org.bouncycastle.asn1.DERObjectIdentifier; import org.bouncycastle.asn1.DERSequence; import org.bouncycastle.asn1.DERSet; import org.bouncycastle.asn1.DERString; import org.jruby.Ruby; import org.jruby.RubyArray; import org.jruby.RubyClass; import org.jruby.RubyModule; import org.jruby.RubyNumeric; import org.jruby.RubyObject; import org.jruby.RubyString; import org.jruby.anno.JRubyMethod; import org.jruby.exceptions.RaiseException; import org.jruby.ext.openssl.x509store.PEMInputOutput; import org.jruby.runtime.Block; import org.jruby.runtime.ObjectAllocator; import org.jruby.runtime.builtin.IRubyObject; /** * @author <a href="mailto:[email protected]">Ola Bini</a> */ public class Request extends RubyObject { private static final long serialVersionUID = -5551557929791764918L; private static ObjectAllocator REQUEST_ALLOCATOR = new ObjectAllocator() { public IRubyObject allocate(Ruby runtime, RubyClass klass) { return new Request(runtime, klass); } }; public static void createRequest(Ruby runtime, RubyModule mX509) { RubyClass cRequest = mX509.defineClassUnder("Request",runtime.getObject(),REQUEST_ALLOCATOR); RubyClass openSSLError = runtime.getModule("OpenSSL").getClass("OpenSSLError"); mX509.defineClassUnder("RequestError",openSSLError,openSSLError.getAllocator()); cRequest.defineAnnotatedMethods(Request.class); } private IRubyObject version; private IRubyObject subject; private IRubyObject public_key; private boolean valid = false; private List<IRubyObject> attrs; private PKCS10CertificationRequestExt req; public Request(Ruby runtime, RubyClass type) { super(runtime,type); attrs = new ArrayList<IRubyObject>(); } @JRubyMethod(name="initialize", frame=true, rest=true) public IRubyObject _initialize(IRubyObject[] args, Block block) { if(org.jruby.runtime.Arity.checkArgumentCount(getRuntime(),args,0,1) == 0) { return this; } byte[] req_bytes = OpenSSLImpl.readX509PEM(args[0]); req = new PKCS10CertificationRequestExt(req_bytes); version = getRuntime().newFixnum(req.getVersion()); String algo = null; byte[] enc = null; try { PublicKey pkey = (PublicKey) OpenSSLReal.getWithBCProvider(new OpenSSLReal.Callable() { public Object call() throws GeneralSecurityException { return req.getPublicKey("BC"); } }); algo = pkey.getAlgorithm(); enc = pkey.getEncoded(); } catch (GeneralSecurityException gse) { throw newX509ReqError(getRuntime(), gse.getMessage()); } if("RSA".equalsIgnoreCase(algo)) { this.public_key = Utils.newRubyInstance(getRuntime(), "OpenSSL::PKey::RSA", RubyString.newString(getRuntime(), enc)); } else if("DSA".equalsIgnoreCase(algo)) { this.public_key = Utils.newRubyInstance(getRuntime(), "OpenSSL::PKey::DSA", RubyString.newString(getRuntime(), enc)); } else { throw getRuntime().newLoadError("not implemented algo for public key: " + algo); } org.bouncycastle.asn1.x509.X509Name subName = req.getCertificationRequestInfo().getSubject(); subject = Utils.newRubyInstance(getRuntime(), "OpenSSL::X509::Name"); DERSequence subNameD = (DERSequence)subName.toASN1Object(); for(int i=0;i<subNameD.size();i++) { DERSequence internal = (DERSequence)((DERSet)subNameD.getObjectAt(i)).getObjectAt(0); Object oid = internal.getObjectAt(0); Object v = null; if(internal.getObjectAt(1) instanceof DERString) { v = ((DERString)internal.getObjectAt(1)).getString(); } Object t = getRuntime().newFixnum(ASN1.idForClass(internal.getObjectAt(1).getClass())); ((X509Name)subject).addEntry(oid,v,t); } ASN1Set in_attrs = req.getCertificationRequestInfo().getAttributes(); for(Enumeration enm = in_attrs.getObjects();enm.hasMoreElements();) { - DERSet obj = (DERSet)enm.nextElement(); - for(Enumeration enm2 = obj.getObjects();enm2.hasMoreElements();) { - DERSequence val = (DERSequence)enm2.nextElement(); - DERObjectIdentifier v0 = (DERObjectIdentifier)val.getObjectAt(0); - DERObject v1 = (DERObject)val.getObjectAt(1); - IRubyObject a1 = getRuntime().newString(ASN1.getSymLookup(getRuntime()).get(v0)); - IRubyObject a2 = ASN1.decode(getRuntime().getClassFromPath("OpenSSL::ASN1"), RubyString.newString(getRuntime(), v1.getDEREncoded())); - add_attribute(Utils.newRubyInstance(getRuntime(), "OpenSSL::X509::Attribute", new IRubyObject[] { a1, a2 })); - } + Object o = enm.nextElement(); + System.out.println("enm: " + o.getClass()); + if (o instanceof DERSequence) { + DERSequence val = (DERSequence)o; + DERObjectIdentifier v0 = (DERObjectIdentifier)val.getObjectAt(0); + DERObject v1 = (DERObject)val.getObjectAt(1); + IRubyObject a1 = getRuntime().newString(ASN1.getSymLookup(getRuntime()).get(v0)); + IRubyObject a2 = ASN1.decode(getRuntime().getClassFromPath("OpenSSL::ASN1"), RubyString.newString(getRuntime(), v1.getDEREncoded())); + add_attribute(Utils.newRubyInstance(getRuntime(), "OpenSSL::X509::Attribute", new IRubyObject[] { a1, a2 })); + } else { + DERSet obj = (DERSet)o; + for(Enumeration enm2 = obj.getObjects();enm2.hasMoreElements();) { + DERSequence val = (DERSequence)enm2.nextElement(); + DERObjectIdentifier v0 = (DERObjectIdentifier)val.getObjectAt(0); + DERObject v1 = (DERObject)val.getObjectAt(1); + IRubyObject a1 = getRuntime().newString(ASN1.getSymLookup(getRuntime()).get(v0)); + IRubyObject a2 = ASN1.decode(getRuntime().getClassFromPath("OpenSSL::ASN1"), RubyString.newString(getRuntime(), v1.getDEREncoded())); + add_attribute(Utils.newRubyInstance(getRuntime(), "OpenSSL::X509::Attribute", new IRubyObject[] { a1, a2 })); + } + } } this.valid = true; return this; } @Override @JRubyMethod public IRubyObject initialize_copy(IRubyObject obj) { System.err.println("WARNING: unimplemented method called: init_copy"); if(this == obj) { return this; } checkFrozen(); version = getRuntime().getNil(); subject = getRuntime().getNil(); public_key = getRuntime().getNil(); return this; } @JRubyMethod(name={"to_pem","to_s"}) public IRubyObject to_pem() { StringWriter w = new StringWriter(); try { PEMInputOutput.writeX509Request(w, req); return getRuntime().newString(w.toString()); } catch (IOException ex) { throw getRuntime().newIOErrorFromException(ex); } finally { try { w.close(); } catch( Exception e ) {} } } @JRubyMethod public IRubyObject to_der() { return RubyString.newString(getRuntime(), req.getDEREncoded()); } @JRubyMethod public IRubyObject to_text() { System.err.println("WARNING: unimplemented method called: to_text"); return getRuntime().getNil(); } @JRubyMethod public IRubyObject version() { return this.version; } @JRubyMethod(name="version=") public IRubyObject set_version(IRubyObject val) { if(val != version) { valid = false; } this.version = val; if(!val.isNil() && req != null) { req.setVersion(RubyNumeric.fix2int(val)); } return val; } @JRubyMethod public IRubyObject subject() { return this.subject; } @JRubyMethod(name="subject=") public IRubyObject set_subject(IRubyObject val) { if(val != subject) { valid = false; } this.subject = val; return val; } @JRubyMethod public IRubyObject signature_algorithm() { System.err.println("WARNING: unimplemented method called: signature_algorithm"); return getRuntime().getNil(); } @JRubyMethod public IRubyObject public_key() { return this.public_key; } @JRubyMethod(name="public_key=") public IRubyObject set_public_key(IRubyObject val) { if(val != public_key) { valid = false; } this.public_key = val; return val; } @JRubyMethod public IRubyObject sign(final IRubyObject key, final IRubyObject digest) { final String keyAlg = ((PKey)public_key).getAlgorithm(); final String digAlg = ((Digest)digest).getShortAlgorithm(); if(("DSA".equalsIgnoreCase(keyAlg) && "MD5".equalsIgnoreCase(digAlg)) || ("RSA".equalsIgnoreCase(keyAlg) && "DSS1".equals(((Digest)digest).name().toString())) || ("DSA".equalsIgnoreCase(keyAlg) && "SHA1".equals(((Digest)digest).name().toString()))) { throw newX509ReqError(getRuntime(), null); } final ASN1EncodableVector v1 = new ASN1EncodableVector(); for(Iterator<IRubyObject> iter = attrs.iterator();iter.hasNext();) { v1.add(((Attribute)iter.next()).toASN1()); } try { // PKCS10CertificationRequestExt depends BC. OpenSSLReal.doWithBCProvider(new OpenSSLReal.Runnable() { public void run() throws GeneralSecurityException { req = new PKCS10CertificationRequestExt(digAlg + "WITH" + keyAlg, ((X509Name) subject).getRealName(), ((PKey) public_key).getPublicKey(), new DERSet(v1), ((PKey) key).getPrivateKey(), "BC"); } }); } catch (GeneralSecurityException gse) { throw newX509ReqError(getRuntime(), gse.getMessage()); } req.setVersion(RubyNumeric.fix2int(version)); valid = true; return this; } @JRubyMethod public IRubyObject verify(IRubyObject key) { try { return valid && req.verify(((PKey)(key.callMethod(getRuntime().getCurrentContext(),"public_key"))).getPublicKey()) ? getRuntime().getTrue() : getRuntime().getFalse(); } catch(Exception e) { return getRuntime().getFalse(); } } @JRubyMethod public IRubyObject attributes() { return getRuntime().newArray(attrs); } @SuppressWarnings("unchecked") @JRubyMethod(name="attributes=") public IRubyObject set_attributes(IRubyObject val) { valid = false; attrs.clear(); attrs.addAll(((RubyArray)val).getList()); if(req != null) { ASN1EncodableVector v1 = new ASN1EncodableVector(); for(Iterator<IRubyObject> iter = attrs.iterator();iter.hasNext();) { v1.add(((Attribute)iter.next()).toASN1()); } req.setAttributes(new DERSet(v1)); } return val; } @JRubyMethod public IRubyObject add_attribute(IRubyObject val) { valid = false; attrs.add(val); if(req != null) { ASN1EncodableVector v1 = new ASN1EncodableVector(); for(Iterator<IRubyObject> iter = attrs.iterator();iter.hasNext();) { v1.add(((Attribute)iter.next()).toASN1()); } req.setAttributes(new DERSet(v1)); } return getRuntime().getNil(); } private static RaiseException newX509ReqError(Ruby runtime, String message) { return Utils.newError(runtime, "OpenSSL::X509::RequestError", message); } }// Request
true
true
public IRubyObject _initialize(IRubyObject[] args, Block block) { if(org.jruby.runtime.Arity.checkArgumentCount(getRuntime(),args,0,1) == 0) { return this; } byte[] req_bytes = OpenSSLImpl.readX509PEM(args[0]); req = new PKCS10CertificationRequestExt(req_bytes); version = getRuntime().newFixnum(req.getVersion()); String algo = null; byte[] enc = null; try { PublicKey pkey = (PublicKey) OpenSSLReal.getWithBCProvider(new OpenSSLReal.Callable() { public Object call() throws GeneralSecurityException { return req.getPublicKey("BC"); } }); algo = pkey.getAlgorithm(); enc = pkey.getEncoded(); } catch (GeneralSecurityException gse) { throw newX509ReqError(getRuntime(), gse.getMessage()); } if("RSA".equalsIgnoreCase(algo)) { this.public_key = Utils.newRubyInstance(getRuntime(), "OpenSSL::PKey::RSA", RubyString.newString(getRuntime(), enc)); } else if("DSA".equalsIgnoreCase(algo)) { this.public_key = Utils.newRubyInstance(getRuntime(), "OpenSSL::PKey::DSA", RubyString.newString(getRuntime(), enc)); } else { throw getRuntime().newLoadError("not implemented algo for public key: " + algo); } org.bouncycastle.asn1.x509.X509Name subName = req.getCertificationRequestInfo().getSubject(); subject = Utils.newRubyInstance(getRuntime(), "OpenSSL::X509::Name"); DERSequence subNameD = (DERSequence)subName.toASN1Object(); for(int i=0;i<subNameD.size();i++) { DERSequence internal = (DERSequence)((DERSet)subNameD.getObjectAt(i)).getObjectAt(0); Object oid = internal.getObjectAt(0); Object v = null; if(internal.getObjectAt(1) instanceof DERString) { v = ((DERString)internal.getObjectAt(1)).getString(); } Object t = getRuntime().newFixnum(ASN1.idForClass(internal.getObjectAt(1).getClass())); ((X509Name)subject).addEntry(oid,v,t); } ASN1Set in_attrs = req.getCertificationRequestInfo().getAttributes(); for(Enumeration enm = in_attrs.getObjects();enm.hasMoreElements();) { DERSet obj = (DERSet)enm.nextElement(); for(Enumeration enm2 = obj.getObjects();enm2.hasMoreElements();) { DERSequence val = (DERSequence)enm2.nextElement(); DERObjectIdentifier v0 = (DERObjectIdentifier)val.getObjectAt(0); DERObject v1 = (DERObject)val.getObjectAt(1); IRubyObject a1 = getRuntime().newString(ASN1.getSymLookup(getRuntime()).get(v0)); IRubyObject a2 = ASN1.decode(getRuntime().getClassFromPath("OpenSSL::ASN1"), RubyString.newString(getRuntime(), v1.getDEREncoded())); add_attribute(Utils.newRubyInstance(getRuntime(), "OpenSSL::X509::Attribute", new IRubyObject[] { a1, a2 })); } } this.valid = true; return this; }
public IRubyObject _initialize(IRubyObject[] args, Block block) { if(org.jruby.runtime.Arity.checkArgumentCount(getRuntime(),args,0,1) == 0) { return this; } byte[] req_bytes = OpenSSLImpl.readX509PEM(args[0]); req = new PKCS10CertificationRequestExt(req_bytes); version = getRuntime().newFixnum(req.getVersion()); String algo = null; byte[] enc = null; try { PublicKey pkey = (PublicKey) OpenSSLReal.getWithBCProvider(new OpenSSLReal.Callable() { public Object call() throws GeneralSecurityException { return req.getPublicKey("BC"); } }); algo = pkey.getAlgorithm(); enc = pkey.getEncoded(); } catch (GeneralSecurityException gse) { throw newX509ReqError(getRuntime(), gse.getMessage()); } if("RSA".equalsIgnoreCase(algo)) { this.public_key = Utils.newRubyInstance(getRuntime(), "OpenSSL::PKey::RSA", RubyString.newString(getRuntime(), enc)); } else if("DSA".equalsIgnoreCase(algo)) { this.public_key = Utils.newRubyInstance(getRuntime(), "OpenSSL::PKey::DSA", RubyString.newString(getRuntime(), enc)); } else { throw getRuntime().newLoadError("not implemented algo for public key: " + algo); } org.bouncycastle.asn1.x509.X509Name subName = req.getCertificationRequestInfo().getSubject(); subject = Utils.newRubyInstance(getRuntime(), "OpenSSL::X509::Name"); DERSequence subNameD = (DERSequence)subName.toASN1Object(); for(int i=0;i<subNameD.size();i++) { DERSequence internal = (DERSequence)((DERSet)subNameD.getObjectAt(i)).getObjectAt(0); Object oid = internal.getObjectAt(0); Object v = null; if(internal.getObjectAt(1) instanceof DERString) { v = ((DERString)internal.getObjectAt(1)).getString(); } Object t = getRuntime().newFixnum(ASN1.idForClass(internal.getObjectAt(1).getClass())); ((X509Name)subject).addEntry(oid,v,t); } ASN1Set in_attrs = req.getCertificationRequestInfo().getAttributes(); for(Enumeration enm = in_attrs.getObjects();enm.hasMoreElements();) { Object o = enm.nextElement(); System.out.println("enm: " + o.getClass()); if (o instanceof DERSequence) { DERSequence val = (DERSequence)o; DERObjectIdentifier v0 = (DERObjectIdentifier)val.getObjectAt(0); DERObject v1 = (DERObject)val.getObjectAt(1); IRubyObject a1 = getRuntime().newString(ASN1.getSymLookup(getRuntime()).get(v0)); IRubyObject a2 = ASN1.decode(getRuntime().getClassFromPath("OpenSSL::ASN1"), RubyString.newString(getRuntime(), v1.getDEREncoded())); add_attribute(Utils.newRubyInstance(getRuntime(), "OpenSSL::X509::Attribute", new IRubyObject[] { a1, a2 })); } else { DERSet obj = (DERSet)o; for(Enumeration enm2 = obj.getObjects();enm2.hasMoreElements();) { DERSequence val = (DERSequence)enm2.nextElement(); DERObjectIdentifier v0 = (DERObjectIdentifier)val.getObjectAt(0); DERObject v1 = (DERObject)val.getObjectAt(1); IRubyObject a1 = getRuntime().newString(ASN1.getSymLookup(getRuntime()).get(v0)); IRubyObject a2 = ASN1.decode(getRuntime().getClassFromPath("OpenSSL::ASN1"), RubyString.newString(getRuntime(), v1.getDEREncoded())); add_attribute(Utils.newRubyInstance(getRuntime(), "OpenSSL::X509::Attribute", new IRubyObject[] { a1, a2 })); } } } this.valid = true; return this; }
diff --git a/src/main/java/net/praqma/hudson/scm/PucmState.java b/src/main/java/net/praqma/hudson/scm/PucmState.java index 9843b2b..352be23 100644 --- a/src/main/java/net/praqma/hudson/scm/PucmState.java +++ b/src/main/java/net/praqma/hudson/scm/PucmState.java @@ -1,254 +1,254 @@ package net.praqma.hudson.scm; import hudson.model.AbstractProject; import hudson.model.Build; import java.util.ArrayList; import java.util.List; import net.praqma.clearcase.ucm.entities.Baseline; import net.praqma.clearcase.ucm.entities.Component; import net.praqma.clearcase.ucm.entities.Project; import net.praqma.clearcase.ucm.entities.Stream; /** * * @author wolfgang * */ public class PucmState { private List<State> states = new ArrayList<State>(); private static final String linesep = System.getProperty( "line.separator" ); /** * Get a state given job name and job number * @param jobName the hudson job name * @param jobNumber the hudson job number * @return */ public State getState( String jobName, Integer jobNumber ) { for( State s : states ) { if( s.getJobName().equals( jobName ) && s.getJobNumber() == jobNumber ) { return s; } } State s = new State( jobName, jobNumber ); states.add( s ); return s; } public boolean removeState( String jobName, Integer jobNumber ) { for( State s : states ) { if( s.getJobName().equals( jobName ) && s.getJobNumber() == jobNumber ) { states.remove( s ); return true; } } return false; } public State getStateByBaseline( String jobName, String baseline ) { for( State s : states ) { if( s.getJobName().equals( jobName ) && s.getBaseline() != null && s.getBaseline().GetFQName().equals( baseline ) ) { return s; } } return null; } public void addState( State state ) { this.states.add( state ); } public boolean stateExists( State state ) { return stateExists( state.jobName, state.jobNumber ); } public boolean stateExists( String jobName, Integer jobNumber ) { for( State s : states ) { if( s.getJobName().equals( jobName ) && s.getJobNumber() == jobNumber ) { return true; } } return false; } public boolean removeState( State state ) { return states.remove( state ); } - public int recalculate( AbstractProject<?, ?> project ) + public synchronized int recalculate( AbstractProject<?, ?> project ) { int count = 0; for( State s : states ) { Integer bnum = s.getJobNumber(); Object o = project.getBuildByNumber( bnum ); Build bld = (Build)o; /* The job is not running */ if( !bld.isLogUpdated() ) { s.remove(); count++; } } return count; } public int size() { return states.size(); } public String stringify() { return net.praqma.util.structure.Printer.listPrinterToString( states ); } public class State { private Baseline baseline; private Stream stream; private Component component; private boolean doPostBuild = true; private Project.Plevel plevel; private String jobName; private Integer jobNumber; public State(){} public State( String jobName, Integer jobNumber ) { this.jobName = jobName; this.jobNumber = jobNumber; } public State( String jobName, Integer jobNumber, Baseline baseline, Stream stream, Component component, boolean doPostBuild ) { this.jobName = jobName; this.jobNumber = jobNumber; this.baseline = baseline; this.stream = stream; this.component = component; this.doPostBuild = doPostBuild; } @Deprecated public void save() { PucmState.this.addState( this ); } public boolean remove() { return PucmState.this.removeState( this ); } public Baseline getBaseline() { return baseline; } public void setBaseline( Baseline baseline ) { this.baseline = baseline; } public Stream getStream() { return stream; } public void setStream( Stream stream ) { this.stream = stream; } public Component getComponent() { return component; } public void setComponent( Component component ) { this.component = component; } public boolean doPostBuild() { return doPostBuild; } public void setPostBuild( boolean doPostBuild ) { this.doPostBuild = doPostBuild; } public String getJobName() { return jobName; } public void setJobName( String jobName ) { this.jobName = jobName; } public Integer getJobNumber() { return jobNumber; } public void setJobNumber( Integer jobNumber ) { this.jobNumber = jobNumber; } public void setPlevel( Project.Plevel plevel ) { this.plevel = plevel; } public Project.Plevel getPlevel() { return plevel; } public String stringify() { StringBuffer sb = new StringBuffer(); sb.append( "Job name : " + this.jobName + linesep ); sb.append( "Job number: " + this.jobNumber + linesep ); sb.append( "Component : " + this.component + linesep ); sb.append( "Stream : " + this.stream + linesep ); sb.append( "Baseline : " + this.baseline + linesep ); sb.append( "Plevel : " + ( this.plevel != null ? this.plevel.toString() : "Missing" ) + linesep ); sb.append( "postBuild : " + this.doPostBuild + linesep ); return sb.toString(); } public String toString() { return "(" + jobName + ", " + jobNumber + ")"; } } }
true
true
public int recalculate( AbstractProject<?, ?> project ) { int count = 0; for( State s : states ) { Integer bnum = s.getJobNumber(); Object o = project.getBuildByNumber( bnum ); Build bld = (Build)o; /* The job is not running */ if( !bld.isLogUpdated() ) { s.remove(); count++; } } return count; }
public synchronized int recalculate( AbstractProject<?, ?> project ) { int count = 0; for( State s : states ) { Integer bnum = s.getJobNumber(); Object o = project.getBuildByNumber( bnum ); Build bld = (Build)o; /* The job is not running */ if( !bld.isLogUpdated() ) { s.remove(); count++; } } return count; }
diff --git a/samples/appengine-repl/src/main/java/com/bedatadriven/renjin/appengine/server/LotREPLsApiImpl.java b/samples/appengine-repl/src/main/java/com/bedatadriven/renjin/appengine/server/LotREPLsApiImpl.java index cd08d4739..70687d63a 100644 --- a/samples/appengine-repl/src/main/java/com/bedatadriven/renjin/appengine/server/LotREPLsApiImpl.java +++ b/samples/appengine-repl/src/main/java/com/bedatadriven/renjin/appengine/server/LotREPLsApiImpl.java @@ -1,156 +1,156 @@ /* * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.bedatadriven.renjin.appengine.server; import com.bedatadriven.renjin.appengine.AppEngineContextFactory; import com.bedatadriven.renjin.appengine.shared.InterpreterException; import com.bedatadriven.renjin.appengine.shared.LotREPLsApi; import com.google.gwt.user.server.rpc.RemoteServiceServlet; import r.io.DatafileReader; import r.io.DatafileWriter; import r.lang.*; import r.lang.SecurityManager; import r.lang.exception.EvalException; import r.parser.RParser; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.util.logging.Level; import java.util.logging.Logger; /** * Server-side implementation of LotREPLsApi. This class manages the * interpreters for each language and routes commands appropriately. * */ public class LotREPLsApiImpl extends RemoteServiceServlet implements LotREPLsApi { private static final String GLOBALS = "GLOBALS"; private final Logger log = Logger.getLogger(LotREPLsApiImpl.class.getName()); private Context masterTopLevelContext; @Override public void init(ServletConfig config) throws ServletException { super.init(config); // The default VFS manager uses a Softref file cache that // is not allowed on AppEngine masterTopLevelContext = AppEngineContextFactory.createTopLevelContext(config.getServletContext()); // disable creation of java objects for the moment // (otherwise any would could access the datastore and do something annoying with it) // figure out how to apply more narrow gain permissions later. masterTopLevelContext.getGlobals().securityManager = new SecurityManager() { @Override public boolean allowNewInstance(Class clazz) { return false; } }; } public String eval(String script) throws InterpreterException { ExpressionVector expression = RParser.parseSource(script + "\n"); if(expression == null) { return ""; } Context context = masterTopLevelContext.fork(); StringWriter writer = new StringWriter(); context.getGlobals().setStdOut(new PrintWriter(writer)); restoreGlobals(context); SEXP result; try { - result = expression.evaluate(context, context.getEnvironment()); + result = context.evaluate(expression); } catch(EvalException e) { log.log(Level.WARNING, "Evaluation failed", e); throw new InterpreterException(e.getMessage()); } saveGlobals(context); if(!context.getGlobals().isInvisible()) { - FunctionCall.newCall(Symbol.get("print"), result) - .evaluate(context, context.getEnvironment()); + context.evaluate( + FunctionCall.newCall(Symbol.get("print"), result)); } context.getGlobals().stdout.flush(); return writer.toString(); } private void restoreGlobals(Context context) { HttpServletRequest request = getThreadLocalRequest(); HttpSession session = request.getSession(); byte[] globals = null; try { globals = (byte[]) session.getAttribute(GLOBALS); if (globals != null) { DatafileReader reader = new DatafileReader(context, context.getEnvironment(), new ByteArrayInputStream(globals)); PairList list = (PairList) reader.readFile(); for(PairList.Node node : list.nodes()) { context.getGlobalEnvironment().setVariable(node.getTag(), node.getValue()); } } } catch(Exception e) { // If there was a deserialization error, throw the session away session.removeAttribute(GLOBALS); log.log(Level.WARNING, "Could not deserialize context.", e); } } private void saveGlobals(Context context) { try { PairList.Builder list = new PairList.Builder(); Environment globalEnvironment = context.getGlobalEnvironment(); int count =0; for(Symbol symbol : globalEnvironment.getSymbolNames()) { SEXP value = globalEnvironment.getVariable(symbol); if(value instanceof Vector) { list.add(symbol, value); count++; } } ByteArrayOutputStream baos = new ByteArrayOutputStream(); DatafileWriter writer = new DatafileWriter(baos); writer.writeExp(list.build()); log.severe(count + " variable saved, " + baos.toByteArray().length + " bytes"); HttpServletRequest request = getThreadLocalRequest(); HttpSession session = request.getSession(); session.setAttribute(GLOBALS, baos.toByteArray()); } catch(Exception e) { log.log(Level.WARNING, "Failed to serialize globals", e); } } }
false
true
public String eval(String script) throws InterpreterException { ExpressionVector expression = RParser.parseSource(script + "\n"); if(expression == null) { return ""; } Context context = masterTopLevelContext.fork(); StringWriter writer = new StringWriter(); context.getGlobals().setStdOut(new PrintWriter(writer)); restoreGlobals(context); SEXP result; try { result = expression.evaluate(context, context.getEnvironment()); } catch(EvalException e) { log.log(Level.WARNING, "Evaluation failed", e); throw new InterpreterException(e.getMessage()); } saveGlobals(context); if(!context.getGlobals().isInvisible()) { FunctionCall.newCall(Symbol.get("print"), result) .evaluate(context, context.getEnvironment()); } context.getGlobals().stdout.flush(); return writer.toString(); }
public String eval(String script) throws InterpreterException { ExpressionVector expression = RParser.parseSource(script + "\n"); if(expression == null) { return ""; } Context context = masterTopLevelContext.fork(); StringWriter writer = new StringWriter(); context.getGlobals().setStdOut(new PrintWriter(writer)); restoreGlobals(context); SEXP result; try { result = context.evaluate(expression); } catch(EvalException e) { log.log(Level.WARNING, "Evaluation failed", e); throw new InterpreterException(e.getMessage()); } saveGlobals(context); if(!context.getGlobals().isInvisible()) { context.evaluate( FunctionCall.newCall(Symbol.get("print"), result)); } context.getGlobals().stdout.flush(); return writer.toString(); }
diff --git a/src/com/inspedio/system/helper/InsPointer.java b/src/com/inspedio/system/helper/InsPointer.java index 39a008a..82d6e19 100644 --- a/src/com/inspedio/system/helper/InsPointer.java +++ b/src/com/inspedio/system/helper/InsPointer.java @@ -1,148 +1,148 @@ package com.inspedio.system.helper; import java.util.Vector; import com.inspedio.entity.primitive.InsPoint; import com.inspedio.system.helper.extension.InsPointerEvent; /** * This is the helper class for pointer input<br> * Useful for global detection of pointerEvent (Pressed, Released, etc) * * @author Hyude * @version 1.0 */ public class InsPointer { public InsPointerEvent[] pressed = new InsPointerEvent[0]; public InsPointerEvent[] released = new InsPointerEvent[0]; public InsPointerEvent[] dragged = new InsPointerEvent[0]; public int holdCount = 0; public InsPoint[] hold = new InsPoint[0]; protected Vector holdList; protected Vector pressedEvents; protected Vector releasedEvents; protected Vector draggedEvents; protected Vector holdEvents; public InsPointer(){ super(); this.pressedEvents = new Vector(); this.releasedEvents = new Vector(); this.draggedEvents = new Vector(); this.holdEvents = new Vector(); this.holdList = new Vector(); } protected void resetEvent(){ this.pressedEvents.removeAllElements(); this.releasedEvents.removeAllElements(); this.draggedEvents.removeAllElements(); this.holdEvents.removeAllElements(); } public void addEvent(InsPointerEvent e){ if(e.type == InsPointerEvent.PRESSED){ this.pressedEvents.addElement(e); this.holdEvents.addElement(e); } else if(e.type == InsPointerEvent.RELEASED){ this.releasedEvents.addElement(e); this.holdEvents.addElement(e); } else if(e.type == InsPointerEvent.DRAGGED){ this.draggedEvents.addElement(e); this.holdEvents.addElement(e); } } public void updatePointerState(){ pressed = new InsPointerEvent[this.pressedEvents.size()]; for(int i = 0; i < pressed.length; i++){ pressed[i] = (InsPointerEvent) this.pressedEvents.elementAt(i); } released = new InsPointerEvent[this.releasedEvents.size()]; for(int i = 0; i < released.length; i++){ released[i] = (InsPointerEvent) this.releasedEvents.elementAt(i); } dragged = new InsPointerEvent[this.draggedEvents.size()]; for(int i = 0; i < dragged.length; i++){ dragged[i] = (InsPointerEvent) this.draggedEvents.elementAt(i); } for(int i = 0; i < this.holdEvents.size(); i++){ - InsPointerEvent e = (InsPointerEvent) this.draggedEvents.elementAt(i); + InsPointerEvent e = (InsPointerEvent) this.holdEvents.elementAt(i); if(e.type == InsPointerEvent.PRESSED){ this.addTouchPoint(e); } else if(e.type == InsPointerEvent.RELEASED){ this.removeTouchPoint(e); } else if(e.type == InsPointerEvent.DRAGGED){ this.moveTouchPoint(e); } } hold = new InsPoint[this.holdList.size()]; for(int i = 0; i < hold.length; i++){ hold[i] = (InsPoint) this.holdList.elementAt(i); } resetEvent(); } protected void addTouchPoint(InsPointerEvent e){ this.holdList.addElement(new InsPoint(e.x, e.y)); this.holdCount++; InsLogger.writeLog("Pointer Added"); } protected void removeTouchPoint(InsPointerEvent e){ int idx = this.searchNearestPoint(e.x, e.y); if(idx != -1){ this.holdList.removeElementAt(idx); InsLogger.writeLog("Pointer Removed"); } this.holdCount--; } protected void moveTouchPoint(InsPointerEvent e){ int idx = this.searchNearestPoint(e.x, e.y); if(idx != -1){ ((InsPoint) this.holdList.elementAt(idx)).setPoint(e.x, e.y); InsLogger.writeLog("Pointer Moved"); } } public int searchNearestPoint(int X, int Y){ int foundIdx = -1; int distance = 0; int tmpDist = 0; for(int i = 0; i < this.holdList.size(); i++) { InsPoint p = (InsPoint) this.holdList.elementAt(i); tmpDist = (int) InsUtil.Distance(p.x, X, p.y, Y); if(foundIdx == -1){ distance = tmpDist; foundIdx = i; } else { if(tmpDist < distance){ distance = tmpDist; foundIdx = i; } } } return foundIdx; } public boolean isAnythingPressed(){ return (this.holdCount > 0); } }
true
true
public void updatePointerState(){ pressed = new InsPointerEvent[this.pressedEvents.size()]; for(int i = 0; i < pressed.length; i++){ pressed[i] = (InsPointerEvent) this.pressedEvents.elementAt(i); } released = new InsPointerEvent[this.releasedEvents.size()]; for(int i = 0; i < released.length; i++){ released[i] = (InsPointerEvent) this.releasedEvents.elementAt(i); } dragged = new InsPointerEvent[this.draggedEvents.size()]; for(int i = 0; i < dragged.length; i++){ dragged[i] = (InsPointerEvent) this.draggedEvents.elementAt(i); } for(int i = 0; i < this.holdEvents.size(); i++){ InsPointerEvent e = (InsPointerEvent) this.draggedEvents.elementAt(i); if(e.type == InsPointerEvent.PRESSED){ this.addTouchPoint(e); } else if(e.type == InsPointerEvent.RELEASED){ this.removeTouchPoint(e); } else if(e.type == InsPointerEvent.DRAGGED){ this.moveTouchPoint(e); } } hold = new InsPoint[this.holdList.size()]; for(int i = 0; i < hold.length; i++){ hold[i] = (InsPoint) this.holdList.elementAt(i); } resetEvent(); }
public void updatePointerState(){ pressed = new InsPointerEvent[this.pressedEvents.size()]; for(int i = 0; i < pressed.length; i++){ pressed[i] = (InsPointerEvent) this.pressedEvents.elementAt(i); } released = new InsPointerEvent[this.releasedEvents.size()]; for(int i = 0; i < released.length; i++){ released[i] = (InsPointerEvent) this.releasedEvents.elementAt(i); } dragged = new InsPointerEvent[this.draggedEvents.size()]; for(int i = 0; i < dragged.length; i++){ dragged[i] = (InsPointerEvent) this.draggedEvents.elementAt(i); } for(int i = 0; i < this.holdEvents.size(); i++){ InsPointerEvent e = (InsPointerEvent) this.holdEvents.elementAt(i); if(e.type == InsPointerEvent.PRESSED){ this.addTouchPoint(e); } else if(e.type == InsPointerEvent.RELEASED){ this.removeTouchPoint(e); } else if(e.type == InsPointerEvent.DRAGGED){ this.moveTouchPoint(e); } } hold = new InsPoint[this.holdList.size()]; for(int i = 0; i < hold.length; i++){ hold[i] = (InsPoint) this.holdList.elementAt(i); } resetEvent(); }
diff --git a/drools-compiler/src/test/java/org/drools/semantics/java/StaticMethodFunctionResolverTest.java b/drools-compiler/src/test/java/org/drools/semantics/java/StaticMethodFunctionResolverTest.java index 832f8b4d5..357ba58d9 100644 --- a/drools-compiler/src/test/java/org/drools/semantics/java/StaticMethodFunctionResolverTest.java +++ b/drools-compiler/src/test/java/org/drools/semantics/java/StaticMethodFunctionResolverTest.java @@ -1,26 +1,26 @@ package org.drools.semantics.java; import java.util.ArrayList; import java.util.List; import org.drools.spi.FunctionResolver; import org.drools.spi.TypeResolver; import junit.framework.TestCase; public class StaticMethodFunctionResolverTest extends TestCase { public void test1() { List list = new ArrayList(); list.add( "org.drools.StaticMethods" ); TypeResolver typeResolver = new ClassTypeResolver( list ); list = new ArrayList(); list.add( "StaticMethods.*" ); FunctionResolver functionResolver = new StaticMethodFunctionResolver( list, typeResolver ); - System.out.println( functionResolver.resolveFunction( "getString", 1 ) ); + System.out.println( functionResolver.resolveFunction( "getString1", 1 ) ); } }
true
true
public void test1() { List list = new ArrayList(); list.add( "org.drools.StaticMethods" ); TypeResolver typeResolver = new ClassTypeResolver( list ); list = new ArrayList(); list.add( "StaticMethods.*" ); FunctionResolver functionResolver = new StaticMethodFunctionResolver( list, typeResolver ); System.out.println( functionResolver.resolveFunction( "getString", 1 ) ); }
public void test1() { List list = new ArrayList(); list.add( "org.drools.StaticMethods" ); TypeResolver typeResolver = new ClassTypeResolver( list ); list = new ArrayList(); list.add( "StaticMethods.*" ); FunctionResolver functionResolver = new StaticMethodFunctionResolver( list, typeResolver ); System.out.println( functionResolver.resolveFunction( "getString1", 1 ) ); }
diff --git a/src/org/openstreetmap/josm/gui/dialogs/LayerListDialog.java b/src/org/openstreetmap/josm/gui/dialogs/LayerListDialog.java index 079dd703..1f552ef9 100644 --- a/src/org/openstreetmap/josm/gui/dialogs/LayerListDialog.java +++ b/src/org/openstreetmap/josm/gui/dialogs/LayerListDialog.java @@ -1,344 +1,356 @@ // License: GPL. Copyright 2007 by Immanuel Scholz and others package org.openstreetmap.josm.gui.dialogs; import static org.openstreetmap.josm.tools.I18n.tr; import java.awt.BorderLayout; import java.awt.Component; import java.awt.GridLayout; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.Collection; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.DefaultListCellRenderer; import javax.swing.DefaultListModel; import javax.swing.Icon; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.ListSelectionModel; import javax.swing.UIManager; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import org.openstreetmap.josm.Main; import org.openstreetmap.josm.gui.ConditionalOptionPaneUtil; import org.openstreetmap.josm.gui.ExtendedDialog; import org.openstreetmap.josm.gui.MapFrame; import org.openstreetmap.josm.gui.MapView; import org.openstreetmap.josm.gui.SideButton; import org.openstreetmap.josm.gui.layer.Layer; import org.openstreetmap.josm.gui.layer.OsmDataLayer; import org.openstreetmap.josm.gui.layer.Layer.LayerChangeListener; import org.openstreetmap.josm.tools.ImageProvider; import org.openstreetmap.josm.tools.ImageProvider.OverlayPosition; import org.openstreetmap.josm.tools.Shortcut; /** * A component that manages the list of all layers and react to selection changes * by setting the active layer in the mapview. * * @author imi */ public class LayerListDialog extends ToggleDialog implements LayerChangeListener { /** * The last layerlist created. Used to update the list in the Show/Hide and Delete actions. * TODO: Replace with Listener-Pattern. */ static JList instance; private JScrollPane listScrollPane; public final static class DeleteLayerAction extends AbstractAction { private final Layer layer; public DeleteLayerAction(Layer layer) { super(tr("Delete"), ImageProvider.get("dialogs", "delete")); putValue(SHORT_DESCRIPTION, tr("Delete the selected layer.")); putValue("help", "Action/LayerDelete"); this.layer = layer; } public void actionPerformed(ActionEvent e) { int sel = instance.getSelectedIndex(); Layer l = layer != null ? layer : (Layer)instance.getSelectedValue(); if(l == null) return; if (l instanceof OsmDataLayer) { if (((OsmDataLayer)l).isModified()) { int result = new ExtendedDialog(Main.parent, tr("Unsaved Changes"), tr("There are unsaved changes. Delete the layer anwyay?"), new String[] {tr("Delete Layer"), tr("Cancel")}, new String[] {"dialogs/delete.png", "cancel.png"}).getValue(); if(result != 1) return; } else if (!ConditionalOptionPaneUtil.showConfirmationDialog( "delete_layer", Main.parent, tr("Do you really want to delete the whole layer?"), tr("Confirmation"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_OPTION)) return; } Main.main.removeLayer(l); if (sel >= instance.getModel().getSize()) { sel = instance.getModel().getSize()-1; } if (instance.getSelectedValue() == null) { instance.setSelectedIndex(sel); } if (Main.map != null) { Main.map.mapView.setActiveLayer((Layer)instance.getSelectedValue()); } } } public final static class ShowHideLayerAction extends AbstractAction { private final Layer layer; public ShowHideLayerAction(Layer layer) { super(tr("Show/Hide"), ImageProvider.get("dialogs", "showhide")); putValue(SHORT_DESCRIPTION, tr("Toggle visible state of the selected layer.")); putValue("help", "Action/LayerShowHide"); this.layer = layer; } public void actionPerformed(ActionEvent e) { Layer l = layer == null ? (Layer)instance.getSelectedValue() : layer; if(l == null) return; l.visible = !l.visible; Main.map.mapView.repaint(); instance.repaint(); } } public final static class ShowHideMarkerText extends AbstractAction { private final Layer layer; public ShowHideMarkerText(Layer layer) { super(tr("Show/Hide Text/Icons"), ImageProvider.get("dialogs", "showhide")); putValue(SHORT_DESCRIPTION, tr("Toggle visible state of the marker text and icons.")); putValue("help", "Action/ShowHideTextIcons"); this.layer = layer; } public void actionPerformed(ActionEvent e) { Layer l = layer == null ? (Layer)instance.getSelectedValue() : layer; String current = Main.pref.get("marker.show "+l.name,"show"); Main.pref.put("marker.show "+l.name, current.equalsIgnoreCase("show") ? "hide" : "show"); Main.map.mapView.repaint(); instance.repaint(); } } /** * The data model for the list component. */ DefaultListModel model = new DefaultListModel(); /** * The merge action. This is only called, if the current selection and its * item below are editable datasets and the merge button is clicked. */ private final SideButton mergeButton; /** * Button for moving layer up. */ private final SideButton upButton; /** * Button for moving layer down. */ private final SideButton downButton; /** * Button for delete layer. */ private Action deleteAction = new DeleteLayerAction(null); /** * Create an layerlist and attach it to the given mapView. */ public LayerListDialog(MapFrame mapFrame) { super(tr("Layers"), "layerlist", tr("Open a list of all loaded layers."), Shortcut.registerShortcut("subwindow:layers", tr("Toggle: {0}", tr("Layers")), KeyEvent.VK_L, Shortcut.GROUP_LAYER), 100); - instance = new JList(model); + instance = new JList(model) { + @Override + protected void processMouseEvent(MouseEvent e) { + // if the layer list is embedded in a detached dialog, the last row is + // is selected if a user clicks in the empty space *below* the last row. + // This mouse event filter prevents this. + // + int idx = locationToIndex(e.getPoint()); + if (getCellBounds(idx, idx).contains(e.getPoint())) { + super.processMouseEvent(e); + } + } + }; listScrollPane = new JScrollPane(instance); add(listScrollPane, BorderLayout.CENTER); instance.setBackground(UIManager.getColor("Button.background")); instance.setCellRenderer(new DefaultListCellRenderer(){ @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { Layer layer = (Layer)value; JLabel label = (JLabel)super.getListCellRendererComponent(list, layer.name, index, isSelected, cellHasFocus); Icon icon = layer.getIcon(); if (!layer.visible) { icon = ImageProvider.overlay(icon, "overlay/invisible", OverlayPosition.SOUTHEAST); } label.setIcon(icon); label.setToolTipText(layer.getToolTipText()); return label; } }); final MapView mapView = mapFrame.mapView; Collection<Layer> data = mapView.getAllLayers(); for (Layer l : data) { model.addElement(l); } instance.setSelectedValue(mapView.getActiveLayer(), true); instance.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); instance.addListSelectionListener(new ListSelectionListener(){ public void valueChanged(ListSelectionEvent e) { if (instance.getModel().getSize() == 0) return; if (instance.getSelectedIndex() == -1) { instance.setSelectedIndex(e.getFirstIndex()); } mapView.setActiveLayer((Layer)instance.getSelectedValue()); } }); Layer.listeners.add(this); instance.addMouseListener(new MouseAdapter(){ private void openPopup(MouseEvent e) { Point p = e.getPoint(); int index = instance.locationToIndex(p); Layer layer = (Layer)instance.getModel().getElementAt(index); LayerListPopup menu = new LayerListPopup(instance, layer); menu.show(listScrollPane, p.x, p.y-3); } @Override public void mousePressed(MouseEvent e) { if (e.isPopupTrigger()) { openPopup(e); } } @Override public void mouseReleased(MouseEvent e) { if (e.isPopupTrigger()) { openPopup(e); } } @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { int index = instance.locationToIndex(e.getPoint()); Layer layer = (Layer)instance.getModel().getElementAt(index); String current = Main.pref.get("marker.show "+layer.name,"show"); Main.pref.put("marker.show "+layer.name, current.equalsIgnoreCase("show") ? "hide" : "show"); layer.visible = !layer.visible; Main.map.mapView.repaint(); instance.repaint(); } } }); // Buttons JPanel buttonPanel = new JPanel(new GridLayout(1, 5)); ActionListener upDown = new ActionListener(){ public void actionPerformed(ActionEvent e) { Layer l = (Layer)instance.getSelectedValue(); int sel = instance.getSelectedIndex(); int selDest = e.getActionCommand().equals("up") ? sel-1 : sel+1; mapView.moveLayer(l, selDest); model.set(sel, model.get(selDest)); model.set(selDest, l); instance.setSelectedIndex(selDest); updateButtonEnabled(); mapView.repaint(); } }; upButton = new SideButton("up", "LayerList", tr("Move the selected layer one row up."), upDown); buttonPanel.add(upButton); downButton = new SideButton("down", "LayerList", tr("Move the selected layer one row down."), upDown); buttonPanel.add(downButton); buttonPanel.add(new SideButton(new ShowHideLayerAction(null), "showhide")); buttonPanel.add(new SideButton(deleteAction, "delete")); mergeButton = new SideButton("mergedown", "LayerList", tr("Merge the layer directly below into the selected layer."), new ActionListener(){ public void actionPerformed(ActionEvent e) { Layer lTo = (Layer)instance.getSelectedValue(); Layer lFrom = (Layer)model.get(instance.getSelectedIndex()+1); lTo.mergeFrom(lFrom); mapView.removeLayer(lFrom); updateButtonEnabled(); mapView.repaint(); } }); buttonPanel.add(mergeButton); add(buttonPanel, BorderLayout.SOUTH); updateButtonEnabled(); } /** * Updates the state of the Buttons. */ void updateButtonEnabled() { int sel = instance.getSelectedIndex(); Layer l = (Layer)instance.getSelectedValue(); boolean enable = model.getSize() > 1; enable = enable && sel < model.getSize()-1; enable = enable && ((Layer)model.get(sel+1)).isMergable(l); mergeButton.setEnabled(enable); upButton.setEnabled(sel > 0); downButton.setEnabled(sel >= 0 && sel < model.getSize()-1); deleteAction.setEnabled(!model.isEmpty()); if(model.getSize() != 0) { setTitle(tr("Layers: {0}", model.getSize()), true); } else { setTitle(tr("Layers"), false); } } /** * Add the new layer to the list. */ public void layerAdded(Layer newLayer) { int pos = Main.map.mapView.getLayerPos(newLayer); model.add(pos, newLayer); updateButtonEnabled(); } public void layerRemoved(Layer oldLayer) { model.removeElement(oldLayer); if (model.isEmpty()) { Layer.listeners.remove(this); return; } if (instance.getSelectedIndex() == -1) { instance.setSelectedIndex(0); } updateButtonEnabled(); } /** * If the newLayer is not the actual selection, select it. */ public void activeLayerChange(Layer oldLayer, Layer newLayer) { if (newLayer != instance.getSelectedValue()) { instance.setSelectedValue(newLayer, true); } updateButtonEnabled(); } }
true
true
public LayerListDialog(MapFrame mapFrame) { super(tr("Layers"), "layerlist", tr("Open a list of all loaded layers."), Shortcut.registerShortcut("subwindow:layers", tr("Toggle: {0}", tr("Layers")), KeyEvent.VK_L, Shortcut.GROUP_LAYER), 100); instance = new JList(model); listScrollPane = new JScrollPane(instance); add(listScrollPane, BorderLayout.CENTER); instance.setBackground(UIManager.getColor("Button.background")); instance.setCellRenderer(new DefaultListCellRenderer(){ @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { Layer layer = (Layer)value; JLabel label = (JLabel)super.getListCellRendererComponent(list, layer.name, index, isSelected, cellHasFocus); Icon icon = layer.getIcon(); if (!layer.visible) { icon = ImageProvider.overlay(icon, "overlay/invisible", OverlayPosition.SOUTHEAST); } label.setIcon(icon); label.setToolTipText(layer.getToolTipText()); return label; } }); final MapView mapView = mapFrame.mapView; Collection<Layer> data = mapView.getAllLayers(); for (Layer l : data) { model.addElement(l); } instance.setSelectedValue(mapView.getActiveLayer(), true); instance.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); instance.addListSelectionListener(new ListSelectionListener(){ public void valueChanged(ListSelectionEvent e) { if (instance.getModel().getSize() == 0) return; if (instance.getSelectedIndex() == -1) { instance.setSelectedIndex(e.getFirstIndex()); } mapView.setActiveLayer((Layer)instance.getSelectedValue()); } }); Layer.listeners.add(this); instance.addMouseListener(new MouseAdapter(){ private void openPopup(MouseEvent e) { Point p = e.getPoint(); int index = instance.locationToIndex(p); Layer layer = (Layer)instance.getModel().getElementAt(index); LayerListPopup menu = new LayerListPopup(instance, layer); menu.show(listScrollPane, p.x, p.y-3); } @Override public void mousePressed(MouseEvent e) { if (e.isPopupTrigger()) { openPopup(e); } } @Override public void mouseReleased(MouseEvent e) { if (e.isPopupTrigger()) { openPopup(e); } } @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { int index = instance.locationToIndex(e.getPoint()); Layer layer = (Layer)instance.getModel().getElementAt(index); String current = Main.pref.get("marker.show "+layer.name,"show"); Main.pref.put("marker.show "+layer.name, current.equalsIgnoreCase("show") ? "hide" : "show"); layer.visible = !layer.visible; Main.map.mapView.repaint(); instance.repaint(); } } }); // Buttons JPanel buttonPanel = new JPanel(new GridLayout(1, 5)); ActionListener upDown = new ActionListener(){ public void actionPerformed(ActionEvent e) { Layer l = (Layer)instance.getSelectedValue(); int sel = instance.getSelectedIndex(); int selDest = e.getActionCommand().equals("up") ? sel-1 : sel+1; mapView.moveLayer(l, selDest); model.set(sel, model.get(selDest)); model.set(selDest, l); instance.setSelectedIndex(selDest); updateButtonEnabled(); mapView.repaint(); } }; upButton = new SideButton("up", "LayerList", tr("Move the selected layer one row up."), upDown); buttonPanel.add(upButton); downButton = new SideButton("down", "LayerList", tr("Move the selected layer one row down."), upDown); buttonPanel.add(downButton); buttonPanel.add(new SideButton(new ShowHideLayerAction(null), "showhide")); buttonPanel.add(new SideButton(deleteAction, "delete")); mergeButton = new SideButton("mergedown", "LayerList", tr("Merge the layer directly below into the selected layer."), new ActionListener(){ public void actionPerformed(ActionEvent e) { Layer lTo = (Layer)instance.getSelectedValue(); Layer lFrom = (Layer)model.get(instance.getSelectedIndex()+1); lTo.mergeFrom(lFrom); mapView.removeLayer(lFrom); updateButtonEnabled(); mapView.repaint(); } }); buttonPanel.add(mergeButton); add(buttonPanel, BorderLayout.SOUTH); updateButtonEnabled(); }
public LayerListDialog(MapFrame mapFrame) { super(tr("Layers"), "layerlist", tr("Open a list of all loaded layers."), Shortcut.registerShortcut("subwindow:layers", tr("Toggle: {0}", tr("Layers")), KeyEvent.VK_L, Shortcut.GROUP_LAYER), 100); instance = new JList(model) { @Override protected void processMouseEvent(MouseEvent e) { // if the layer list is embedded in a detached dialog, the last row is // is selected if a user clicks in the empty space *below* the last row. // This mouse event filter prevents this. // int idx = locationToIndex(e.getPoint()); if (getCellBounds(idx, idx).contains(e.getPoint())) { super.processMouseEvent(e); } } }; listScrollPane = new JScrollPane(instance); add(listScrollPane, BorderLayout.CENTER); instance.setBackground(UIManager.getColor("Button.background")); instance.setCellRenderer(new DefaultListCellRenderer(){ @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { Layer layer = (Layer)value; JLabel label = (JLabel)super.getListCellRendererComponent(list, layer.name, index, isSelected, cellHasFocus); Icon icon = layer.getIcon(); if (!layer.visible) { icon = ImageProvider.overlay(icon, "overlay/invisible", OverlayPosition.SOUTHEAST); } label.setIcon(icon); label.setToolTipText(layer.getToolTipText()); return label; } }); final MapView mapView = mapFrame.mapView; Collection<Layer> data = mapView.getAllLayers(); for (Layer l : data) { model.addElement(l); } instance.setSelectedValue(mapView.getActiveLayer(), true); instance.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); instance.addListSelectionListener(new ListSelectionListener(){ public void valueChanged(ListSelectionEvent e) { if (instance.getModel().getSize() == 0) return; if (instance.getSelectedIndex() == -1) { instance.setSelectedIndex(e.getFirstIndex()); } mapView.setActiveLayer((Layer)instance.getSelectedValue()); } }); Layer.listeners.add(this); instance.addMouseListener(new MouseAdapter(){ private void openPopup(MouseEvent e) { Point p = e.getPoint(); int index = instance.locationToIndex(p); Layer layer = (Layer)instance.getModel().getElementAt(index); LayerListPopup menu = new LayerListPopup(instance, layer); menu.show(listScrollPane, p.x, p.y-3); } @Override public void mousePressed(MouseEvent e) { if (e.isPopupTrigger()) { openPopup(e); } } @Override public void mouseReleased(MouseEvent e) { if (e.isPopupTrigger()) { openPopup(e); } } @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { int index = instance.locationToIndex(e.getPoint()); Layer layer = (Layer)instance.getModel().getElementAt(index); String current = Main.pref.get("marker.show "+layer.name,"show"); Main.pref.put("marker.show "+layer.name, current.equalsIgnoreCase("show") ? "hide" : "show"); layer.visible = !layer.visible; Main.map.mapView.repaint(); instance.repaint(); } } }); // Buttons JPanel buttonPanel = new JPanel(new GridLayout(1, 5)); ActionListener upDown = new ActionListener(){ public void actionPerformed(ActionEvent e) { Layer l = (Layer)instance.getSelectedValue(); int sel = instance.getSelectedIndex(); int selDest = e.getActionCommand().equals("up") ? sel-1 : sel+1; mapView.moveLayer(l, selDest); model.set(sel, model.get(selDest)); model.set(selDest, l); instance.setSelectedIndex(selDest); updateButtonEnabled(); mapView.repaint(); } }; upButton = new SideButton("up", "LayerList", tr("Move the selected layer one row up."), upDown); buttonPanel.add(upButton); downButton = new SideButton("down", "LayerList", tr("Move the selected layer one row down."), upDown); buttonPanel.add(downButton); buttonPanel.add(new SideButton(new ShowHideLayerAction(null), "showhide")); buttonPanel.add(new SideButton(deleteAction, "delete")); mergeButton = new SideButton("mergedown", "LayerList", tr("Merge the layer directly below into the selected layer."), new ActionListener(){ public void actionPerformed(ActionEvent e) { Layer lTo = (Layer)instance.getSelectedValue(); Layer lFrom = (Layer)model.get(instance.getSelectedIndex()+1); lTo.mergeFrom(lFrom); mapView.removeLayer(lFrom); updateButtonEnabled(); mapView.repaint(); } }); buttonPanel.add(mergeButton); add(buttonPanel, BorderLayout.SOUTH); updateButtonEnabled(); }
diff --git a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/remote/launch/PerfLaunchConfigDelegate.java b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/remote/launch/PerfLaunchConfigDelegate.java index 5bf7c8a96..a7f2f56b2 100644 --- a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/remote/launch/PerfLaunchConfigDelegate.java +++ b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/remote/launch/PerfLaunchConfigDelegate.java @@ -1,220 +1,221 @@ /******************************************************************************* * Copyright (c) 2004, 2008, 2009 Red Hat, Inc. and others * (C) Copyright IBM Corp. 2010 * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Kent Sebastian <[email protected]> - initial API and implementation * Keith Seitz <[email protected]> - setup code in launch the method, initially * written in the now-defunct OprofileSession class * QNX Software Systems and others - the section of code marked in the launch * method, and the exec method * Thavidu Ranatunga (IBM) - This code is based on the AbstractOprofileLauncher * class code for the OProfile plugin. Part of that was originally adapted * from code written by QNX Software Systems and others for the CDT * LocalCDILaunchDelegate class. *******************************************************************************/ package org.eclipse.linuxtools.internal.perf.remote.launch; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintStream; import org.eclipse.ui.console.*; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Arrays; import org.eclipse.cdt.debug.core.ICDTLaunchConfigurationConstants; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.debug.core.ILaunch; import org.eclipse.debug.core.ILaunchConfiguration; import org.eclipse.debug.ui.IDebugUIConstants; import org.eclipse.linuxtools.internal.perf.PerfCore; import org.eclipse.linuxtools.internal.perf.PerfPlugin; import org.eclipse.linuxtools.profiling.launch.ProfileLaunchConfigurationDelegate; import org.eclipse.linuxtools.profiling.launch.ConfigUtils; import org.eclipse.linuxtools.profiling.launch.IRemoteFileProxy; import org.eclipse.linuxtools.profiling.launch.RemoteConnection; import org.eclipse.linuxtools.profiling.launch.RemoteConnectionException; import org.eclipse.linuxtools.tools.launch.core.factory.RuntimeProcessFactory; import org.eclipse.core.filesystem.EFS; import org.eclipse.core.filesystem.IFileInfo; import org.eclipse.core.filesystem.IFileStore; public class PerfLaunchConfigDelegate extends ProfileLaunchConfigurationDelegate { private ConfigUtils configUtils; private static String OUTPUT_STR = "--output="; //$NON-NLS-1$ @Override protected String getPluginID() { return PerfPlugin.PLUGIN_ID; } @Override public void launch(ILaunchConfiguration config, String mode, ILaunch launch, IProgressMonitor monitor) throws CoreException { try { this.configUtils = new ConfigUtils(config); IProject project = ConfigUtils.getProject(configUtils.getProjectName()); // check if Perf exists in $PATH if (! PerfCore.checkRemotePerfInPath(project)) { IStatus status = new Status(IStatus.ERROR, PerfPlugin.PLUGIN_ID, "Error: Perf was not found on PATH"); //$NON-NLS-1$ throw new CoreException(status); } URI exeURI = new URI(configUtils.getExecutablePath()); String configWorkingDir = configUtils.getWorkingDirectory(); RemoteConnection exeRC = new RemoteConnection(exeURI); String perfPathString = RuntimeProcessFactory.getFactory().whichCommand(PerfPlugin.PERF_COMMAND, project); boolean copyExecutable = configUtils.getCopyExecutable(); if (copyExecutable) { URI copyExeURI = new URI(configUtils.getCopyFromExecutablePath()); RemoteConnection copyExeRC = new RemoteConnection(copyExeURI); IRemoteFileProxy copyExeRFP = copyExeRC.getRmtFileProxy(); IFileStore copyExeFS = copyExeRFP.getResource(copyExeURI.getPath()); IRemoteFileProxy exeRFP = exeRC.getRmtFileProxy(); IFileStore exeFS = exeRFP.getResource(exeURI.getPath()); IFileInfo exeFI = exeFS.fetchInfo(); if (exeFI.isDirectory()) { // Assume the user wants to copy the file to the given directory, using // the same filename as the "copy from" executable. IPath copyExePath = Path.fromOSString(copyExeURI.getPath()); IPath newExePath = Path.fromOSString(exeURI.getPath()).append(copyExePath.lastSegment()); // update the exeURI with the new path. exeURI = new URI(exeURI.getScheme(), exeURI.getAuthority(), newExePath.toString(), exeURI.getQuery(), exeURI.getFragment()); exeFS = exeRFP.getResource(exeURI.getPath()); } copyExeFS.copy(exeFS, EFS.OVERWRITE | EFS.SHALLOW, new SubProgressMonitor(monitor, 1)); // Note: assume that we don't need to create a new exeRC since the // scheme and authority remain the same between the original exeURI and the new one. } IPath remoteBinFile = Path.fromOSString(exeURI.getPath()); IFileStore workingDir; if(configWorkingDir == null){ // If no working directory was provided, use the directory containing the // the executable as the working directory. IPath workingDirPath = (Path.fromPortableString(remoteBinFile.removeLastSegments(1).toOSString())); IRemoteFileProxy workingDirRFP = exeRC.getRmtFileProxy(); workingDir = workingDirRFP.getResource(workingDirPath.toOSString()); } else { URI workingDirURI = new URI(configUtils.getWorkingDirectory()); RemoteConnection workingDirRC = new RemoteConnection(workingDirURI); IRemoteFileProxy workingDirRFP = workingDirRC.getRmtFileProxy(); workingDir = workingDirRFP.getResource(workingDirURI.getPath()); } //Build the commandline string to run perf recording the given project String arguments[] = getProgramArgumentsArray( config ); //Program args from launch config. ArrayList<String> command = new ArrayList<String>( 4 + arguments.length ); command.addAll(Arrays.asList(PerfCore.getRecordString(config))); //Get the base commandline string (with flags/options based on config) command.add( remoteBinFile.toOSString() ); // Add the path to the executable command.set(0, perfPathString); command.add(2,OUTPUT_STR + configWorkingDir + IPath.SEPARATOR + PerfPlugin.PERF_DEFAULT_DATA); //Compile string command.addAll( Arrays.asList( arguments ) ); //Spawn the process String[] commandArray = command.toArray(new String[command.size()]); Process pProxy = RuntimeProcessFactory.getFactory().exec(commandArray, getEnvironment(config), workingDir, project); MessageConsole console = new MessageConsole("Perf Console", null); //$NON-NLS-1$ console.activate(); ConsolePlugin.getDefault().getConsoleManager().addConsoles(new IConsole[] { console }); MessageConsoleStream stream = console.newMessageStream(); if (pProxy != null) { BufferedReader error = new BufferedReader( new InputStreamReader(pProxy.getErrorStream())); String err; err = error.readLine(); while (err != null) { stream.println(err); err = error.readLine(); } error.close(); } /* This commented part is the basic method to run perf record without integrating into eclipse. String binCall = exePath.toOSString(); for(String arg : arguments) { binCall.concat(" " + arg); } PerfCore.Run(binCall);*/ pProxy.destroy(); PrintStream print = null; if (config.getAttribute(IDebugUIConstants.ATTR_CAPTURE_IN_CONSOLE, true)) { //Get the console to output to. //This may not be the best way to accomplish this but it shall do for now. ConsolePlugin plugin = ConsolePlugin.getDefault(); IConsoleManager conMan = plugin.getConsoleManager(); IConsole[] existing = conMan.getConsoles(); IOConsole binaryOutCons = null; //Find the console for(IConsole x : existing) { if (x.getName().contains(renderProcessLabel(commandArray[0]))) { binaryOutCons = (IOConsole)x; } } if ((binaryOutCons == null) && (existing.length != 0)) { //if can't be found get the most recent opened, this should probably never happen. if (existing[existing.length - 1] instanceof IOConsole) binaryOutCons = (IOConsole)existing[existing.length - 1]; } //Get the printstream via the outputstream. //Get ouput stream OutputStream outputTo; if (binaryOutCons != null) { outputTo = binaryOutCons.newOutputStream(); //Get the printstream for that console print = new PrintStream(outputTo); } for (int i = 0; i < command.size(); i++) { print.print(command.get(i) + " "); } //Print Message print.println(); print.println("Analysing recorded perf.data, please wait..."); //Possibly should pass this (the console reference) on to PerfCore.Report if theres anything we ever want to spit out to user. } PerfCore.Report(config, getEnvironment(config), Path.fromOSString(configWorkingDir + IPath.SEPARATOR), monitor, null, print); + PerfCore.RefreshView(renderProcessLabel(exeURI.getPath())); } catch (IOException e) { e.printStackTrace(); abort(e.getLocalizedMessage(), null, ICDTLaunchConfigurationConstants.ERR_INTERNAL_ERROR); } catch (RemoteConnectionException e) { e.printStackTrace(); abort(e.getLocalizedMessage(), null, ICDTLaunchConfigurationConstants.ERR_INTERNAL_ERROR); } catch (URISyntaxException e) { e.printStackTrace(); abort(e.getLocalizedMessage(), null, ICDTLaunchConfigurationConstants.ERR_INTERNAL_ERROR); } // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } } }
true
true
public void launch(ILaunchConfiguration config, String mode, ILaunch launch, IProgressMonitor monitor) throws CoreException { try { this.configUtils = new ConfigUtils(config); IProject project = ConfigUtils.getProject(configUtils.getProjectName()); // check if Perf exists in $PATH if (! PerfCore.checkRemotePerfInPath(project)) { IStatus status = new Status(IStatus.ERROR, PerfPlugin.PLUGIN_ID, "Error: Perf was not found on PATH"); //$NON-NLS-1$ throw new CoreException(status); } URI exeURI = new URI(configUtils.getExecutablePath()); String configWorkingDir = configUtils.getWorkingDirectory(); RemoteConnection exeRC = new RemoteConnection(exeURI); String perfPathString = RuntimeProcessFactory.getFactory().whichCommand(PerfPlugin.PERF_COMMAND, project); boolean copyExecutable = configUtils.getCopyExecutable(); if (copyExecutable) { URI copyExeURI = new URI(configUtils.getCopyFromExecutablePath()); RemoteConnection copyExeRC = new RemoteConnection(copyExeURI); IRemoteFileProxy copyExeRFP = copyExeRC.getRmtFileProxy(); IFileStore copyExeFS = copyExeRFP.getResource(copyExeURI.getPath()); IRemoteFileProxy exeRFP = exeRC.getRmtFileProxy(); IFileStore exeFS = exeRFP.getResource(exeURI.getPath()); IFileInfo exeFI = exeFS.fetchInfo(); if (exeFI.isDirectory()) { // Assume the user wants to copy the file to the given directory, using // the same filename as the "copy from" executable. IPath copyExePath = Path.fromOSString(copyExeURI.getPath()); IPath newExePath = Path.fromOSString(exeURI.getPath()).append(copyExePath.lastSegment()); // update the exeURI with the new path. exeURI = new URI(exeURI.getScheme(), exeURI.getAuthority(), newExePath.toString(), exeURI.getQuery(), exeURI.getFragment()); exeFS = exeRFP.getResource(exeURI.getPath()); } copyExeFS.copy(exeFS, EFS.OVERWRITE | EFS.SHALLOW, new SubProgressMonitor(monitor, 1)); // Note: assume that we don't need to create a new exeRC since the // scheme and authority remain the same between the original exeURI and the new one. } IPath remoteBinFile = Path.fromOSString(exeURI.getPath()); IFileStore workingDir; if(configWorkingDir == null){ // If no working directory was provided, use the directory containing the // the executable as the working directory. IPath workingDirPath = (Path.fromPortableString(remoteBinFile.removeLastSegments(1).toOSString())); IRemoteFileProxy workingDirRFP = exeRC.getRmtFileProxy(); workingDir = workingDirRFP.getResource(workingDirPath.toOSString()); } else { URI workingDirURI = new URI(configUtils.getWorkingDirectory()); RemoteConnection workingDirRC = new RemoteConnection(workingDirURI); IRemoteFileProxy workingDirRFP = workingDirRC.getRmtFileProxy(); workingDir = workingDirRFP.getResource(workingDirURI.getPath()); } //Build the commandline string to run perf recording the given project String arguments[] = getProgramArgumentsArray( config ); //Program args from launch config. ArrayList<String> command = new ArrayList<String>( 4 + arguments.length ); command.addAll(Arrays.asList(PerfCore.getRecordString(config))); //Get the base commandline string (with flags/options based on config) command.add( remoteBinFile.toOSString() ); // Add the path to the executable command.set(0, perfPathString); command.add(2,OUTPUT_STR + configWorkingDir + IPath.SEPARATOR + PerfPlugin.PERF_DEFAULT_DATA); //Compile string command.addAll( Arrays.asList( arguments ) ); //Spawn the process String[] commandArray = command.toArray(new String[command.size()]); Process pProxy = RuntimeProcessFactory.getFactory().exec(commandArray, getEnvironment(config), workingDir, project); MessageConsole console = new MessageConsole("Perf Console", null); //$NON-NLS-1$ console.activate(); ConsolePlugin.getDefault().getConsoleManager().addConsoles(new IConsole[] { console }); MessageConsoleStream stream = console.newMessageStream(); if (pProxy != null) { BufferedReader error = new BufferedReader( new InputStreamReader(pProxy.getErrorStream())); String err; err = error.readLine(); while (err != null) { stream.println(err); err = error.readLine(); } error.close(); } /* This commented part is the basic method to run perf record without integrating into eclipse. String binCall = exePath.toOSString(); for(String arg : arguments) { binCall.concat(" " + arg); } PerfCore.Run(binCall);*/ pProxy.destroy(); PrintStream print = null; if (config.getAttribute(IDebugUIConstants.ATTR_CAPTURE_IN_CONSOLE, true)) { //Get the console to output to. //This may not be the best way to accomplish this but it shall do for now. ConsolePlugin plugin = ConsolePlugin.getDefault(); IConsoleManager conMan = plugin.getConsoleManager(); IConsole[] existing = conMan.getConsoles(); IOConsole binaryOutCons = null; //Find the console for(IConsole x : existing) { if (x.getName().contains(renderProcessLabel(commandArray[0]))) { binaryOutCons = (IOConsole)x; } } if ((binaryOutCons == null) && (existing.length != 0)) { //if can't be found get the most recent opened, this should probably never happen. if (existing[existing.length - 1] instanceof IOConsole) binaryOutCons = (IOConsole)existing[existing.length - 1]; } //Get the printstream via the outputstream. //Get ouput stream OutputStream outputTo; if (binaryOutCons != null) { outputTo = binaryOutCons.newOutputStream(); //Get the printstream for that console print = new PrintStream(outputTo); } for (int i = 0; i < command.size(); i++) { print.print(command.get(i) + " "); } //Print Message print.println(); print.println("Analysing recorded perf.data, please wait..."); //Possibly should pass this (the console reference) on to PerfCore.Report if theres anything we ever want to spit out to user. } PerfCore.Report(config, getEnvironment(config), Path.fromOSString(configWorkingDir + IPath.SEPARATOR), monitor, null, print); } catch (IOException e) { e.printStackTrace(); abort(e.getLocalizedMessage(), null, ICDTLaunchConfigurationConstants.ERR_INTERNAL_ERROR); } catch (RemoteConnectionException e) { e.printStackTrace(); abort(e.getLocalizedMessage(), null, ICDTLaunchConfigurationConstants.ERR_INTERNAL_ERROR); } catch (URISyntaxException e) { e.printStackTrace(); abort(e.getLocalizedMessage(), null, ICDTLaunchConfigurationConstants.ERR_INTERNAL_ERROR); } // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } }
public void launch(ILaunchConfiguration config, String mode, ILaunch launch, IProgressMonitor monitor) throws CoreException { try { this.configUtils = new ConfigUtils(config); IProject project = ConfigUtils.getProject(configUtils.getProjectName()); // check if Perf exists in $PATH if (! PerfCore.checkRemotePerfInPath(project)) { IStatus status = new Status(IStatus.ERROR, PerfPlugin.PLUGIN_ID, "Error: Perf was not found on PATH"); //$NON-NLS-1$ throw new CoreException(status); } URI exeURI = new URI(configUtils.getExecutablePath()); String configWorkingDir = configUtils.getWorkingDirectory(); RemoteConnection exeRC = new RemoteConnection(exeURI); String perfPathString = RuntimeProcessFactory.getFactory().whichCommand(PerfPlugin.PERF_COMMAND, project); boolean copyExecutable = configUtils.getCopyExecutable(); if (copyExecutable) { URI copyExeURI = new URI(configUtils.getCopyFromExecutablePath()); RemoteConnection copyExeRC = new RemoteConnection(copyExeURI); IRemoteFileProxy copyExeRFP = copyExeRC.getRmtFileProxy(); IFileStore copyExeFS = copyExeRFP.getResource(copyExeURI.getPath()); IRemoteFileProxy exeRFP = exeRC.getRmtFileProxy(); IFileStore exeFS = exeRFP.getResource(exeURI.getPath()); IFileInfo exeFI = exeFS.fetchInfo(); if (exeFI.isDirectory()) { // Assume the user wants to copy the file to the given directory, using // the same filename as the "copy from" executable. IPath copyExePath = Path.fromOSString(copyExeURI.getPath()); IPath newExePath = Path.fromOSString(exeURI.getPath()).append(copyExePath.lastSegment()); // update the exeURI with the new path. exeURI = new URI(exeURI.getScheme(), exeURI.getAuthority(), newExePath.toString(), exeURI.getQuery(), exeURI.getFragment()); exeFS = exeRFP.getResource(exeURI.getPath()); } copyExeFS.copy(exeFS, EFS.OVERWRITE | EFS.SHALLOW, new SubProgressMonitor(monitor, 1)); // Note: assume that we don't need to create a new exeRC since the // scheme and authority remain the same between the original exeURI and the new one. } IPath remoteBinFile = Path.fromOSString(exeURI.getPath()); IFileStore workingDir; if(configWorkingDir == null){ // If no working directory was provided, use the directory containing the // the executable as the working directory. IPath workingDirPath = (Path.fromPortableString(remoteBinFile.removeLastSegments(1).toOSString())); IRemoteFileProxy workingDirRFP = exeRC.getRmtFileProxy(); workingDir = workingDirRFP.getResource(workingDirPath.toOSString()); } else { URI workingDirURI = new URI(configUtils.getWorkingDirectory()); RemoteConnection workingDirRC = new RemoteConnection(workingDirURI); IRemoteFileProxy workingDirRFP = workingDirRC.getRmtFileProxy(); workingDir = workingDirRFP.getResource(workingDirURI.getPath()); } //Build the commandline string to run perf recording the given project String arguments[] = getProgramArgumentsArray( config ); //Program args from launch config. ArrayList<String> command = new ArrayList<String>( 4 + arguments.length ); command.addAll(Arrays.asList(PerfCore.getRecordString(config))); //Get the base commandline string (with flags/options based on config) command.add( remoteBinFile.toOSString() ); // Add the path to the executable command.set(0, perfPathString); command.add(2,OUTPUT_STR + configWorkingDir + IPath.SEPARATOR + PerfPlugin.PERF_DEFAULT_DATA); //Compile string command.addAll( Arrays.asList( arguments ) ); //Spawn the process String[] commandArray = command.toArray(new String[command.size()]); Process pProxy = RuntimeProcessFactory.getFactory().exec(commandArray, getEnvironment(config), workingDir, project); MessageConsole console = new MessageConsole("Perf Console", null); //$NON-NLS-1$ console.activate(); ConsolePlugin.getDefault().getConsoleManager().addConsoles(new IConsole[] { console }); MessageConsoleStream stream = console.newMessageStream(); if (pProxy != null) { BufferedReader error = new BufferedReader( new InputStreamReader(pProxy.getErrorStream())); String err; err = error.readLine(); while (err != null) { stream.println(err); err = error.readLine(); } error.close(); } /* This commented part is the basic method to run perf record without integrating into eclipse. String binCall = exePath.toOSString(); for(String arg : arguments) { binCall.concat(" " + arg); } PerfCore.Run(binCall);*/ pProxy.destroy(); PrintStream print = null; if (config.getAttribute(IDebugUIConstants.ATTR_CAPTURE_IN_CONSOLE, true)) { //Get the console to output to. //This may not be the best way to accomplish this but it shall do for now. ConsolePlugin plugin = ConsolePlugin.getDefault(); IConsoleManager conMan = plugin.getConsoleManager(); IConsole[] existing = conMan.getConsoles(); IOConsole binaryOutCons = null; //Find the console for(IConsole x : existing) { if (x.getName().contains(renderProcessLabel(commandArray[0]))) { binaryOutCons = (IOConsole)x; } } if ((binaryOutCons == null) && (existing.length != 0)) { //if can't be found get the most recent opened, this should probably never happen. if (existing[existing.length - 1] instanceof IOConsole) binaryOutCons = (IOConsole)existing[existing.length - 1]; } //Get the printstream via the outputstream. //Get ouput stream OutputStream outputTo; if (binaryOutCons != null) { outputTo = binaryOutCons.newOutputStream(); //Get the printstream for that console print = new PrintStream(outputTo); } for (int i = 0; i < command.size(); i++) { print.print(command.get(i) + " "); } //Print Message print.println(); print.println("Analysing recorded perf.data, please wait..."); //Possibly should pass this (the console reference) on to PerfCore.Report if theres anything we ever want to spit out to user. } PerfCore.Report(config, getEnvironment(config), Path.fromOSString(configWorkingDir + IPath.SEPARATOR), monitor, null, print); PerfCore.RefreshView(renderProcessLabel(exeURI.getPath())); } catch (IOException e) { e.printStackTrace(); abort(e.getLocalizedMessage(), null, ICDTLaunchConfigurationConstants.ERR_INTERNAL_ERROR); } catch (RemoteConnectionException e) { e.printStackTrace(); abort(e.getLocalizedMessage(), null, ICDTLaunchConfigurationConstants.ERR_INTERNAL_ERROR); } catch (URISyntaxException e) { e.printStackTrace(); abort(e.getLocalizedMessage(), null, ICDTLaunchConfigurationConstants.ERR_INTERNAL_ERROR); } // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } }
diff --git a/src/com/ben/software/activity/OrderActivity.java b/src/com/ben/software/activity/OrderActivity.java index db5736a..ce9340e 100644 --- a/src/com/ben/software/activity/OrderActivity.java +++ b/src/com/ben/software/activity/OrderActivity.java @@ -1,236 +1,236 @@ package com.ben.software.activity; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.ben.software.Order; import com.ben.software.R; import com.ben.software.db.DatabaseHelper; import android.app.Activity; import android.content.ContentUris; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.Toast; public class OrderActivity extends Activity { private static final String LOG_TAG = "activity.OrderActivity"; private List<Map<String, String>> mAutoCompleteList; private ListView mOrderListView; private List<Map<String, String>> mDataList; private EditText mCountEditor; private EditText mRemarkEditor; private SimpleAdapter mSimpleAdapter; private long mCurrentCuisineId = -1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(getResources().getText(R.string.order_title) + " - 17桌"); setContentView(R.layout.order); DatabaseHelper dbHelper = new DatabaseHelper(this); dbHelper.clearTestData(); dbHelper.addTestData(); dbHelper.close(); mAutoCompleteList = createAutoCompleteList(); SimpleAdapter adapter = new AutoCompleteAdapter(this, mAutoCompleteList, android.R.layout.simple_dropdown_item_1line, new String[] {"cuisine"}, new int[] {android.R.id.text1}, "id", "cuisine"); AutoCompleteTextView input = (AutoCompleteTextView) findViewById(R.id.orderText); input.setThreshold(1); input.setAdapter(adapter); input.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Log.v(LOG_TAG, "AdapterView.OnItemClickListener - onItemClick position: " + position + " id: " + id); mCurrentCuisineId = id; } }); input.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { Log.v(LOG_TAG, "AdapterView.OnItemSelectedListener - onItemSelected position: " + position + " id: " + id); } public void onNothingSelected(AdapterView<?> parent) { Log.v(LOG_TAG, "AdapterView.OnItemSelectedListener - onNothingSelected"); } }); input.addTextChangedListener(new TextWatcher() { public void onTextChanged(CharSequence aS, int aStart, int aBefore, int aCount) { Log.v(LOG_TAG, "TextWatcher.onTextChanged - aS: " + aS); // mCurrentCuisineId = -1; } public void beforeTextChanged(CharSequence aS, int aStart, int aCount, int aAfter) { // TODO Auto-generated method stub } public void afterTextChanged(Editable aS) { // TODO Auto-generated method stub } }); input.setOnEditorActionListener(new TextView.OnEditorActionListener() { public boolean onEditorAction(TextView aV, int aActionId, KeyEvent aEvent) { Log.v(LOG_TAG, "TextView.OnEditorActionListener - onEditorAction"); return false; } } ); mCountEditor = (EditText) findViewById(R.id.countText); mRemarkEditor = (EditText) findViewById(R.id.remarkText); mDataList = new ArrayList<Map<String, String>>(); mOrderListView = (ListView) findViewById(R.id.orderList); mOrderListView.addHeaderView(createListHeader()); mSimpleAdapter = new SimpleAdapter(this, (List<Map<String, String>>) mDataList, R.layout.orderlist_row, new String[] {"code", "name", "price", "count", "remark"}, new int[] {R.id.cuisineCodeText, R.id.cuisineNameText, R.id.cuisinePriceText, R.id.cuisineCountText, R.id.cuisineRemarkText}); mOrderListView.setAdapter(mSimpleAdapter); Button addButton = (Button) findViewById(R.id.addCuisine); addButton.setOnClickListener( new View.OnClickListener() { public void onClick(View aView) { Log.v(LOG_TAG, "View.OnClickListener - onClick"); if (mCurrentCuisineId != -1) { // TODO: Find in database. String[] projection = new String[] {"_id", "name", "code" ,"price","remark"}; Uri uri = ContentUris.withAppendedId(Order.CuisineColumns.CONTENT_URI,mCurrentCuisineId); Cursor c = managedQuery(uri, projection, null, null, null); if (c != null) { if (c.moveToFirst()) { Map<String, String> map = new HashMap<String, String>(); map.put("id", Long.toString(mCurrentCuisineId)); map.put("name", c.getString(c.getColumnIndex("name"))); map.put("code", c.getString(c.getColumnIndex("code"))); map.put("price", c.getString(c.getColumnIndex("price"))); map.put("count", mCountEditor.getText().toString()); map.put("remark", mRemarkEditor.getText().toString()); mDataList.add(map); mSimpleAdapter.notifyDataSetChanged(); } } else { return; } } else { // TODO: 根据名字查找,判断是否存在,添加 } } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate menu from XML resource MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.order, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { Log.v(LOG_TAG, "onOptionsItemSelected"); switch (item.getItemId()) { case R.id.order_commit: Toast.makeText(this, "提交成功", Toast.LENGTH_LONG).show(); Intent intent = new Intent(this, FunctionListActivity.class); startActivity(intent); finish(); return true; default: return super.onOptionsItemSelected(item); } } private View createListHeader() { LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE); View headerView = inflater.inflate(R.layout.orderlist_row, null); TextView codeHeader = (TextView) headerView.findViewById(R.id.cuisineCodeText); codeHeader.setText(R.string.cuisine_code); TextView nameHeader = (TextView) headerView.findViewById(R.id.cuisineNameText); nameHeader.setText(R.string.cuisine_name); TextView priceHeader = (TextView) headerView.findViewById(R.id.cuisinePriceText); priceHeader.setText(R.string.cuisine_price); TextView countHeader = (TextView) headerView.findViewById(R.id.cuisineCountText); countHeader.setText(R.string.cuisine_count); TextView remarkHeader = (TextView) headerView.findViewById(R.id.cuisineRemarkText); remarkHeader.setText(R.string.cuisine_remark); remarkHeader.setGravity(Gravity.CENTER); return headerView; } private List<Map<String, String>> createAutoCompleteList() { Log.v(LOG_TAG, "createAutoCompleteList"); ArrayList<Map<String,String>> list = new ArrayList<Map<String,String>>(); String[] projection = new String[] {"_id", "name", "code", "price", "discount", "remark"}; Cursor c = managedQuery(Order.CuisineColumns.CONTENT_URI, projection, null, null, null); if (c != null) { boolean succeeded = c.moveToFirst(); while (succeeded) { Map<String,String> map = new HashMap<String, String>(); String name = c.getString(c.getColumnIndex("name")); String id = Integer.toString(c.getInt(c.getColumnIndex("_id"))); String code = Integer.toString(c.getInt(c.getColumnIndex("code"))); - if (code != null || !code.isEmpty()) { + if (code != null && !code.isEmpty()) { name = code + " " + name; } map.put("cuisine",name); map.put("id", id); list.add(map); succeeded = c.moveToNext(); } } return list; } }
true
true
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(getResources().getText(R.string.order_title) + " - 17桌"); setContentView(R.layout.order); DatabaseHelper dbHelper = new DatabaseHelper(this); dbHelper.clearTestData(); dbHelper.addTestData(); dbHelper.close(); mAutoCompleteList = createAutoCompleteList(); SimpleAdapter adapter = new AutoCompleteAdapter(this, mAutoCompleteList, android.R.layout.simple_dropdown_item_1line, new String[] {"cuisine"}, new int[] {android.R.id.text1}, "id", "cuisine"); AutoCompleteTextView input = (AutoCompleteTextView) findViewById(R.id.orderText); input.setThreshold(1); input.setAdapter(adapter); input.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Log.v(LOG_TAG, "AdapterView.OnItemClickListener - onItemClick position: " + position + " id: " + id); mCurrentCuisineId = id; } }); input.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { Log.v(LOG_TAG, "AdapterView.OnItemSelectedListener - onItemSelected position: " + position + " id: " + id); } public void onNothingSelected(AdapterView<?> parent) { Log.v(LOG_TAG, "AdapterView.OnItemSelectedListener - onNothingSelected"); } }); input.addTextChangedListener(new TextWatcher() { public void onTextChanged(CharSequence aS, int aStart, int aBefore, int aCount) { Log.v(LOG_TAG, "TextWatcher.onTextChanged - aS: " + aS); // mCurrentCuisineId = -1; } public void beforeTextChanged(CharSequence aS, int aStart, int aCount, int aAfter) { // TODO Auto-generated method stub } public void afterTextChanged(Editable aS) { // TODO Auto-generated method stub } }); input.setOnEditorActionListener(new TextView.OnEditorActionListener() { public boolean onEditorAction(TextView aV, int aActionId, KeyEvent aEvent) { Log.v(LOG_TAG, "TextView.OnEditorActionListener - onEditorAction"); return false; } } ); mCountEditor = (EditText) findViewById(R.id.countText); mRemarkEditor = (EditText) findViewById(R.id.remarkText); mDataList = new ArrayList<Map<String, String>>(); mOrderListView = (ListView) findViewById(R.id.orderList); mOrderListView.addHeaderView(createListHeader()); mSimpleAdapter = new SimpleAdapter(this, (List<Map<String, String>>) mDataList, R.layout.orderlist_row, new String[] {"code", "name", "price", "count", "remark"}, new int[] {R.id.cuisineCodeText, R.id.cuisineNameText, R.id.cuisinePriceText, R.id.cuisineCountText, R.id.cuisineRemarkText}); mOrderListView.setAdapter(mSimpleAdapter); Button addButton = (Button) findViewById(R.id.addCuisine); addButton.setOnClickListener( new View.OnClickListener() { public void onClick(View aView) { Log.v(LOG_TAG, "View.OnClickListener - onClick"); if (mCurrentCuisineId != -1) { // TODO: Find in database. String[] projection = new String[] {"_id", "name", "code" ,"price","remark"}; Uri uri = ContentUris.withAppendedId(Order.CuisineColumns.CONTENT_URI,mCurrentCuisineId); Cursor c = managedQuery(uri, projection, null, null, null); if (c != null) { if (c.moveToFirst()) { Map<String, String> map = new HashMap<String, String>(); map.put("id", Long.toString(mCurrentCuisineId)); map.put("name", c.getString(c.getColumnIndex("name"))); map.put("code", c.getString(c.getColumnIndex("code"))); map.put("price", c.getString(c.getColumnIndex("price"))); map.put("count", mCountEditor.getText().toString()); map.put("remark", mRemarkEditor.getText().toString()); mDataList.add(map); mSimpleAdapter.notifyDataSetChanged(); } } else { return; } } else { // TODO: 根据名字查找,判断是否存在,添加 } } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate menu from XML resource MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.order, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { Log.v(LOG_TAG, "onOptionsItemSelected"); switch (item.getItemId()) { case R.id.order_commit: Toast.makeText(this, "提交成功", Toast.LENGTH_LONG).show(); Intent intent = new Intent(this, FunctionListActivity.class); startActivity(intent); finish(); return true; default: return super.onOptionsItemSelected(item); } } private View createListHeader() { LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE); View headerView = inflater.inflate(R.layout.orderlist_row, null); TextView codeHeader = (TextView) headerView.findViewById(R.id.cuisineCodeText); codeHeader.setText(R.string.cuisine_code); TextView nameHeader = (TextView) headerView.findViewById(R.id.cuisineNameText); nameHeader.setText(R.string.cuisine_name); TextView priceHeader = (TextView) headerView.findViewById(R.id.cuisinePriceText); priceHeader.setText(R.string.cuisine_price); TextView countHeader = (TextView) headerView.findViewById(R.id.cuisineCountText); countHeader.setText(R.string.cuisine_count); TextView remarkHeader = (TextView) headerView.findViewById(R.id.cuisineRemarkText); remarkHeader.setText(R.string.cuisine_remark); remarkHeader.setGravity(Gravity.CENTER); return headerView; } private List<Map<String, String>> createAutoCompleteList() { Log.v(LOG_TAG, "createAutoCompleteList"); ArrayList<Map<String,String>> list = new ArrayList<Map<String,String>>(); String[] projection = new String[] {"_id", "name", "code", "price", "discount", "remark"}; Cursor c = managedQuery(Order.CuisineColumns.CONTENT_URI, projection, null, null, null); if (c != null) { boolean succeeded = c.moveToFirst(); while (succeeded) { Map<String,String> map = new HashMap<String, String>(); String name = c.getString(c.getColumnIndex("name")); String id = Integer.toString(c.getInt(c.getColumnIndex("_id"))); String code = Integer.toString(c.getInt(c.getColumnIndex("code"))); if (code != null || !code.isEmpty()) { name = code + " " + name; } map.put("cuisine",name); map.put("id", id); list.add(map); succeeded = c.moveToNext(); } } return list; } }
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(getResources().getText(R.string.order_title) + " - 17桌"); setContentView(R.layout.order); DatabaseHelper dbHelper = new DatabaseHelper(this); dbHelper.clearTestData(); dbHelper.addTestData(); dbHelper.close(); mAutoCompleteList = createAutoCompleteList(); SimpleAdapter adapter = new AutoCompleteAdapter(this, mAutoCompleteList, android.R.layout.simple_dropdown_item_1line, new String[] {"cuisine"}, new int[] {android.R.id.text1}, "id", "cuisine"); AutoCompleteTextView input = (AutoCompleteTextView) findViewById(R.id.orderText); input.setThreshold(1); input.setAdapter(adapter); input.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Log.v(LOG_TAG, "AdapterView.OnItemClickListener - onItemClick position: " + position + " id: " + id); mCurrentCuisineId = id; } }); input.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { Log.v(LOG_TAG, "AdapterView.OnItemSelectedListener - onItemSelected position: " + position + " id: " + id); } public void onNothingSelected(AdapterView<?> parent) { Log.v(LOG_TAG, "AdapterView.OnItemSelectedListener - onNothingSelected"); } }); input.addTextChangedListener(new TextWatcher() { public void onTextChanged(CharSequence aS, int aStart, int aBefore, int aCount) { Log.v(LOG_TAG, "TextWatcher.onTextChanged - aS: " + aS); // mCurrentCuisineId = -1; } public void beforeTextChanged(CharSequence aS, int aStart, int aCount, int aAfter) { // TODO Auto-generated method stub } public void afterTextChanged(Editable aS) { // TODO Auto-generated method stub } }); input.setOnEditorActionListener(new TextView.OnEditorActionListener() { public boolean onEditorAction(TextView aV, int aActionId, KeyEvent aEvent) { Log.v(LOG_TAG, "TextView.OnEditorActionListener - onEditorAction"); return false; } } ); mCountEditor = (EditText) findViewById(R.id.countText); mRemarkEditor = (EditText) findViewById(R.id.remarkText); mDataList = new ArrayList<Map<String, String>>(); mOrderListView = (ListView) findViewById(R.id.orderList); mOrderListView.addHeaderView(createListHeader()); mSimpleAdapter = new SimpleAdapter(this, (List<Map<String, String>>) mDataList, R.layout.orderlist_row, new String[] {"code", "name", "price", "count", "remark"}, new int[] {R.id.cuisineCodeText, R.id.cuisineNameText, R.id.cuisinePriceText, R.id.cuisineCountText, R.id.cuisineRemarkText}); mOrderListView.setAdapter(mSimpleAdapter); Button addButton = (Button) findViewById(R.id.addCuisine); addButton.setOnClickListener( new View.OnClickListener() { public void onClick(View aView) { Log.v(LOG_TAG, "View.OnClickListener - onClick"); if (mCurrentCuisineId != -1) { // TODO: Find in database. String[] projection = new String[] {"_id", "name", "code" ,"price","remark"}; Uri uri = ContentUris.withAppendedId(Order.CuisineColumns.CONTENT_URI,mCurrentCuisineId); Cursor c = managedQuery(uri, projection, null, null, null); if (c != null) { if (c.moveToFirst()) { Map<String, String> map = new HashMap<String, String>(); map.put("id", Long.toString(mCurrentCuisineId)); map.put("name", c.getString(c.getColumnIndex("name"))); map.put("code", c.getString(c.getColumnIndex("code"))); map.put("price", c.getString(c.getColumnIndex("price"))); map.put("count", mCountEditor.getText().toString()); map.put("remark", mRemarkEditor.getText().toString()); mDataList.add(map); mSimpleAdapter.notifyDataSetChanged(); } } else { return; } } else { // TODO: 根据名字查找,判断是否存在,添加 } } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate menu from XML resource MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.order, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { Log.v(LOG_TAG, "onOptionsItemSelected"); switch (item.getItemId()) { case R.id.order_commit: Toast.makeText(this, "提交成功", Toast.LENGTH_LONG).show(); Intent intent = new Intent(this, FunctionListActivity.class); startActivity(intent); finish(); return true; default: return super.onOptionsItemSelected(item); } } private View createListHeader() { LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE); View headerView = inflater.inflate(R.layout.orderlist_row, null); TextView codeHeader = (TextView) headerView.findViewById(R.id.cuisineCodeText); codeHeader.setText(R.string.cuisine_code); TextView nameHeader = (TextView) headerView.findViewById(R.id.cuisineNameText); nameHeader.setText(R.string.cuisine_name); TextView priceHeader = (TextView) headerView.findViewById(R.id.cuisinePriceText); priceHeader.setText(R.string.cuisine_price); TextView countHeader = (TextView) headerView.findViewById(R.id.cuisineCountText); countHeader.setText(R.string.cuisine_count); TextView remarkHeader = (TextView) headerView.findViewById(R.id.cuisineRemarkText); remarkHeader.setText(R.string.cuisine_remark); remarkHeader.setGravity(Gravity.CENTER); return headerView; } private List<Map<String, String>> createAutoCompleteList() { Log.v(LOG_TAG, "createAutoCompleteList"); ArrayList<Map<String,String>> list = new ArrayList<Map<String,String>>(); String[] projection = new String[] {"_id", "name", "code", "price", "discount", "remark"}; Cursor c = managedQuery(Order.CuisineColumns.CONTENT_URI, projection, null, null, null); if (c != null) { boolean succeeded = c.moveToFirst(); while (succeeded) { Map<String,String> map = new HashMap<String, String>(); String name = c.getString(c.getColumnIndex("name")); String id = Integer.toString(c.getInt(c.getColumnIndex("_id"))); String code = Integer.toString(c.getInt(c.getColumnIndex("code"))); if (code != null && !code.isEmpty()) { name = code + " " + name; } map.put("cuisine",name); map.put("id", id); list.add(map); succeeded = c.moveToNext(); } } return list; } }
diff --git a/web/src/main/java/org/openmrs/web/servlet/ComplexObsServlet.java b/web/src/main/java/org/openmrs/web/servlet/ComplexObsServlet.java index 28fcd4a2..19fde1ab 100644 --- a/web/src/main/java/org/openmrs/web/servlet/ComplexObsServlet.java +++ b/web/src/main/java/org/openmrs/web/servlet/ComplexObsServlet.java @@ -1,98 +1,98 @@ /** * The contents of this file are subject to the OpenMRS Public License * Version 1.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://license.openmrs.org * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * Copyright (C) OpenMRS, LLC. All Rights Reserved. */ package org.openmrs.web.servlet; import java.awt.image.RenderedImage; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openmrs.Obs; import org.openmrs.api.context.Context; import org.openmrs.obs.ComplexData; import org.openmrs.util.OpenmrsUtil; import org.openmrs.util.PrivilegeConstants; import org.openmrs.web.WebConstants; public class ComplexObsServlet extends HttpServlet { public static final long serialVersionUID = 1234432L; private static final Log log = LogFactory.getLog(ComplexObsServlet.class); /** * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String obsId = request.getParameter("obsId"); String view = request.getParameter("view"); String viewType = request.getParameter("viewType"); HttpSession session = request.getSession(); if (obsId == null || obsId.length() == 0) { session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "error.null"); return; } if (!Context.hasPrivilege(PrivilegeConstants.VIEW_OBS)) { session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Privilege required: " + PrivilegeConstants.VIEW_OBS); session.setAttribute(WebConstants.OPENMRS_LOGIN_REDIRECT_HTTPSESSION_ATTR, request.getRequestURI() + "?" + request.getQueryString()); response.sendRedirect(request.getContextPath() + "/login.htm"); return; } Obs complexObs = Context.getObsService().getComplexObs(Integer.valueOf(obsId), view); ComplexData cd = complexObs.getComplexData(); Object data = cd.getData(); if ("download".equals(viewType)) { response.setHeader("Content-Disposition", "attachment; filename=" + cd.getTitle()); response.setHeader("Pragma", "no-cache"); } if (data instanceof byte[]) { ByteArrayInputStream stream = new ByteArrayInputStream((byte[]) data); OpenmrsUtil.copyFile(stream, response.getOutputStream()); } else if (RenderedImage.class.isAssignableFrom(data.getClass())) { RenderedImage img = (RenderedImage) data; - String[] parts = cd.getTitle().split("."); + String[] parts = cd.getTitle().split("\\."); String extension = "jpg"; // default extension if (parts.length > 0) { extension = parts[parts.length - 1]; } ImageIO.write(img, extension, response.getOutputStream()); } else if (InputStream.class.isAssignableFrom(data.getClass())) { InputStream stream = (InputStream) data; OpenmrsUtil.copyFile(stream, response.getOutputStream()); stream.close(); } else { throw new ServletException("Couldn't serialize complex obs data for obsId=" + obsId + " of type " + data.getClass()); } } }
true
true
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String obsId = request.getParameter("obsId"); String view = request.getParameter("view"); String viewType = request.getParameter("viewType"); HttpSession session = request.getSession(); if (obsId == null || obsId.length() == 0) { session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "error.null"); return; } if (!Context.hasPrivilege(PrivilegeConstants.VIEW_OBS)) { session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Privilege required: " + PrivilegeConstants.VIEW_OBS); session.setAttribute(WebConstants.OPENMRS_LOGIN_REDIRECT_HTTPSESSION_ATTR, request.getRequestURI() + "?" + request.getQueryString()); response.sendRedirect(request.getContextPath() + "/login.htm"); return; } Obs complexObs = Context.getObsService().getComplexObs(Integer.valueOf(obsId), view); ComplexData cd = complexObs.getComplexData(); Object data = cd.getData(); if ("download".equals(viewType)) { response.setHeader("Content-Disposition", "attachment; filename=" + cd.getTitle()); response.setHeader("Pragma", "no-cache"); } if (data instanceof byte[]) { ByteArrayInputStream stream = new ByteArrayInputStream((byte[]) data); OpenmrsUtil.copyFile(stream, response.getOutputStream()); } else if (RenderedImage.class.isAssignableFrom(data.getClass())) { RenderedImage img = (RenderedImage) data; String[] parts = cd.getTitle().split("."); String extension = "jpg"; // default extension if (parts.length > 0) { extension = parts[parts.length - 1]; } ImageIO.write(img, extension, response.getOutputStream()); } else if (InputStream.class.isAssignableFrom(data.getClass())) { InputStream stream = (InputStream) data; OpenmrsUtil.copyFile(stream, response.getOutputStream()); stream.close(); } else { throw new ServletException("Couldn't serialize complex obs data for obsId=" + obsId + " of type " + data.getClass()); } }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String obsId = request.getParameter("obsId"); String view = request.getParameter("view"); String viewType = request.getParameter("viewType"); HttpSession session = request.getSession(); if (obsId == null || obsId.length() == 0) { session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "error.null"); return; } if (!Context.hasPrivilege(PrivilegeConstants.VIEW_OBS)) { session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Privilege required: " + PrivilegeConstants.VIEW_OBS); session.setAttribute(WebConstants.OPENMRS_LOGIN_REDIRECT_HTTPSESSION_ATTR, request.getRequestURI() + "?" + request.getQueryString()); response.sendRedirect(request.getContextPath() + "/login.htm"); return; } Obs complexObs = Context.getObsService().getComplexObs(Integer.valueOf(obsId), view); ComplexData cd = complexObs.getComplexData(); Object data = cd.getData(); if ("download".equals(viewType)) { response.setHeader("Content-Disposition", "attachment; filename=" + cd.getTitle()); response.setHeader("Pragma", "no-cache"); } if (data instanceof byte[]) { ByteArrayInputStream stream = new ByteArrayInputStream((byte[]) data); OpenmrsUtil.copyFile(stream, response.getOutputStream()); } else if (RenderedImage.class.isAssignableFrom(data.getClass())) { RenderedImage img = (RenderedImage) data; String[] parts = cd.getTitle().split("\\."); String extension = "jpg"; // default extension if (parts.length > 0) { extension = parts[parts.length - 1]; } ImageIO.write(img, extension, response.getOutputStream()); } else if (InputStream.class.isAssignableFrom(data.getClass())) { InputStream stream = (InputStream) data; OpenmrsUtil.copyFile(stream, response.getOutputStream()); stream.close(); } else { throw new ServletException("Couldn't serialize complex obs data for obsId=" + obsId + " of type " + data.getClass()); } }
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/io/CombineHiveInputFormat.java b/ql/src/java/org/apache/hadoop/hive/ql/io/CombineHiveInputFormat.java index 7a1d1e1d..e9483eb7 100644 --- a/ql/src/java/org/apache/hadoop/hive/ql/io/CombineHiveInputFormat.java +++ b/ql/src/java/org/apache/hadoop/hive/ql/io/CombineHiveInputFormat.java @@ -1,385 +1,385 @@ /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hive.ql.io; import java.io.DataInput; import java.io.DataOutput; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Map; import java.util.Queue; import java.util.LinkedList; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.PathFilter; import org.apache.hadoop.hive.ql.exec.Utilities; import org.apache.hadoop.hive.ql.plan.PartitionDesc; import org.apache.hadoop.hive.ql.plan.TableDesc; import org.apache.hadoop.hive.shims.ShimLoader; import org.apache.hadoop.hive.shims.HadoopShims.CombineFileInputFormatShim; import org.apache.hadoop.hive.shims.HadoopShims.InputSplitShim; import org.apache.hadoop.io.Writable; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.io.compress.CompressionCodecFactory; import org.apache.hadoop.mapred.InputFormat; import org.apache.hadoop.mapred.InputSplit; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.RecordReader; import org.apache.hadoop.mapred.Reporter; import org.apache.hadoop.mapred.TextInputFormat; /** * CombineHiveInputFormat is a parameterized InputFormat which looks at the path * name and determine the correct InputFormat for that path name from * mapredPlan.pathToPartitionInfo(). It can be used to read files with different * input format in the same map-reduce job. */ public class CombineHiveInputFormat<K extends WritableComparable, V extends Writable> extends HiveInputFormat<K, V> { public static final Log LOG = LogFactory .getLog("org.apache.hadoop.hive.ql.io.CombineHiveInputFormat"); /** * CombineHiveInputSplit encapsulates an InputSplit with its corresponding * inputFormatClassName. A CombineHiveInputSplit comprises of multiple chunks * from different files. Since, they belong to a single directory, there is a * single inputformat for all the chunks. */ public static class CombineHiveInputSplit implements InputSplitShim { String inputFormatClassName; InputSplitShim inputSplitShim; public CombineHiveInputSplit() throws IOException { this(ShimLoader.getHadoopShims().getCombineFileInputFormat() .getInputSplitShim()); } public CombineHiveInputSplit(InputSplitShim inputSplitShim) throws IOException { this(inputSplitShim.getJob(), inputSplitShim); } public CombineHiveInputSplit(JobConf job, InputSplitShim inputSplitShim) throws IOException { this.inputSplitShim = inputSplitShim; if (job != null) { Map<String, PartitionDesc> pathToPartitionInfo = Utilities .getMapRedWork(job).getPathToPartitionInfo(); // extract all the inputFormatClass names for each chunk in the // CombinedSplit. Path[] ipaths = inputSplitShim.getPaths(); for (int i = 0; i < ipaths.length; i++) { PartitionDesc part = getPartitionDescFromPath(pathToPartitionInfo, ipaths[i]); // create a new InputFormat instance if this is the first time to see // this class if (i == 0) { inputFormatClassName = part.getInputFileFormatClass().getName(); } else { assert inputFormatClassName.equals(part.getInputFileFormatClass() .getName()); } } } } public InputSplitShim getInputSplitShim() { return inputSplitShim; } /** * Returns the inputFormat class name for the i-th chunk. */ public String inputFormatClassName() { return inputFormatClassName; } public void setInputFormatClassName(String inputFormatClassName) { this.inputFormatClassName = inputFormatClassName; } public JobConf getJob() { return inputSplitShim.getJob(); } public long getLength() { return inputSplitShim.getLength(); } /** Returns an array containing the startoffsets of the files in the split. */ public long[] getStartOffsets() { return inputSplitShim.getStartOffsets(); } /** Returns an array containing the lengths of the files in the split. */ public long[] getLengths() { return inputSplitShim.getLengths(); } /** Returns the start offset of the i<sup>th</sup> Path. */ public long getOffset(int i) { return inputSplitShim.getOffset(i); } /** Returns the length of the i<sup>th</sup> Path. */ public long getLength(int i) { return inputSplitShim.getLength(i); } /** Returns the number of Paths in the split. */ public int getNumPaths() { return inputSplitShim.getNumPaths(); } /** Returns the i<sup>th</sup> Path. */ public Path getPath(int i) { return inputSplitShim.getPath(i); } /** Returns all the Paths in the split. */ public Path[] getPaths() { return inputSplitShim.getPaths(); } /** Returns all the Paths where this input-split resides. */ public String[] getLocations() throws IOException { return inputSplitShim.getLocations(); } /** * Prints this obejct as a string. */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(inputSplitShim.toString()); sb.append("InputFormatClass: " + inputFormatClassName); sb.append("\n"); return sb.toString(); } /** * Writable interface. */ public void readFields(DataInput in) throws IOException { inputSplitShim.readFields(in); inputFormatClassName = in.readUTF(); } /** * Writable interface. */ public void write(DataOutput out) throws IOException { inputSplitShim.write(out); if (inputFormatClassName == null) { Map<String, PartitionDesc> pathToPartitionInfo = Utilities .getMapRedWork(getJob()).getPathToPartitionInfo(); // extract all the inputFormatClass names for each chunk in the // CombinedSplit. PartitionDesc part = getPartitionDescFromPath(pathToPartitionInfo, inputSplitShim.getPath(0)); // create a new InputFormat instance if this is the first time to see // this class inputFormatClassName = part.getInputFileFormatClass().getName(); } out.writeUTF(inputFormatClassName); } } /** * Create Hive splits based on CombineFileSplit. */ @Override public InputSplit[] getSplits(JobConf job, int numSplits) throws IOException { init(job); CombineFileInputFormatShim combine = ShimLoader.getHadoopShims() .getCombineFileInputFormat(); if (combine == null) { return super.getSplits(job, numSplits); } if (combine.getInputPathsShim(job).length == 0) { throw new IOException("No input paths specified in job"); } ArrayList<InputSplit> result = new ArrayList<InputSplit>(); // combine splits only from same tables. Do not combine splits from multiple // tables. Path[] paths = combine.getInputPathsShim(job); for (Path path : paths) { LOG.info("CombineHiveInputSplit creating pool for " + path); PartitionDesc part = getPartitionDescFromPath(pathToPartitionInfo, path); TableDesc tableDesc = part.getTableDesc(); if ((tableDesc != null) && tableDesc.isNonNative()) { return super.getSplits(job, numSplits); } // Use HiveInputFormat if any of the paths is not splittable Class inputFormatClass = part.getInputFileFormatClass(); InputFormat inputFormat = getInputFormatFromCache(inputFormatClass, job); // Since there is no easy way of knowing whether MAPREDUCE-1597 is present in the tree or not, // we use a configuration variable for the same - if (this.mrwork != null && this.mrwork.getHadoopSupportsSplittable()) { + if (this.mrwork != null && !this.mrwork.getHadoopSupportsSplittable()) { // The following code should be removed, once // https://issues.apache.org/jira/browse/MAPREDUCE-1597 is fixed. // Hadoop does not handle non-splittable files correctly for CombineFileInputFormat, // so don't use CombineFileInputFormat for non-splittable files FileSystem inpFs = path.getFileSystem(job); if (inputFormat instanceof TextInputFormat) { Queue<Path> dirs = new LinkedList<Path>(); FileStatus fStats = inpFs.getFileStatus(path); // If path is a directory if (fStats.isDir()) { dirs.offer(path); } else if ((new CompressionCodecFactory(job)).getCodec(path) != null) { return super.getSplits(job, numSplits); } while (dirs.peek() != null) { Path tstPath = dirs.remove(); FileStatus[] fStatus = inpFs.listStatus(tstPath); for (int idx = 0; idx < fStatus.length; idx++) { if (fStatus[idx].isDir()) { dirs.offer(fStatus[idx].getPath()); } else if ((new CompressionCodecFactory(job)).getCodec(fStatus[idx].getPath()) != null) { return super.getSplits(job, numSplits); } } } } } if (inputFormat instanceof SymlinkTextInputFormat) { return super.getSplits(job, numSplits); } combine.createPool(job, new CombineFilter(path)); } InputSplitShim[] iss = combine.getSplits(job, 1); for (InputSplitShim is : iss) { CombineHiveInputSplit csplit = new CombineHiveInputSplit(job, is); result.add(csplit); } LOG.info("number of splits " + result.size()); return result.toArray(new CombineHiveInputSplit[result.size()]); } /** * Create a generic Hive RecordReader than can iterate over all chunks in a * CombinedFileSplit. */ @Override public RecordReader getRecordReader(InputSplit split, JobConf job, Reporter reporter) throws IOException { if (!(split instanceof CombineHiveInputSplit)) { return super.getRecordReader(split, job, reporter); } CombineHiveInputSplit hsplit = (CombineHiveInputSplit) split; String inputFormatClassName = null; Class inputFormatClass = null; try { inputFormatClassName = hsplit.inputFormatClassName(); inputFormatClass = job.getClassByName(inputFormatClassName); } catch (Exception e) { throw new IOException("cannot find class " + inputFormatClassName); } initColumnsNeeded(job, inputFormatClass, hsplit.getPath(0).toString(), hsplit.getPath(0).toUri().getPath()); return ShimLoader.getHadoopShims().getCombineFileInputFormat() .getRecordReader(job, ((CombineHiveInputSplit) split).getInputSplitShim(), reporter, CombineHiveRecordReader.class); } protected static PartitionDesc getPartitionDescFromPath( Map<String, PartitionDesc> pathToPartitionInfo, Path dir) throws IOException { try { // Take only the path part of the URI. // The format of the keys in pathToPartitionInfo sometimes contains a port // and sometimes doesn't, so we just compare paths. URI dirUri = new URI(dir.toUri().getPath()); for (Map.Entry<String, PartitionDesc> entry : pathToPartitionInfo .entrySet()) { URI pathOfPartition = new URI(entry.getKey()); pathOfPartition = new URI(pathOfPartition.getPath()); if (!pathOfPartition.relativize(dirUri).equals(dirUri)) { return entry.getValue(); } } } catch (URISyntaxException e2) { LOG.info("getPartitionDescFromPath ", e2); } throw new IOException("cannot find dir = " + dir.toString() + " in partToPartitionInfo: " + pathToPartitionInfo.keySet()); } static class CombineFilter implements PathFilter { private final String pString; // store a path prefix in this TestFilter public CombineFilter(Path p) { pString = p.toString() + File.separator; } // returns true if the specified path matches the prefix stored // in this TestFilter. public boolean accept(Path path) { if (path.toString().indexOf(pString) == 0) { return true; } return false; } @Override public String toString() { return "PathFilter:" + pString; } } }
true
true
public InputSplit[] getSplits(JobConf job, int numSplits) throws IOException { init(job); CombineFileInputFormatShim combine = ShimLoader.getHadoopShims() .getCombineFileInputFormat(); if (combine == null) { return super.getSplits(job, numSplits); } if (combine.getInputPathsShim(job).length == 0) { throw new IOException("No input paths specified in job"); } ArrayList<InputSplit> result = new ArrayList<InputSplit>(); // combine splits only from same tables. Do not combine splits from multiple // tables. Path[] paths = combine.getInputPathsShim(job); for (Path path : paths) { LOG.info("CombineHiveInputSplit creating pool for " + path); PartitionDesc part = getPartitionDescFromPath(pathToPartitionInfo, path); TableDesc tableDesc = part.getTableDesc(); if ((tableDesc != null) && tableDesc.isNonNative()) { return super.getSplits(job, numSplits); } // Use HiveInputFormat if any of the paths is not splittable Class inputFormatClass = part.getInputFileFormatClass(); InputFormat inputFormat = getInputFormatFromCache(inputFormatClass, job); // Since there is no easy way of knowing whether MAPREDUCE-1597 is present in the tree or not, // we use a configuration variable for the same if (this.mrwork != null && this.mrwork.getHadoopSupportsSplittable()) { // The following code should be removed, once // https://issues.apache.org/jira/browse/MAPREDUCE-1597 is fixed. // Hadoop does not handle non-splittable files correctly for CombineFileInputFormat, // so don't use CombineFileInputFormat for non-splittable files FileSystem inpFs = path.getFileSystem(job); if (inputFormat instanceof TextInputFormat) { Queue<Path> dirs = new LinkedList<Path>(); FileStatus fStats = inpFs.getFileStatus(path); // If path is a directory if (fStats.isDir()) { dirs.offer(path); } else if ((new CompressionCodecFactory(job)).getCodec(path) != null) { return super.getSplits(job, numSplits); } while (dirs.peek() != null) { Path tstPath = dirs.remove(); FileStatus[] fStatus = inpFs.listStatus(tstPath); for (int idx = 0; idx < fStatus.length; idx++) { if (fStatus[idx].isDir()) { dirs.offer(fStatus[idx].getPath()); } else if ((new CompressionCodecFactory(job)).getCodec(fStatus[idx].getPath()) != null) { return super.getSplits(job, numSplits); } } } } } if (inputFormat instanceof SymlinkTextInputFormat) { return super.getSplits(job, numSplits); } combine.createPool(job, new CombineFilter(path)); } InputSplitShim[] iss = combine.getSplits(job, 1); for (InputSplitShim is : iss) { CombineHiveInputSplit csplit = new CombineHiveInputSplit(job, is); result.add(csplit); } LOG.info("number of splits " + result.size()); return result.toArray(new CombineHiveInputSplit[result.size()]); }
public InputSplit[] getSplits(JobConf job, int numSplits) throws IOException { init(job); CombineFileInputFormatShim combine = ShimLoader.getHadoopShims() .getCombineFileInputFormat(); if (combine == null) { return super.getSplits(job, numSplits); } if (combine.getInputPathsShim(job).length == 0) { throw new IOException("No input paths specified in job"); } ArrayList<InputSplit> result = new ArrayList<InputSplit>(); // combine splits only from same tables. Do not combine splits from multiple // tables. Path[] paths = combine.getInputPathsShim(job); for (Path path : paths) { LOG.info("CombineHiveInputSplit creating pool for " + path); PartitionDesc part = getPartitionDescFromPath(pathToPartitionInfo, path); TableDesc tableDesc = part.getTableDesc(); if ((tableDesc != null) && tableDesc.isNonNative()) { return super.getSplits(job, numSplits); } // Use HiveInputFormat if any of the paths is not splittable Class inputFormatClass = part.getInputFileFormatClass(); InputFormat inputFormat = getInputFormatFromCache(inputFormatClass, job); // Since there is no easy way of knowing whether MAPREDUCE-1597 is present in the tree or not, // we use a configuration variable for the same if (this.mrwork != null && !this.mrwork.getHadoopSupportsSplittable()) { // The following code should be removed, once // https://issues.apache.org/jira/browse/MAPREDUCE-1597 is fixed. // Hadoop does not handle non-splittable files correctly for CombineFileInputFormat, // so don't use CombineFileInputFormat for non-splittable files FileSystem inpFs = path.getFileSystem(job); if (inputFormat instanceof TextInputFormat) { Queue<Path> dirs = new LinkedList<Path>(); FileStatus fStats = inpFs.getFileStatus(path); // If path is a directory if (fStats.isDir()) { dirs.offer(path); } else if ((new CompressionCodecFactory(job)).getCodec(path) != null) { return super.getSplits(job, numSplits); } while (dirs.peek() != null) { Path tstPath = dirs.remove(); FileStatus[] fStatus = inpFs.listStatus(tstPath); for (int idx = 0; idx < fStatus.length; idx++) { if (fStatus[idx].isDir()) { dirs.offer(fStatus[idx].getPath()); } else if ((new CompressionCodecFactory(job)).getCodec(fStatus[idx].getPath()) != null) { return super.getSplits(job, numSplits); } } } } } if (inputFormat instanceof SymlinkTextInputFormat) { return super.getSplits(job, numSplits); } combine.createPool(job, new CombineFilter(path)); } InputSplitShim[] iss = combine.getSplits(job, 1); for (InputSplitShim is : iss) { CombineHiveInputSplit csplit = new CombineHiveInputSplit(job, is); result.add(csplit); } LOG.info("number of splits " + result.size()); return result.toArray(new CombineHiveInputSplit[result.size()]); }
diff --git a/src/com/android/settings/TetherSettings.java b/src/com/android/settings/TetherSettings.java index e27c96ee5..867f73352 100644 --- a/src/com/android/settings/TetherSettings.java +++ b/src/com/android/settings/TetherSettings.java @@ -1,630 +1,630 @@ /* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.settings; import com.android.settings.wifi.WifiApEnabler; import com.android.settings.wifi.WifiApDialog; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothPan; import android.bluetooth.BluetoothProfile; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.res.AssetManager; import android.hardware.usb.UsbManager; import android.net.ConnectivityManager; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiManager; import android.os.Bundle; import android.os.Environment; import android.preference.CheckBoxPreference; import android.preference.Preference; import android.preference.PreferenceScreen; import android.text.TextUtils; import android.view.ViewGroup; import android.view.ViewParent; import android.webkit.WebView; import java.io.InputStream; import java.util.ArrayList; import java.util.Locale; /* * Displays preferences for Tethering. */ public class TetherSettings extends SettingsPreferenceFragment implements DialogInterface.OnClickListener, Preference.OnPreferenceChangeListener { private static final String USB_TETHER_SETTINGS = "usb_tether_settings"; private static final String ENABLE_WIFI_AP = "enable_wifi_ap"; private static final String ENABLE_BLUETOOTH_TETHERING = "enable_bluetooth_tethering"; private static final String TETHERING_HELP = "tethering_help"; private static final String USB_HELP_MODIFIER = "usb_"; private static final String WIFI_HELP_MODIFIER = "wifi_"; private static final String HELP_URL = "file:///android_asset/html/%y%z/tethering_%xhelp.html"; private static final String HELP_PATH = "html/%y%z/tethering_help.html"; private static final int DIALOG_TETHER_HELP = 1; private static final int DIALOG_AP_SETTINGS = 2; private WebView mView; private CheckBoxPreference mUsbTether; private WifiApEnabler mWifiApEnabler; private CheckBoxPreference mEnableWifiAp; private CheckBoxPreference mBluetoothTether; private PreferenceScreen mTetherHelp; private BroadcastReceiver mTetherChangeReceiver; private String[] mUsbRegexs; private String[] mWifiRegexs; private String[] mBluetoothRegexs; private BluetoothPan mBluetoothPan; private static final String WIFI_AP_SSID_AND_SECURITY = "wifi_ap_ssid_and_security"; private static final int CONFIG_SUBTEXT = R.string.wifi_tether_configure_subtext; private String[] mSecurityType; private Preference mCreateNetwork; private WifiApDialog mDialog; private WifiManager mWifiManager; private WifiConfiguration mWifiConfig = null; private boolean mUsbConnected; private boolean mMassStorageActive; private boolean mBluetoothEnableForTether; private static final int INVALID = -1; private static final int WIFI_TETHERING = 0; private static final int USB_TETHERING = 1; private static final int BLUETOOTH_TETHERING = 2; /* One of INVALID, WIFI_TETHERING, USB_TETHERING or BLUETOOTH_TETHERING */ private int mTetherChoice = INVALID; /* Stores the package name and the class name of the provisioning app */ private String[] mProvisionApp; private static final int PROVISION_REQUEST = 0; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); addPreferencesFromResource(R.xml.tether_prefs); final Activity activity = getActivity(); BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); if (adapter != null) { adapter.getProfileProxy(activity.getApplicationContext(), mProfileServiceListener, BluetoothProfile.PAN); } mEnableWifiAp = (CheckBoxPreference) findPreference(ENABLE_WIFI_AP); Preference wifiApSettings = findPreference(WIFI_AP_SSID_AND_SECURITY); mUsbTether = (CheckBoxPreference) findPreference(USB_TETHER_SETTINGS); mBluetoothTether = (CheckBoxPreference) findPreference(ENABLE_BLUETOOTH_TETHERING); mTetherHelp = (PreferenceScreen) findPreference(TETHERING_HELP); ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); mUsbRegexs = cm.getTetherableUsbRegexs(); mWifiRegexs = cm.getTetherableWifiRegexs(); mBluetoothRegexs = cm.getTetherableBluetoothRegexs(); final boolean usbAvailable = mUsbRegexs.length != 0; final boolean wifiAvailable = mWifiRegexs.length != 0; final boolean bluetoothAvailable = mBluetoothRegexs.length != 0; if (!usbAvailable || Utils.isMonkeyRunning()) { getPreferenceScreen().removePreference(mUsbTether); } - if (wifiAvailable) { + if (wifiAvailable && !Utils.isMonkeyRunning()) { mWifiApEnabler = new WifiApEnabler(activity, mEnableWifiAp); initWifiTethering(); } else { getPreferenceScreen().removePreference(mEnableWifiAp); getPreferenceScreen().removePreference(wifiApSettings); } if (!bluetoothAvailable) { getPreferenceScreen().removePreference(mBluetoothTether); } else { if (mBluetoothPan != null && mBluetoothPan.isTetheringOn()) { mBluetoothTether.setChecked(true); } else { mBluetoothTether.setChecked(false); } } mProvisionApp = getResources().getStringArray( com.android.internal.R.array.config_mobile_hotspot_provision_app); mView = new WebView(activity); } private void initWifiTethering() { final Activity activity = getActivity(); mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); mWifiConfig = mWifiManager.getWifiApConfiguration(); mSecurityType = getResources().getStringArray(R.array.wifi_ap_security); mCreateNetwork = findPreference(WIFI_AP_SSID_AND_SECURITY); if (mWifiConfig == null) { final String s = activity.getString( com.android.internal.R.string.wifi_tether_configure_ssid_default); mCreateNetwork.setSummary(String.format(activity.getString(CONFIG_SUBTEXT), s, mSecurityType[WifiApDialog.OPEN_INDEX])); } else { int index = WifiApDialog.getSecurityTypeIndex(mWifiConfig); mCreateNetwork.setSummary(String.format(activity.getString(CONFIG_SUBTEXT), mWifiConfig.SSID, mSecurityType[index])); } } private BluetoothProfile.ServiceListener mProfileServiceListener = new BluetoothProfile.ServiceListener() { public void onServiceConnected(int profile, BluetoothProfile proxy) { mBluetoothPan = (BluetoothPan) proxy; } public void onServiceDisconnected(int profile) { mBluetoothPan = null; } }; @Override public Dialog onCreateDialog(int id) { if (id == DIALOG_TETHER_HELP) { Locale locale = Locale.getDefault(); // check for the full language + country resource, if not there, try just language final AssetManager am = getActivity().getAssets(); String path = HELP_PATH.replace("%y", locale.getLanguage().toLowerCase()); path = path.replace("%z", '_'+locale.getCountry().toLowerCase()); boolean useCountry = true; InputStream is = null; try { is = am.open(path); } catch (Exception ignored) { useCountry = false; } finally { if (is != null) { try { is.close(); } catch (Exception ignored) {} } } String url = HELP_URL.replace("%y", locale.getLanguage().toLowerCase()); url = url.replace("%z", useCountry ? '_'+locale.getCountry().toLowerCase() : ""); if ((mUsbRegexs.length != 0) && (mWifiRegexs.length == 0)) { url = url.replace("%x", USB_HELP_MODIFIER); } else if ((mWifiRegexs.length != 0) && (mUsbRegexs.length == 0)) { url = url.replace("%x", WIFI_HELP_MODIFIER); } else { // could assert that both wifi and usb have regexs, but the default // is to use this anyway so no check is needed url = url.replace("%x", ""); } mView.loadUrl(url); // Detach from old parent first ViewParent parent = mView.getParent(); if (parent != null && parent instanceof ViewGroup) { ((ViewGroup) parent).removeView(mView); } return new AlertDialog.Builder(getActivity()) .setCancelable(true) .setTitle(R.string.tethering_help_button_text) .setView(mView) .create(); } else if (id == DIALOG_AP_SETTINGS) { final Activity activity = getActivity(); mDialog = new WifiApDialog(activity, this, mWifiConfig); return mDialog; } return null; } private class TetherChangeReceiver extends BroadcastReceiver { @Override public void onReceive(Context content, Intent intent) { String action = intent.getAction(); if (action.equals(ConnectivityManager.ACTION_TETHER_STATE_CHANGED)) { // TODO - this should understand the interface types ArrayList<String> available = intent.getStringArrayListExtra( ConnectivityManager.EXTRA_AVAILABLE_TETHER); ArrayList<String> active = intent.getStringArrayListExtra( ConnectivityManager.EXTRA_ACTIVE_TETHER); ArrayList<String> errored = intent.getStringArrayListExtra( ConnectivityManager.EXTRA_ERRORED_TETHER); updateState(available.toArray(new String[available.size()]), active.toArray(new String[active.size()]), errored.toArray(new String[errored.size()])); } else if (action.equals(Intent.ACTION_MEDIA_SHARED)) { mMassStorageActive = true; updateState(); } else if (action.equals(Intent.ACTION_MEDIA_UNSHARED)) { mMassStorageActive = false; updateState(); } else if (action.equals(UsbManager.ACTION_USB_STATE)) { mUsbConnected = intent.getBooleanExtra(UsbManager.USB_CONNECTED, false); updateState(); } else if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) { if (mBluetoothEnableForTether) { switch (intent .getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR)) { case BluetoothAdapter.STATE_ON: mBluetoothPan.setBluetoothTethering(true); mBluetoothEnableForTether = false; break; case BluetoothAdapter.STATE_OFF: case BluetoothAdapter.ERROR: mBluetoothEnableForTether = false; break; default: // ignore transition states } } updateState(); } } } @Override public void onStart() { super.onStart(); final Activity activity = getActivity(); mMassStorageActive = Environment.MEDIA_SHARED.equals(Environment.getExternalStorageState()); mTetherChangeReceiver = new TetherChangeReceiver(); IntentFilter filter = new IntentFilter(ConnectivityManager.ACTION_TETHER_STATE_CHANGED); Intent intent = activity.registerReceiver(mTetherChangeReceiver, filter); filter = new IntentFilter(); filter.addAction(UsbManager.ACTION_USB_STATE); activity.registerReceiver(mTetherChangeReceiver, filter); filter = new IntentFilter(); filter.addAction(Intent.ACTION_MEDIA_SHARED); filter.addAction(Intent.ACTION_MEDIA_UNSHARED); filter.addDataScheme("file"); activity.registerReceiver(mTetherChangeReceiver, filter); filter = new IntentFilter(); filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); activity.registerReceiver(mTetherChangeReceiver, filter); if (intent != null) mTetherChangeReceiver.onReceive(activity, intent); if (mWifiApEnabler != null) { mEnableWifiAp.setOnPreferenceChangeListener(this); mWifiApEnabler.resume(); } updateState(); } @Override public void onStop() { super.onStop(); getActivity().unregisterReceiver(mTetherChangeReceiver); mTetherChangeReceiver = null; if (mWifiApEnabler != null) { mEnableWifiAp.setOnPreferenceChangeListener(null); mWifiApEnabler.pause(); } } private void updateState() { ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); String[] available = cm.getTetherableIfaces(); String[] tethered = cm.getTetheredIfaces(); String[] errored = cm.getTetheringErroredIfaces(); updateState(available, tethered, errored); } private void updateState(String[] available, String[] tethered, String[] errored) { updateUsbState(available, tethered, errored); updateBluetoothState(available, tethered, errored); } private void updateUsbState(String[] available, String[] tethered, String[] errored) { ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); boolean usbAvailable = mUsbConnected && !mMassStorageActive; int usbError = ConnectivityManager.TETHER_ERROR_NO_ERROR; for (String s : available) { for (String regex : mUsbRegexs) { if (s.matches(regex)) { if (usbError == ConnectivityManager.TETHER_ERROR_NO_ERROR) { usbError = cm.getLastTetherError(s); } } } } boolean usbTethered = false; for (String s : tethered) { for (String regex : mUsbRegexs) { if (s.matches(regex)) usbTethered = true; } } boolean usbErrored = false; for (String s: errored) { for (String regex : mUsbRegexs) { if (s.matches(regex)) usbErrored = true; } } if (usbTethered) { mUsbTether.setSummary(R.string.usb_tethering_active_subtext); mUsbTether.setEnabled(true); mUsbTether.setChecked(true); } else if (usbAvailable) { if (usbError == ConnectivityManager.TETHER_ERROR_NO_ERROR) { mUsbTether.setSummary(R.string.usb_tethering_available_subtext); } else { mUsbTether.setSummary(R.string.usb_tethering_errored_subtext); } mUsbTether.setEnabled(true); mUsbTether.setChecked(false); } else if (usbErrored) { mUsbTether.setSummary(R.string.usb_tethering_errored_subtext); mUsbTether.setEnabled(false); mUsbTether.setChecked(false); } else if (mMassStorageActive) { mUsbTether.setSummary(R.string.usb_tethering_storage_active_subtext); mUsbTether.setEnabled(false); mUsbTether.setChecked(false); } else { mUsbTether.setSummary(R.string.usb_tethering_unavailable_subtext); mUsbTether.setEnabled(false); mUsbTether.setChecked(false); } } private void updateBluetoothState(String[] available, String[] tethered, String[] errored) { int bluetoothTethered = 0; for (String s : tethered) { for (String regex : mBluetoothRegexs) { if (s.matches(regex)) bluetoothTethered++; } } boolean bluetoothErrored = false; for (String s: errored) { for (String regex : mBluetoothRegexs) { if (s.matches(regex)) bluetoothErrored = true; } } BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); int btState = adapter.getState(); if (btState == BluetoothAdapter.STATE_TURNING_OFF) { mBluetoothTether.setEnabled(false); mBluetoothTether.setSummary(R.string.wifi_stopping); } else if (btState == BluetoothAdapter.STATE_TURNING_ON) { mBluetoothTether.setEnabled(false); mBluetoothTether.setSummary(R.string.bluetooth_turning_on); } else if (btState == BluetoothAdapter.STATE_ON && mBluetoothPan.isTetheringOn()) { mBluetoothTether.setChecked(true); mBluetoothTether.setEnabled(true); if (bluetoothTethered > 1) { String summary = getString( R.string.bluetooth_tethering_devices_connected_subtext, bluetoothTethered); mBluetoothTether.setSummary(summary); } else if (bluetoothTethered == 1) { mBluetoothTether.setSummary(R.string.bluetooth_tethering_device_connected_subtext); } else if (bluetoothErrored) { mBluetoothTether.setSummary(R.string.bluetooth_tethering_errored_subtext); } else { mBluetoothTether.setSummary(R.string.bluetooth_tethering_available_subtext); } } else { mBluetoothTether.setEnabled(true); mBluetoothTether.setChecked(false); mBluetoothTether.setSummary(R.string.bluetooth_tethering_off_subtext); } } public boolean onPreferenceChange(Preference preference, Object value) { boolean enable = (Boolean) value; if (enable) { startProvisioningIfNecessary(WIFI_TETHERING); } else { mWifiApEnabler.setSoftapEnabled(false); } return false; } boolean isProvisioningNeeded() { return mProvisionApp.length == 2; } private void startProvisioningIfNecessary(int choice) { mTetherChoice = choice; if (isProvisioningNeeded()) { Intent intent = new Intent(Intent.ACTION_MAIN); intent.setClassName(mProvisionApp[0], mProvisionApp[1]); startActivityForResult(intent, PROVISION_REQUEST); } else { startTethering(); } } public void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); if (requestCode == PROVISION_REQUEST) { if (resultCode == Activity.RESULT_OK) { startTethering(); } else { //BT and USB need checkbox turned off on failure //Wifi tethering is never turned on until afterwards switch (mTetherChoice) { case BLUETOOTH_TETHERING: mBluetoothTether.setChecked(false); break; case USB_TETHERING: mUsbTether.setChecked(false); break; } mTetherChoice = INVALID; } } } private void startTethering() { switch (mTetherChoice) { case WIFI_TETHERING: mWifiApEnabler.setSoftapEnabled(true); break; case BLUETOOTH_TETHERING: // turn on Bluetooth first BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); if (adapter.getState() == BluetoothAdapter.STATE_OFF) { mBluetoothEnableForTether = true; adapter.enable(); mBluetoothTether.setSummary(R.string.bluetooth_turning_on); mBluetoothTether.setEnabled(false); } else { mBluetoothPan.setBluetoothTethering(true); mBluetoothTether.setSummary(R.string.bluetooth_tethering_available_subtext); } break; case USB_TETHERING: setUsbTethering(true); break; default: //should not happen break; } } private void setUsbTethering(boolean enabled) { ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); if (cm.setUsbTethering(enabled) != ConnectivityManager.TETHER_ERROR_NO_ERROR) { mUsbTether.setChecked(false); mUsbTether.setSummary(R.string.usb_tethering_errored_subtext); return; } mUsbTether.setSummary(""); } @Override public boolean onPreferenceTreeClick(PreferenceScreen screen, Preference preference) { ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); if (preference == mUsbTether) { boolean newState = mUsbTether.isChecked(); if (newState) { startProvisioningIfNecessary(USB_TETHERING); } else { setUsbTethering(newState); } } else if (preference == mBluetoothTether) { boolean bluetoothTetherState = mBluetoothTether.isChecked(); if (bluetoothTetherState) { startProvisioningIfNecessary(BLUETOOTH_TETHERING); } else { boolean errored = false; String [] tethered = cm.getTetheredIfaces(); String bluetoothIface = findIface(tethered, mBluetoothRegexs); if (bluetoothIface != null && cm.untether(bluetoothIface) != ConnectivityManager.TETHER_ERROR_NO_ERROR) { errored = true; } mBluetoothPan.setBluetoothTethering(false); if (errored) { mBluetoothTether.setSummary(R.string.bluetooth_tethering_errored_subtext); } else { mBluetoothTether.setSummary(R.string.bluetooth_tethering_off_subtext); } } } else if (preference == mTetherHelp) { showDialog(DIALOG_TETHER_HELP); return true; } else if (preference == mCreateNetwork) { showDialog(DIALOG_AP_SETTINGS); } return super.onPreferenceTreeClick(screen, preference); } private static String findIface(String[] ifaces, String[] regexes) { for (String iface : ifaces) { for (String regex : regexes) { if (iface.matches(regex)) { return iface; } } } return null; } public void onClick(DialogInterface dialogInterface, int button) { if (button == DialogInterface.BUTTON_POSITIVE) { mWifiConfig = mDialog.getConfig(); if (mWifiConfig != null) { /** * if soft AP is stopped, bring up * else restart with new config * TODO: update config on a running access point when framework support is added */ if (mWifiManager.getWifiApState() == WifiManager.WIFI_AP_STATE_ENABLED) { mWifiManager.setWifiApEnabled(null, false); mWifiManager.setWifiApEnabled(mWifiConfig, true); } else { mWifiManager.setWifiApConfiguration(mWifiConfig); } int index = WifiApDialog.getSecurityTypeIndex(mWifiConfig); mCreateNetwork.setSummary(String.format(getActivity().getString(CONFIG_SUBTEXT), mWifiConfig.SSID, mSecurityType[index])); } } } }
true
true
public void onCreate(Bundle icicle) { super.onCreate(icicle); addPreferencesFromResource(R.xml.tether_prefs); final Activity activity = getActivity(); BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); if (adapter != null) { adapter.getProfileProxy(activity.getApplicationContext(), mProfileServiceListener, BluetoothProfile.PAN); } mEnableWifiAp = (CheckBoxPreference) findPreference(ENABLE_WIFI_AP); Preference wifiApSettings = findPreference(WIFI_AP_SSID_AND_SECURITY); mUsbTether = (CheckBoxPreference) findPreference(USB_TETHER_SETTINGS); mBluetoothTether = (CheckBoxPreference) findPreference(ENABLE_BLUETOOTH_TETHERING); mTetherHelp = (PreferenceScreen) findPreference(TETHERING_HELP); ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); mUsbRegexs = cm.getTetherableUsbRegexs(); mWifiRegexs = cm.getTetherableWifiRegexs(); mBluetoothRegexs = cm.getTetherableBluetoothRegexs(); final boolean usbAvailable = mUsbRegexs.length != 0; final boolean wifiAvailable = mWifiRegexs.length != 0; final boolean bluetoothAvailable = mBluetoothRegexs.length != 0; if (!usbAvailable || Utils.isMonkeyRunning()) { getPreferenceScreen().removePreference(mUsbTether); } if (wifiAvailable) { mWifiApEnabler = new WifiApEnabler(activity, mEnableWifiAp); initWifiTethering(); } else { getPreferenceScreen().removePreference(mEnableWifiAp); getPreferenceScreen().removePreference(wifiApSettings); } if (!bluetoothAvailable) { getPreferenceScreen().removePreference(mBluetoothTether); } else { if (mBluetoothPan != null && mBluetoothPan.isTetheringOn()) { mBluetoothTether.setChecked(true); } else { mBluetoothTether.setChecked(false); } } mProvisionApp = getResources().getStringArray( com.android.internal.R.array.config_mobile_hotspot_provision_app); mView = new WebView(activity); }
public void onCreate(Bundle icicle) { super.onCreate(icicle); addPreferencesFromResource(R.xml.tether_prefs); final Activity activity = getActivity(); BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); if (adapter != null) { adapter.getProfileProxy(activity.getApplicationContext(), mProfileServiceListener, BluetoothProfile.PAN); } mEnableWifiAp = (CheckBoxPreference) findPreference(ENABLE_WIFI_AP); Preference wifiApSettings = findPreference(WIFI_AP_SSID_AND_SECURITY); mUsbTether = (CheckBoxPreference) findPreference(USB_TETHER_SETTINGS); mBluetoothTether = (CheckBoxPreference) findPreference(ENABLE_BLUETOOTH_TETHERING); mTetherHelp = (PreferenceScreen) findPreference(TETHERING_HELP); ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); mUsbRegexs = cm.getTetherableUsbRegexs(); mWifiRegexs = cm.getTetherableWifiRegexs(); mBluetoothRegexs = cm.getTetherableBluetoothRegexs(); final boolean usbAvailable = mUsbRegexs.length != 0; final boolean wifiAvailable = mWifiRegexs.length != 0; final boolean bluetoothAvailable = mBluetoothRegexs.length != 0; if (!usbAvailable || Utils.isMonkeyRunning()) { getPreferenceScreen().removePreference(mUsbTether); } if (wifiAvailable && !Utils.isMonkeyRunning()) { mWifiApEnabler = new WifiApEnabler(activity, mEnableWifiAp); initWifiTethering(); } else { getPreferenceScreen().removePreference(mEnableWifiAp); getPreferenceScreen().removePreference(wifiApSettings); } if (!bluetoothAvailable) { getPreferenceScreen().removePreference(mBluetoothTether); } else { if (mBluetoothPan != null && mBluetoothPan.isTetheringOn()) { mBluetoothTether.setChecked(true); } else { mBluetoothTether.setChecked(false); } } mProvisionApp = getResources().getStringArray( com.android.internal.R.array.config_mobile_hotspot_provision_app); mView = new WebView(activity); }
diff --git a/robospice-core-parent/robospice/src/main/java/com/octo/android/robospice/SpiceManager.java b/robospice-core-parent/robospice/src/main/java/com/octo/android/robospice/SpiceManager.java index f978585d6..17ed30460 100644 --- a/robospice-core-parent/robospice/src/main/java/com/octo/android/robospice/SpiceManager.java +++ b/robospice-core-parent/robospice/src/main/java/com/octo/android/robospice/SpiceManager.java @@ -1,980 +1,979 @@ package com.octo.android.robospice; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; import roboguice.util.temp.Ln; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.IBinder; import com.octo.android.robospice.SpiceService.SpiceServiceBinder; import com.octo.android.robospice.persistence.DurationInMillis; import com.octo.android.robospice.persistence.exception.CacheLoadingException; import com.octo.android.robospice.request.CachedSpiceRequest; import com.octo.android.robospice.request.SpiceRequest; import com.octo.android.robospice.request.listener.RequestListener; import com.octo.android.robospice.request.listener.SpiceServiceServiceListener; /** * The instances of this class allow to acces the {@link SpiceService}. <br/> * They are tied to activities and obtain a local binding to the {@link SpiceService}. When binding occurs, the {@link SpiceManager} will send commadnds to the {@link SpiceService}, to execute * requests, clear cache, prevent listeners from being called and so on. Basically, all features of the {@link SpiceService} are accessible from the {@link SpiceManager}. It acts as an asynchronous * proxy : every call to a {@link SpiceService} method is asynchronous and will occur as soon as possible when the {@link SpiceManager} successfully binds to the service. * @author jva * @author sni * @author mwa */ /* * Note to maintainers : This class is quite complex and requires background knowledge in multi-threading & local service binding in android. Thx to Henri Tremblay (from EasyMock) for his happy code * review. */ public class SpiceManager implements Runnable { /** The class of the {@link SpiceService} to bind to. */ private final Class<? extends SpiceService> spiceServiceClass; /** A reference on the {@link SpiceService} obtained by local binding. */ private SpiceService spiceService; /** {@link SpiceService} binder. */ private SpiceServiceConnection spiceServiceConnection = new SpiceServiceConnection(); /** The contextWeakReference used to bind to the service from. */ private WeakReference<Context> contextWeakReference; /** * Whether or not {@link SpiceManager} is started. Must be volatile to ensure multi-thread consistency. */ private volatile boolean isStopped = true; /** The queue of requests to be sent to the service. */ private final BlockingQueue<CachedSpiceRequest<?>> requestQueue = new LinkedBlockingQueue<CachedSpiceRequest<?>>(); /** * The list of all requests that have not yet been passed to the service. All iterations must be synchronized. */ private final Map<CachedSpiceRequest<?>, Set<RequestListener<?>>> mapRequestToLaunchToRequestListener = Collections .synchronizedMap(new IdentityHashMap<CachedSpiceRequest<?>, Set<RequestListener<?>>>()); /** * The list of all requests that have already been passed to the service. All iterations must be synchronized. */ private final Map<CachedSpiceRequest<?>, Set<RequestListener<?>>> mapPendingRequestToRequestListener = Collections .synchronizedMap(new IdentityHashMap<CachedSpiceRequest<?>, Set<RequestListener<?>>>()); private final ExecutorService executorService = Executors.newSingleThreadExecutor(); /** * Lock used to synchronize binding to / unbinding from the {@link SpiceService}. */ private final ReentrantLock lockAcquireService = new ReentrantLock(); /** A monitor to ensure service is bound before accessing it. */ private final Condition conditionServiceBound = lockAcquireService.newCondition(); /** A monitor to ensure service is unbound. */ private final Condition conditionServiceUnbound = lockAcquireService.newCondition(); /** * Lock used to synchronize transmission of requests to the {@link SpiceService}. */ private final ReentrantLock lockSendRequestsToService = new ReentrantLock(); /** Thread running runnable code. */ protected Thread runner; /** Reacts to service processing of requests. */ private final RequestRemoverSpiceServiceListener removerSpiceServiceListener = new RequestRemoverSpiceServiceListener(); /** * Whether or not we are unbinding (to prevent unbinding twice. Must be volatile to ensure multi-thread consistency. */ private volatile boolean isUnbinding = false; // ============================================================================================ // THREAD BEHAVIOR // ============================================================================================ /** * Creates a {@link SpiceManager}. Typically this occurs in the construction of an Activity or Fragment. This method will check if the service to bind to has been properly declared in * AndroidManifest. * @param spiceServiceClass * the service class to bind to. */ public SpiceManager(final Class<? extends SpiceService> spiceServiceClass) { this.spiceServiceClass = spiceServiceClass; } /** * Start the {@link SpiceManager}. It will bind asynchronously to the {@link SpiceService}. * @param contextWeakReference * a contextWeakReference that will be used to bind to the service. Typically, the Activity or Fragment that needs to interact with the {@link SpiceService}. */ public synchronized void start(final Context context) { this.contextWeakReference = new WeakReference<Context>(context); if (runner != null) { throw new IllegalStateException("Already started."); } else { // start the binding to the service runner = new Thread(this); isStopped = false; runner.start(); Ln.d("SpiceManager started."); } } /** * Method is synchronized with {@link #start(Context)}. * @return whether or not the {@link SpiceManager} is started. */ public synchronized boolean isStarted() { return !isStopped; } @Override public void run() { // start the service it is not started yet. Context context = contextWeakReference.get(); if (context != null) { checkServiceIsProperlyDeclaredInAndroidManifest(context); final Intent intent = new Intent(context, spiceServiceClass); context.startService(intent); } else { Ln.d("Service was not started as Activity died prematurely"); isStopped = true; - shouldStop(); } bindToService(contextWeakReference.get()); try { waitForServiceToBeBound(); if (spiceService == null) { return; } while (!isStopped) { try { sendRequestToService(requestQueue.take()); } catch (final InterruptedException ex) { Ln.d("Interrupted while waiting for new request."); } } } catch (final InterruptedException e) { Ln.d(e, "Interrupted while waiting for acquiring service."); } finally { unbindFromService(contextWeakReference.get()); } } private void sendRequestToService(final CachedSpiceRequest<?> spiceRequest) { lockSendRequestsToService.lock(); try { if (spiceRequest != null) { final Set<RequestListener<?>> listRequestListener = mapRequestToLaunchToRequestListener.remove(spiceRequest); mapPendingRequestToRequestListener.put(spiceRequest, listRequestListener); Ln.d("Sending request to service : " + spiceRequest.getClass().getSimpleName()); spiceService.addRequest(spiceRequest, listRequestListener); } } finally { lockSendRequestsToService.unlock(); } } /** * Stops the {@link SpiceManager}. It will unbind from {@link SpiceService}. All request listeners that had been registered to listen to {@link SpiceRequest}s sent from this {@link SpiceManager} * will be unregistered. None of them will be notified with the results of their {@link SpiceRequest}s. Unbinding will occur asynchronously. */ public synchronized void shouldStop() { if (this.runner == null) { throw new IllegalStateException("Not started yet"); } Ln.d("SpiceManager stopping."); dontNotifyAnyRequestListenersInternal(); isUnbinding = false; unbindFromService(contextWeakReference.get()); spiceServiceConnection = null; this.isStopped = true; this.runner.interrupt(); this.runner = null; this.contextWeakReference.clear(); Ln.d("SpiceManager stopped."); } /** * This is mostly a testing method. Stops the {@link SpiceManager}. It will unbind from {@link SpiceService}. All request listeners that had been registered to listen to {@link SpiceRequest}s sent * from this {@link SpiceManager} will be unregistered. None of them will be notified with the results of their {@link SpiceRequest}s. Unbinding will occur syncrhonously : the method returns when * all events have been unregistered and when main processing thread stops. */ public synchronized void shouldStopAndJoin(final long timeOut) throws InterruptedException { if (this.runner == null) { throw new IllegalStateException("Not started yet"); } Ln.d("SpiceManager stopping. Joining"); dontNotifyAnyRequestListenersInternal(); unbindFromService(contextWeakReference.get()); this.isStopped = true; this.runner.interrupt(); this.runner.join(timeOut); this.runner = null; this.contextWeakReference.clear(); Ln.d("SpiceManager stopped."); } // ============================================================================================ // PUBLIC EXPOSED METHODS : requests executions // ============================================================================================ /** * Get some data previously saved in cache with key <i>requestCacheKey</i> with maximum time in cache : <i>cacheDuration</i> millisecond and register listeners to notify when request is finished. * This method executes a SpiceRequest with no network processing. It just checks whatever is in the cache and return it, including null if there is no such data found in cache. * @param clazz * the class of the result to retrieve from cache. * @param requestCacheKey * the key used to store and retrieve the result of the request in the cache * @param cacheExpiryDuration * duration in milliseconds after which the content of the cache will be considered to be expired. {@link DurationInMillis#ALWAYS_RETURNED} means data in cache is always returned if it * exists. {@link DurationInMillis#ALWAYS_EXPIRED} means data in cache is never returned.(see {@link DurationInMillis}) * @param requestListener * the listener to notify when the request will finish. If nothing is found in cache, listeners will receive a null result on their {@link RequestListener#onRequestSuccess(Object)} * method. If something is found in cache, they will receive it in this method. If an error occurs, they will be notified via their * {@link RequestListener#onRequestFailure(com.octo.android.robospice.persistence.exception.SpiceException)} method. */ public <T> void getFromCache(final Class<T> clazz, final Object requestCacheKey, final long cacheExpiryDuration, final RequestListener<T> requestListener) { final SpiceRequest<T> request = new SpiceRequest<T>(clazz) { @Override public T loadDataFromNetwork() throws Exception { return null; } @Override public boolean isAggregatable() { return false; } }; final CachedSpiceRequest<T> cachedSpiceRequest = new CachedSpiceRequest<T>(request, requestCacheKey, cacheExpiryDuration); execute(cachedSpiceRequest, requestListener); } /** * Add listener to a pending request if it exists. If no such request exists, this method does nothing. If a request identified by clazz and requestCacheKey, it will receive an additional * listener. * @param clazz * the class of the result of the pending request to look for. * @param requestCacheKey * the key used to store and retrieve the result of the request in the cache * @param requestListener * the listener to notify when the request will finish. */ public <T> void addListenerIfPending(final Class<T> clazz, final Object requestCacheKey, final RequestListener<T> requestListener) { final SpiceRequest<T> request = new SpiceRequest<T>(clazz) { @Override public T loadDataFromNetwork() throws Exception { return null; } }; final CachedSpiceRequest<T> cachedSpiceRequest = new CachedSpiceRequest<T>(request, requestCacheKey, DurationInMillis.ALWAYS_EXPIRED); cachedSpiceRequest.setProcessable(false); execute(cachedSpiceRequest, requestListener); } /** * Execute a request, without using cache. No result from cache will be returned. The method {@link SpiceRequest#loadDataFromNetwork()} will always be invoked. The result will not be stored in * cache. * @param request * the request to execute. * @param requestListener * the listener to notify when the request will finish. */ public <T> void execute(final SpiceRequest<T> request, final RequestListener<T> requestListener) { final CachedSpiceRequest<T> cachedSpiceRequest = new CachedSpiceRequest<T>(request, null, DurationInMillis.ALWAYS_RETURNED); execute(cachedSpiceRequest, requestListener); } /** * Execute a request. Before invoking the method {@link SpiceRequest#loadDataFromNetwork()}, the cache will be checked : if a result has been cached with the cache key <i>requestCacheKey</i>, * RoboSpice will consider the parameter <i>cacheExpiryDuration</i> to determine whether the result in the cache is expired or not. If it is not expired, then listeners will receive the data in * cache. Otherwise, the method {@link SpiceRequest#loadDataFromNetwork()} will be invoked and the result will be stored in cache using the cache key <i>requestCacheKey</i>. * @param request * the request to execute * @param requestCacheKey * the key used to store and retrieve the result of the request in the cache * @param cacheExpiryDuration * duration in milliseconds after which the content of the cache will be considered to be expired. {@link DurationInMillis#ALWAYS_RETURNED} means data in cache is always returned if it * exists. {@link DurationInMillis#ALWAYS_EXPIRED} means data in cache is never returned.(see {@link DurationInMillis}) * @param requestListener * the listener to notify when the request will finish */ public <T> void execute(final SpiceRequest<T> request, final Object requestCacheKey, final long cacheExpiryDuration, final RequestListener<T> requestListener) { final CachedSpiceRequest<T> cachedSpiceRequest = new CachedSpiceRequest<T>(request, requestCacheKey, cacheExpiryDuration); execute(cachedSpiceRequest, requestListener); } /** * Execute a request, put the result in cache and register listeners to notify when request is finished. * @param cachedSpiceRequest * the request to execute. {@link CachedSpiceRequest} is a wrapper of {@link SpiceRequest} that contains cache key and cache duration * @param requestListener * the listener to notify when the request will finish */ public <T> void execute(final CachedSpiceRequest<T> cachedSpiceRequest, final RequestListener<T> requestListener) { addRequestListenerToListOfRequestListeners(cachedSpiceRequest, requestListener); this.requestQueue.add(cachedSpiceRequest); } /** * Gets data from cache, expired or not, and executes a request normaly. Before invoking the method {@link SpiceRequest#loadDataFromNetwork()}, the cache will be checked : if a result has been * cached with the cache key <i>requestCacheKey</i>, RoboSpice will consider the parameter <i>cacheExpiryDuration</i> to determine whether the result in the cache is expired or not. If it is not * expired, then listeners will receive the data in cache only. If the result is absent or expired, then {@link SpiceRequest#loadDataFromNetwork()} will be invoked and the result will be stored in * cache using the cache key <i>requestCacheKey</i>. * @param request * the request to execute * @param requestCacheKey * the key used to store and retrieve the result of the request in the cache * @param cacheExpiryDuration * duration in milliseconds after which the content of the cache will be considered to be expired. {@link DurationInMillis#ALWAYS_RETURNED} means data in cache is always returned if it * exists. {@link DurationInMillis#ALWAYS_EXPIRED} doesn't make much sense here. * @param requestListener * the listener to notify when the request will finish */ public <T> void getFromCacheAndLoadFromNetworkIfExpired(final SpiceRequest<T> request, final Object requestCacheKey, final long cacheExpiryDuration, final RequestListener<T> requestListener) { final CachedSpiceRequest<T> cachedSpiceRequest = new CachedSpiceRequest<T>(request, requestCacheKey, cacheExpiryDuration); cachedSpiceRequest.setAcceptingDirtyCache(true); execute(cachedSpiceRequest, requestListener); } /** * Cancel a pending request if it exists. If no such request exists, this method does nothing. If a request identified by clazz and requestCacheKey exists, it will be cancelled and its associated * listeners will get notified. * @param clazz * the class of the result of the pending request to look for. * @param requestCacheKey * the cache key associated to the request's results. */ public <T> void cancel(final Class<T> clazz, final Object requestCacheKey) { final SpiceRequest<T> request = new SpiceRequest<T>(clazz) { @Override public T loadDataFromNetwork() throws Exception { return null; } }; final CachedSpiceRequest<T> cachedSpiceRequest = new CachedSpiceRequest<T>(request, requestCacheKey, DurationInMillis.ALWAYS_EXPIRED); cachedSpiceRequest.setProcessable(false); cachedSpiceRequest.cancel(); execute(cachedSpiceRequest, null); } // ============================================================================================ // PUBLIC EXPOSED METHODS : unregister listeners // ============================================================================================ /** * Disable request listeners notifications for a specific request.<br/> * None of the listeners associated to this request will be called when request will finish.<br/> * This method will ask (asynchronously) to the {@link SpiceService} to remove listeners if requests have already been sent to the {@link SpiceService} if the request has already been sent to the * service. Otherwise, it will just remove listeners before passing the request to the {@link SpiceService}. Calling this method doesn't prevent request from being executed (and put in cache) but * will remove request's listeners notification. * @param request * Request for which listeners are to unregistered. */ public void dontNotifyRequestListenersForRequest(final SpiceRequest<?> request) { executorService.execute(new Runnable() { @Override public void run() { dontNotifyRequestListenersForRequestInternal(request); } }); } /** * Internal method to remove requests. If request has not been passed to the {@link SpiceService} yet, all listeners are unregistered locally before being passed to the service. Otherwise, it will * asynchronously ask to the {@link SpiceService} to remove the listeners of the request being processed. * @param request * Request for which listeners are to unregistered. */ protected void dontNotifyRequestListenersForRequestInternal(final SpiceRequest<?> request) { try { lockSendRequestsToService.lock(); final boolean requestNotPassedToServiceYet = removeListenersOfCachedRequestToLaunch(request); Ln.v("Removed from requests to launch list : " + requestNotPassedToServiceYet); // if the request was already passed to service, bind to // service and // unregister listeners. if (!requestNotPassedToServiceYet) { removeListenersOfPendingCachedRequest(request); Ln.v("Removed from pending requests list"); } } catch (final InterruptedException e) { Ln.e(e, "Interrupted while removing listeners."); } finally { lockSendRequestsToService.unlock(); } } /** * Remove all listeners of a request that has not yet been passed to the {@link SpiceService}. * @param request * the request for which listeners must be unregistered. * @return a boolean indicating if the request could be found inside the list of requests to be launched. If false, the request was already passed to the service. */ private boolean removeListenersOfCachedRequestToLaunch(final SpiceRequest<?> request) { synchronized (mapRequestToLaunchToRequestListener) { for (final CachedSpiceRequest<?> cachedSpiceRequest : mapRequestToLaunchToRequestListener.keySet()) { if (match(cachedSpiceRequest, request)) { final Set<RequestListener<?>> setRequestListeners = mapRequestToLaunchToRequestListener.get(cachedSpiceRequest); setRequestListeners.clear(); return true; } } return false; } } /** * Remove all listeners of a request that may have already been passed to the {@link SpiceService}. If the request has already been passed to the {@link SpiceService}, the method will bind to the * service and ask it to remove listeners. * @param request * the request for which listeners must be unregistered. */ private void removeListenersOfPendingCachedRequest(final SpiceRequest<?> request) throws InterruptedException { synchronized (mapPendingRequestToRequestListener) { for (final CachedSpiceRequest<?> cachedSpiceRequest : mapPendingRequestToRequestListener.keySet()) { if (match(cachedSpiceRequest, request)) { waitForServiceToBeBound(); if (spiceService == null) { return; } final Set<RequestListener<?>> setRequestListeners = mapPendingRequestToRequestListener.get(cachedSpiceRequest); spiceService.dontNotifyRequestListenersForRequest(cachedSpiceRequest, setRequestListeners); mapPendingRequestToRequestListener.remove(cachedSpiceRequest); break; } } } } /** * Disable request listeners notifications for all requests. <br/> * Should be called in {@link Activity#onStop} */ public void dontNotifyAnyRequestListeners() { executorService.execute(new Runnable() { @Override public void run() { dontNotifyAnyRequestListenersInternal(); } }); } /** * Remove all listeners of requests. All requests that have not been yet passed to the service will see their of listeners cleaned. For all requests that have been passed to the service, we ask * the service to remove their listeners. */ protected void dontNotifyAnyRequestListenersInternal() { try { lockSendRequestsToService.lock(); mapRequestToLaunchToRequestListener.clear(); Ln.v("Cleared listeners of all requests to launch"); removeListenersOfAllPendingCachedRequests(); } catch (final InterruptedException e) { Ln.e(e, "Interrupted while removing listeners."); } finally { lockSendRequestsToService.unlock(); } } /** * Asynchronously ask service to remove all listeners of pending requests. * @throws InterruptedException * in case service binding fails. */ private void removeListenersOfAllPendingCachedRequests() throws InterruptedException { synchronized (mapPendingRequestToRequestListener) { if (!mapPendingRequestToRequestListener.isEmpty()) { if (spiceService == null) { return; } for (final CachedSpiceRequest<?> cachedSpiceRequest : mapPendingRequestToRequestListener.keySet()) { final Set<RequestListener<?>> setRequestListeners = mapPendingRequestToRequestListener.get(cachedSpiceRequest); if (setRequestListeners != null) { Ln.d("Removing listeners of request : " + cachedSpiceRequest.toString() + " : " + setRequestListeners.size()); spiceService.dontNotifyRequestListenersForRequest(cachedSpiceRequest, setRequestListeners); } } mapPendingRequestToRequestListener.clear(); } Ln.v("Cleared listeners of all pending requests"); } } /** * Wether or not a given {@link CachedSpiceRequest} matches a {@link SpiceRequest}. * @param cachedSpiceRequest * the request know by the {@link SpiceManager}. * @param spiceRequest * the request that we wish to remove notification for. * @return true if {@link CachedSpiceRequest} matches contentRequest. */ private boolean match(final CachedSpiceRequest<?> cachedSpiceRequest, final SpiceRequest<?> spiceRequest) { if (spiceRequest instanceof CachedSpiceRequest) { return spiceRequest == cachedSpiceRequest; } else { return cachedSpiceRequest.getSpiceRequest() == spiceRequest; } } // ============================================================================================ // PUBLIC EXPOSED METHODS : content service driving. // ============================================================================================ /** * Cancel a specific request * @param request * the request to cancel */ public void cancel(final SpiceRequest<?> request) { executorService.execute(new Runnable() { @Override public void run() { request.cancel(); } }); } /** * Cancel all requests */ public void cancelAllRequests() { executorService.execute(new Runnable() { @Override public void run() { cancelAllRequestsInternal(); } }); } private void cancelAllRequestsInternal() { try { lockSendRequestsToService.lock(); // cancel each request that to be sent to service, and // keep // listening for // cancellation. synchronized (mapRequestToLaunchToRequestListener) { for (final CachedSpiceRequest<?> cachedSpiceRequest : mapRequestToLaunchToRequestListener.keySet()) { cachedSpiceRequest.cancel(); } } // cancel each request that has been sent to service, // and keep // listening for cancellation. // we must duplicate the list as each call to cancel // will, by a listener of request processing // remove the request from our list. final List<CachedSpiceRequest<?>> listDuplicate = new ArrayList<CachedSpiceRequest<?>>(mapPendingRequestToRequestListener.keySet()); for (final CachedSpiceRequest<?> cachedSpiceRequest : listDuplicate) { cachedSpiceRequest.cancel(); } } finally { lockSendRequestsToService.unlock(); } } public <T> Future<List<Object>> getAllCacheKeys(final Class<T> clazz) { return executorService.submit(new Callable<List<Object>>() { @Override public List<Object> call() throws Exception { waitForServiceToBeBound(); if (spiceService == null) { return new ArrayList<Object>(); } return spiceService.getAllCacheKeys(clazz); } }); } public <T> Future<List<T>> getAllDataFromCache(final Class<T> clazz) throws CacheLoadingException { return executorService.submit(new Callable<List<T>>() { @Override public List<T> call() throws Exception { waitForServiceToBeBound(); if (spiceService == null) { return new ArrayList<T>(); } return spiceService.loadAllDataFromCache(clazz); } }); } /** * Get some data previously saved in cache with key <i>requestCacheKey</i>. This method doesn't perform any network processing, it just check if there are previously saved data. Don't call this * method in the main thread because you could block it. Instead, use the asynchronous version of this method: {@link #getFromCache(final Class<T>, final Object, final long, final * RequestListener<T>) getFromCache}. * @param clazz * the class of the result to retrieve from cache. * @param cacheKey * the key used to store and retrieve the result of the request in the cache * @return * @throws CacheLoadingException * Exception thrown when a problem occurs while loading data from cache. */ public <T> Future<T> getDataFromCache(final Class<T> clazz, final Object cacheKey) throws CacheLoadingException { return executorService.submit(new Callable<T>() { @Override public T call() throws Exception { waitForServiceToBeBound(); if (spiceService == null) { return null; } return spiceService.getDataFromCache(clazz, cacheKey); } }); } /** * Remove some specific content from cache * @param clazz * the Type of data you want to remove from cache * @param cacheKey * the key of the object in cache */ public <T> void removeDataFromCache(final Class<T> clazz, final Object cacheKey) { executorService.execute(new Runnable() { @Override public void run() { try { waitForServiceToBeBound(); if (spiceService == null) { return; } spiceService.removeDataFromCache(clazz, cacheKey); } catch (final InterruptedException e) { Ln.e(e, "Interrupted while waiting for acquiring service."); } } }); } /** * Remove some specific content from cache * @param clazz * the type of data you want to remove from cache. */ public <T> void removeDataFromCache(final Class<T> clazz) { executorService.execute(new Runnable() { @Override public void run() { try { waitForServiceToBeBound(); if (spiceService == null) { return; } spiceService.removeAllDataFromCache(clazz); } catch (final InterruptedException e) { Ln.e(e, "Interrupted while waiting for acquiring service."); } } }); } /** * Remove all data from cache. This will clear all data stored by the {@link CacheManager} of the {@link SpiceService}. */ public void removeAllDataFromCache() { executorService.execute(new Runnable() { @Override public void run() { try { waitForServiceToBeBound(); if (spiceService == null) { return; } spiceService.removeAllDataFromCache(); } catch (final InterruptedException e) { Ln.e(e, "Interrupted while waiting for acquiring service."); } } }); } /** * Configure the behavior in case of error during reading/writing cache. <br/> * Specify wether an error on reading/writing cache must fail the process. * @param failOnCacheError * true if an error must fail the process */ public void setFailOnCacheError(final boolean failOnCacheError) { executorService.execute(new Runnable() { @Override public void run() { try { waitForServiceToBeBound(); if (spiceService == null) { return; } spiceService.setFailOnCacheError(failOnCacheError); } catch (final InterruptedException e) { Ln.e(e, "Interrupted while waiting for acquiring service."); } } }); } private <T> void addRequestListenerToListOfRequestListeners(final CachedSpiceRequest<T> cachedSpiceRequest, final RequestListener<T> requestListener) { synchronized (mapRequestToLaunchToRequestListener) { Set<RequestListener<?>> listeners = mapRequestToLaunchToRequestListener.get(cachedSpiceRequest); if (listeners == null) { listeners = new HashSet<RequestListener<?>>(); this.mapRequestToLaunchToRequestListener.put(cachedSpiceRequest, listeners); } listeners.add(requestListener); } } // ------------------------------- // -------Listeners notification // ------------------------------- /** * Dumps request processor state. */ public void dumpState() { executorService.execute(new Runnable() { @Override public void run() { lockSendRequestsToService.lock(); try { final StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("[SpiceManager : "); stringBuilder.append("Requests to be launched : \n"); dumpMap(stringBuilder, mapRequestToLaunchToRequestListener); stringBuilder.append("Pending requests : \n"); dumpMap(stringBuilder, mapPendingRequestToRequestListener); stringBuilder.append(']'); waitForServiceToBeBound(); if (spiceService == null) { return; } spiceService.dumpState(); } catch (final InterruptedException e) { Ln.e(e, "Interrupted while waiting for acquiring service."); } finally { lockSendRequestsToService.unlock(); } } }); } // ============================================================================================ // INNER CLASS // ============================================================================================ /** Reacts to binding/unbinding with {@link SpiceService}. */ public class SpiceServiceConnection implements ServiceConnection { @Override public void onServiceConnected(final ComponentName name, final IBinder service) { lockAcquireService.lock(); try { spiceService = ((SpiceServiceBinder) service).getSpiceService(); spiceService.addSpiceServiceListener(new RequestRemoverSpiceServiceListener()); Ln.d("Bound to service : " + spiceService.getClass().getSimpleName()); conditionServiceBound.signalAll(); } finally { lockAcquireService.unlock(); } } /** Called only for unexpected unbinding. */ @Override public void onServiceDisconnected(final ComponentName name) { lockAcquireService.lock(); try { Ln.d("Unbound from service start : " + spiceService.getClass().getSimpleName()); spiceService = null; isUnbinding = false; conditionServiceUnbound.signalAll(); } finally { lockAcquireService.unlock(); } } } /** * Called when a request has been processed by the {@link SpiceService}. */ private class RequestRemoverSpiceServiceListener implements SpiceServiceServiceListener { @Override public void onRequestProcessed(final CachedSpiceRequest<?> cachedSpiceRequest) { synchronized (mapPendingRequestToRequestListener) { mapPendingRequestToRequestListener.remove(cachedSpiceRequest); } } } // ============================================================================================ // PRIVATE METHODS : SpiceService binding management. // ============================================================================================ /** For testing purpose. */ protected boolean isBound() { return spiceService != null; } private void bindToService(final Context context) { if (context == null || isStopped) { // fix issue 40. Thx Shussu return; } try { lockAcquireService.lock(); if (spiceService == null) { final Intent intentService = new Intent(context, spiceServiceClass); Ln.v("Binding to service."); spiceServiceConnection = new SpiceServiceConnection(); context.getApplicationContext().bindService(intentService, spiceServiceConnection, Context.BIND_AUTO_CREATE); } } finally { lockAcquireService.unlock(); } } private void unbindFromService(final Context context) { if (context == null) { return; } try { Ln.v("Unbinding from service start."); lockAcquireService.lock(); if (spiceService != null && !isUnbinding) { isUnbinding = true; spiceService.removeSpiceServiceListener(removerSpiceServiceListener); Ln.v("Unbinding from service."); context.getApplicationContext().unbindService(this.spiceServiceConnection); Ln.d("Unbound from service : " + spiceService.getClass().getSimpleName()); spiceService = null; isUnbinding = false; } } catch (final Exception e) { Ln.e(e, "Could not unbind from service."); } finally { lockAcquireService.unlock(); } } /** * Wait for acquiring binding to {@link SpiceService}. * @throws InterruptedException * in case the binding is interrupted. */ protected void waitForServiceToBeBound() throws InterruptedException { Ln.d("Waiting for service to be bound."); lockAcquireService.lock(); try { while (spiceService == null && !isStopped) { conditionServiceBound.await(); } } finally { lockAcquireService.unlock(); } } /** * Wait for acquiring binding to {@link SpiceService}. * @throws InterruptedException * in case the binding is interrupted. */ protected void waitForServiceToBeUnbound() throws InterruptedException { Ln.d("Waiting for service to be unbound."); lockAcquireService.lock(); try { while (spiceService != null) { conditionServiceUnbound.await(); } } finally { lockAcquireService.unlock(); } } private void checkServiceIsProperlyDeclaredInAndroidManifest(final Context context) { final Intent intentCheck = new Intent(context, spiceServiceClass); if (context.getPackageManager().queryIntentServices(intentCheck, 0).isEmpty()) { shouldStop(); throw new RuntimeException("Impossible to start SpiceManager as no service of class : " + spiceServiceClass.getName() + " is registered in AndroidManifest.xml file !"); } } private void dumpMap(final StringBuilder stringBuilder, final Map<CachedSpiceRequest<?>, Set<RequestListener<?>>> map) { synchronized (map) { stringBuilder.append(" request count= "); stringBuilder.append(mapRequestToLaunchToRequestListener.keySet().size()); stringBuilder.append(", listeners per requests = ["); for (final Map.Entry<CachedSpiceRequest<?>, Set<RequestListener<?>>> entry : map.entrySet()) { stringBuilder.append(entry.getKey().getClass().getName()); stringBuilder.append(":"); stringBuilder.append(entry.getKey()); stringBuilder.append(" --> "); if (entry.getValue() == null) { stringBuilder.append(entry.getValue()); } else { stringBuilder.append(entry.getValue().size()); } stringBuilder.append(" listeners"); stringBuilder.append('\n'); } stringBuilder.append(']'); stringBuilder.append('\n'); } } }
true
true
public void run() { // start the service it is not started yet. Context context = contextWeakReference.get(); if (context != null) { checkServiceIsProperlyDeclaredInAndroidManifest(context); final Intent intent = new Intent(context, spiceServiceClass); context.startService(intent); } else { Ln.d("Service was not started as Activity died prematurely"); isStopped = true; shouldStop(); } bindToService(contextWeakReference.get()); try { waitForServiceToBeBound(); if (spiceService == null) { return; } while (!isStopped) { try { sendRequestToService(requestQueue.take()); } catch (final InterruptedException ex) { Ln.d("Interrupted while waiting for new request."); } } } catch (final InterruptedException e) { Ln.d(e, "Interrupted while waiting for acquiring service."); } finally { unbindFromService(contextWeakReference.get()); } }
public void run() { // start the service it is not started yet. Context context = contextWeakReference.get(); if (context != null) { checkServiceIsProperlyDeclaredInAndroidManifest(context); final Intent intent = new Intent(context, spiceServiceClass); context.startService(intent); } else { Ln.d("Service was not started as Activity died prematurely"); isStopped = true; } bindToService(contextWeakReference.get()); try { waitForServiceToBeBound(); if (spiceService == null) { return; } while (!isStopped) { try { sendRequestToService(requestQueue.take()); } catch (final InterruptedException ex) { Ln.d("Interrupted while waiting for new request."); } } } catch (final InterruptedException e) { Ln.d(e, "Interrupted while waiting for acquiring service."); } finally { unbindFromService(contextWeakReference.get()); } }
diff --git a/src/com/turt2live/antishare/ASListener.java b/src/com/turt2live/antishare/ASListener.java index 037cc9da..20f5a5c3 100644 --- a/src/com/turt2live/antishare/ASListener.java +++ b/src/com/turt2live/antishare/ASListener.java @@ -1,1002 +1,1007 @@ package com.turt2live.antishare; import java.io.BufferedWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.block.Chest; import org.bukkit.block.Furnace; import org.bukkit.block.Jukebox; import org.bukkit.entity.Boat; import org.bukkit.entity.Entity; import org.bukkit.entity.Item; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Minecart; import org.bukkit.entity.Painting; import org.bukkit.entity.Player; import org.bukkit.entity.PoweredMinecart; import org.bukkit.entity.Projectile; import org.bukkit.entity.StorageMinecart; import org.bukkit.entity.ThrownExpBottle; import org.bukkit.entity.Vehicle; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockPistonExtendEvent; import org.bukkit.event.block.BlockPistonRetractEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; import org.bukkit.event.entity.EntityTargetEvent; import org.bukkit.event.entity.ExpBottleEvent; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.player.PlayerChangedWorldEvent; import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.event.player.PlayerDropItemEvent; import org.bukkit.event.player.PlayerEggThrowEvent; import org.bukkit.event.player.PlayerGameModeChangeEvent; import org.bukkit.event.player.PlayerInteractEntityEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerKickEvent; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.event.player.PlayerPickupItemEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.vehicle.VehicleDestroyEvent; import org.bukkit.event.world.WorldLoadEvent; import org.bukkit.event.world.WorldUnloadEvent; import org.bukkit.inventory.ItemStack; import com.turt2live.antishare.notification.Alert.AlertTrigger; import com.turt2live.antishare.notification.Alert.AlertType; import com.turt2live.antishare.permissions.PermissionNodes; import com.turt2live.antishare.regions.ASRegion; import com.turt2live.antishare.storage.PerWorldConfig; import com.turt2live.antishare.storage.PerWorldConfig.ListType; /** * The core listener - Listens to all events needed by AntiShare and handles them * * @author turt2live */ public class ASListener implements Listener { private AntiShare plugin = AntiShare.instance; private ConcurrentHashMap<World, PerWorldConfig> config = new ConcurrentHashMap<World, PerWorldConfig>(); /** * Creates a new Listener */ public ASListener(){ reload(); } /** * Reloads lists */ public void reload(){ config.clear(); for(World world : Bukkit.getWorlds()){ config.put(world, new PerWorldConfig(world)); } } /** * Prints out each world to the writer * * @param out the writer * @throws IOException for internal handling */ public void print(BufferedWriter out) throws IOException{ for(World world : config.keySet()){ out.write("## WORLD: " + world.getName() + " \r\n"); config.get(world).print(out); } } // ################# World Load @EventHandler public void onWorldLoad(WorldLoadEvent event){ World world = event.getWorld(); config.put(world, new PerWorldConfig(world)); } // ################# World Unload @EventHandler public void onWorldUnload(WorldUnloadEvent event){ World world = event.getWorld(); config.remove(world); } // ################# Block Break @EventHandler (priority = EventPriority.LOWEST, ignoreCancelled = true) public void onBlockBreak(BlockBreakEvent event){ Player player = event.getPlayer(); Block block = event.getBlock(); AlertType type = AlertType.ILLEGAL; boolean special = false; boolean region = false; Boolean drops = null; AlertType specialType = AlertType.LEGAL; String blockGM = "Unknown"; // Check if they should be blocked if(!plugin.isBlocked(player, PermissionNodes.ALLOW_BLOCK_BREAK, block.getWorld())){ type = AlertType.LEGAL; } if(!config.get(block.getWorld()).isBlocked(block.getType(), ListType.BLOCK_BREAK)){ type = AlertType.LEGAL; } // Check creative/survival blocks if(!plugin.getPermissions().has(player, PermissionNodes.FREE_PLACE)){ GameMode blockGamemode = plugin.getBlockManager().getType(block); if(blockGamemode != null){ special = true; blockGM = blockGamemode.name().toLowerCase(); String oGM = blockGM.equalsIgnoreCase("creative") ? "survival" : "creative"; if(player.getGameMode() != blockGamemode){ boolean deny = plugin.getConfig().getBoolean("settings." + oGM + "-breaking-" + blockGM + "-blocks.deny"); drops = plugin.getConfig().getBoolean("settings." + oGM + "-breaking-" + blockGM + "-blocks.block-drops"); if(deny){ specialType = AlertType.ILLEGAL; } } } } // Check regions if(!plugin.getPermissions().has(player, PermissionNodes.REGION_BREAK)){ ASRegion playerRegion = plugin.getRegionManager().getRegion(player.getLocation()); ASRegion blockRegion = plugin.getRegionManager().getRegion(block.getLocation()); if(playerRegion != blockRegion){ special = true; region = true; specialType = AlertType.ILLEGAL; } } // Handle event if(type == AlertType.ILLEGAL || specialType == AlertType.ILLEGAL){ event.setCancelled(true); + }else{ + plugin.getBlockManager().removeBlock(block); } // Handle drops if(drops != null){ if(drops){ if(event.isCancelled()){ + plugin.getBlockManager().removeBlock(block); block.breakNaturally(); } }else{ + plugin.getBlockManager().removeBlock(block); block.setType(Material.AIR); } } // Alert if(special){ if(region){ if(specialType == AlertType.ILLEGAL){ String specialMessage = ChatColor.YELLOW + player.getName() + ChatColor.WHITE + (specialType == AlertType.ILLEGAL ? " tried to break " : " broke ") + (specialType == AlertType.ILLEGAL ? ChatColor.RED : ChatColor.GREEN) + block.getType().name().replace("_", " ") + ChatColor.WHITE + " in a region."; String specialPlayerMessage = ChatColor.RED + "You cannot break blocks that are not in your region"; plugin.getAlerts().alert(specialMessage, player, specialPlayerMessage, specialType, AlertTrigger.BLOCK_BREAK); } }else{ String specialMessage = ChatColor.YELLOW + player.getName() + ChatColor.WHITE + (specialType == AlertType.ILLEGAL ? " tried to break the " + blockGM + " block " : " broke the " + blockGM + " block ") + (specialType == AlertType.ILLEGAL ? ChatColor.RED : ChatColor.GREEN) + block.getType().name().replace("_", " "); String specialPlayerMessage = plugin.getMessage("blocked-action." + blockGM + "-block-break"); plugin.getAlerts().alert(specialMessage, player, specialPlayerMessage, specialType, (blockGM.equalsIgnoreCase("creative") ? AlertTrigger.CREATIVE_BLOCK : AlertTrigger.SURVIVAL_BLOCK)); } }else{ String message = ChatColor.YELLOW + player.getName() + ChatColor.WHITE + (type == AlertType.ILLEGAL ? " tried to break " : " broke ") + (type == AlertType.ILLEGAL ? ChatColor.RED : ChatColor.GREEN) + block.getType().name().replace("_", " "); String playerMessage = plugin.getMessage("blocked-action.break-block"); plugin.getAlerts().alert(message, player, playerMessage, type, AlertTrigger.BLOCK_BREAK); } // Check for 'attached' blocks and internal inventories if(player.getGameMode() == GameMode.CREATIVE && !plugin.getPermissions().has(player, PermissionNodes.BREAK_ANYTHING)){ // Check inventories if(config.get(block.getWorld()).clearBlockInventoryOnBreak()){ if(block.getState() instanceof Chest){ Chest state = (Chest) block.getState(); state.getBlockInventory().clear(); }else if(block.getState() instanceof Jukebox){ Jukebox state = (Jukebox) block.getState(); state.setPlaying(null); }else if(block.getState() instanceof Furnace){ Furnace state = (Furnace) block.getState(); state.getInventory().clear(); } } // Check for attached blocks if(config.get(block.getWorld()).removeAttachedBlocksOnBreak()){ for(BlockFace face : BlockFace.values()){ Block rel = block.getRelative(face); if(ASUtils.isDroppedOnBreak(rel, block)){ + plugin.getBlockManager().removeBlock(rel); rel.setType(Material.AIR); } } } } } // ################# Block Place @EventHandler (priority = EventPriority.LOWEST, ignoreCancelled = true) public void onBlockPlace(BlockPlaceEvent event){ Player player = event.getPlayer(); Block block = event.getBlock(); AlertType type = AlertType.ILLEGAL; boolean region = false; // Sanity check if(block.getType() == Material.AIR){ return; } // Check if they should be blocked if(!plugin.isBlocked(player, PermissionNodes.ALLOW_BLOCK_PLACE, block.getWorld())){ type = AlertType.LEGAL; } if(!config.get(block.getWorld()).isBlocked(block.getType(), ListType.BLOCK_PLACE)){ type = AlertType.LEGAL; } if(!plugin.getPermissions().has(player, PermissionNodes.REGION_PLACE)){ ASRegion playerRegion = plugin.getRegionManager().getRegion(player.getLocation()); ASRegion blockRegion = plugin.getRegionManager().getRegion(block.getLocation()); if(playerRegion != blockRegion){ type = AlertType.ILLEGAL; region = true; } } // Handle event if(type == AlertType.ILLEGAL){ event.setCancelled(true); }else{ // Handle block place for tracker if(!plugin.getPermissions().has(player, PermissionNodes.FREE_PLACE)){ plugin.getBlockManager().addBlock(player.getGameMode(), block); } } // Alert if(region){ if(type == AlertType.ILLEGAL){ String message = ChatColor.YELLOW + player.getName() + ChatColor.WHITE + (type == AlertType.ILLEGAL ? " tried to place " : " placed ") + (type == AlertType.ILLEGAL ? ChatColor.RED : ChatColor.GREEN) + block.getType().name().replace("_", " ") + ChatColor.WHITE + " in a region."; String playerMessage = ChatColor.RED + "You cannot place blocks in another region!"; plugin.getAlerts().alert(message, player, playerMessage, type, AlertTrigger.BLOCK_PLACE); } }else{ String message = ChatColor.YELLOW + player.getName() + ChatColor.WHITE + (type == AlertType.ILLEGAL ? " tried to place " : " placed ") + (type == AlertType.ILLEGAL ? ChatColor.RED : ChatColor.GREEN) + block.getType().name().replace("_", " "); String playerMessage = plugin.getMessage("blocked-action.place-block"); plugin.getAlerts().alert(message, player, playerMessage, type, AlertTrigger.BLOCK_PLACE); } } // ################# Player Interact Block @EventHandler (priority = EventPriority.LOWEST, ignoreCancelled = true) public void onInteract(PlayerInteractEvent event){ Player player = event.getPlayer(); Block block = event.getClickedBlock(); Action action = event.getAction(); AlertType type = AlertType.LEGAL; String message = "no message"; String playerMessage = "no message"; AlertTrigger trigger = AlertTrigger.RIGHT_CLICK; // Check for AntiShare tool if(plugin.getPermissions().has(player, PermissionNodes.TOOL_USE) && player.getItemInHand() != null && (action == Action.RIGHT_CLICK_BLOCK || action == Action.LEFT_CLICK_BLOCK)){ if(player.getItemInHand().getType() == AntiShare.ANTISHARE_TOOL){ String blockname = block.getType().name().replaceAll("_", " ").toLowerCase(); String gamemode = (plugin.getBlockManager().getType(block) != null ? plugin.getBlockManager().getType(block).name() : "natural").toLowerCase(); ASUtils.sendToPlayer(player, "That " + ChatColor.YELLOW + blockname + ChatColor.WHITE + " is a " + ChatColor.YELLOW + gamemode + ChatColor.WHITE + " block."); // Cancel and stop the check event.setCancelled(true); return; } } // Right click list if(action == Action.RIGHT_CLICK_AIR || action == Action.RIGHT_CLICK_BLOCK){ // Check if they should be blocked if(config.get(block.getWorld()).isBlocked(block.getType(), ListType.RIGHT_CLICK)){ type = AlertType.ILLEGAL; } if(!plugin.isBlocked(player, PermissionNodes.ALLOW_RIGHT_CLICK, block.getWorld())){ type = AlertType.LEGAL; } // Set messages message = ChatColor.YELLOW + player.getName() + ChatColor.WHITE + (type == AlertType.ILLEGAL ? " tried to right click " : " right clicked ") + (type == AlertType.ILLEGAL ? ChatColor.RED : ChatColor.GREEN) + block.getType().name().replace("_", " "); playerMessage = plugin.getMessage("blocked-action.right-click"); } // If this event is triggered as legal from the right click, check use lists if(type == AlertType.LEGAL){ if(config.get(block.getWorld()).isBlocked(block.getType(), ListType.USE)){ type = AlertType.ILLEGAL; } // Check if they should be blocked if(!plugin.isBlocked(player, PermissionNodes.ALLOW_USE, block.getWorld())){ type = AlertType.LEGAL; } // Set messages message = ChatColor.YELLOW + player.getName() + ChatColor.WHITE + (type == AlertType.ILLEGAL ? " tried to right click " : " right clicked ") + (type == AlertType.ILLEGAL ? ChatColor.RED : ChatColor.GREEN) + block.getType().name().replace("_", " "); playerMessage = plugin.getMessage("blocked-action.right-click"); } // If the event is triggered as legal from the use lists, check the player's item in hand if(type == AlertType.LEGAL && action == Action.RIGHT_CLICK_BLOCK && player.getItemInHand() != null){ // Check if they should be blocked if(config.get(player.getWorld()).isBlocked(player.getItemInHand().getType(), ListType.USE)){ type = AlertType.ILLEGAL; } if(!plugin.isBlocked(player, PermissionNodes.ALLOW_USE, player.getWorld())){ type = AlertType.LEGAL; } // Set messages message = ChatColor.YELLOW + player.getName() + ChatColor.WHITE + (type == AlertType.ILLEGAL ? " tried to use " : " used ") + (type == AlertType.ILLEGAL ? ChatColor.RED : ChatColor.GREEN) + player.getItemInHand().getType().name().replace("_", " "); playerMessage = plugin.getMessage("blocked-action.use-item"); trigger = AlertTrigger.USE_ITEM; } // Handle event if(type == AlertType.ILLEGAL){ event.setCancelled(true); } // Alert (with sanity check) if(type != AlertType.LEGAL){ plugin.getAlerts().alert(message, player, playerMessage, type, trigger); } } // ################# Player Interact Entity @EventHandler (priority = EventPriority.LOWEST, ignoreCancelled = true) public void onInteractEntity(PlayerInteractEntityEvent event){ Player player = event.getPlayer(); AlertType type = AlertType.ILLEGAL; // Convert entity -> item ID Material item = Material.AIR; if(event.getRightClicked() instanceof StorageMinecart){ item = Material.STORAGE_MINECART; }else if(event.getRightClicked() instanceof PoweredMinecart){ item = Material.POWERED_MINECART; }else if(event.getRightClicked() instanceof Boat){ item = Material.BOAT; }else if(event.getRightClicked() instanceof Minecart){ item = Material.MINECART; }else if(event.getRightClicked() instanceof Painting){ item = Material.PAINTING; } // If the entity is not found, ignore the event if(item == Material.AIR){ return; } // Check if they should be blocked if(!plugin.isBlocked(player, PermissionNodes.ALLOW_RIGHT_CLICK, player.getWorld())){ type = AlertType.LEGAL; } if(!config.get(player.getWorld()).isBlocked(item, ListType.RIGHT_CLICK)){ type = AlertType.LEGAL; } // Handle event if(type == AlertType.ILLEGAL){ event.setCancelled(true); } // Alert (with sanity check) String message = ChatColor.YELLOW + player.getName() + ChatColor.WHITE + (type == AlertType.ILLEGAL ? " tried to right click " : " right clicked ") + (type == AlertType.ILLEGAL ? ChatColor.RED : ChatColor.GREEN) + item.name(); String playerMessage = plugin.getMessage("blocked-action.right-click"); plugin.getAlerts().alert(message, player, playerMessage, type, AlertTrigger.RIGHT_CLICK); } // ################# Cart Death Check @EventHandler (priority = EventPriority.LOWEST, ignoreCancelled = true) public void onCartDeath(VehicleDestroyEvent event){ Entity attacker = event.getAttacker(); Vehicle potentialCart = event.getVehicle(); // Sanity checks if(attacker == null || !(potentialCart instanceof StorageMinecart)){ return; } if(!(attacker instanceof Player)){ return; } // Setup Player player = (Player) attacker; StorageMinecart cart = (StorageMinecart) potentialCart; // Check internal inventories if(player.getGameMode() == GameMode.CREATIVE && !plugin.getPermissions().has(player, PermissionNodes.BREAK_ANYTHING)){ // Check inventories if(config.get(player.getWorld()).clearBlockInventoryOnBreak()){ cart.getInventory().clear(); } } } // ################# Egg Check @EventHandler (priority = EventPriority.LOWEST, ignoreCancelled = true) public void onEggThrow(PlayerEggThrowEvent event){ Player player = event.getPlayer(); AlertType type = AlertType.ILLEGAL; Material item = Material.EGG; // Check if they should be blocked if(!plugin.isBlocked(player, PermissionNodes.ALLOW_USE, player.getWorld())){ type = AlertType.LEGAL; } if(!config.get(player.getWorld()).isBlocked(item, ListType.USE)){ type = AlertType.LEGAL; } // Handle event if(type == AlertType.ILLEGAL){ event.setHatching(false); } // Alert (with sanity check) String message = ChatColor.YELLOW + player.getName() + ChatColor.WHITE + (type == AlertType.ILLEGAL ? " tried to use " : " used ") + (type == AlertType.ILLEGAL ? ChatColor.RED : ChatColor.GREEN) + item.name(); String playerMessage = plugin.getMessage("blocked-action.use-item"); plugin.getAlerts().alert(message, player, playerMessage, type, AlertTrigger.USE_ITEM); } // ################# Experience Bottle Check @EventHandler (priority = EventPriority.LOWEST, ignoreCancelled = true) public void onExpBottle(ExpBottleEvent event){ ThrownExpBottle bottle = event.getEntity(); LivingEntity shooter = bottle.getShooter(); AlertType type = AlertType.ILLEGAL; Material item = Material.EXP_BOTTLE; // Sanity Check if(!(shooter instanceof Player)){ return; } // Setup Player player = (Player) shooter; // Check if they should be blocked if(!plugin.isBlocked(player, PermissionNodes.ALLOW_USE, player.getWorld())){ type = AlertType.LEGAL; } if(!config.get(player.getWorld()).isBlocked(item, ListType.USE)){ type = AlertType.LEGAL; } // Handle event if(type == AlertType.ILLEGAL){ event.setExperience(0); event.setShowEffect(false); } // Alert (with sanity check) String message = ChatColor.YELLOW + player.getName() + ChatColor.WHITE + (type == AlertType.ILLEGAL ? " tried to use " : " used ") + (type == AlertType.ILLEGAL ? ChatColor.RED : ChatColor.GREEN) + item.name(); String playerMessage = plugin.getMessage("blocked-action.use-item"); if(type == AlertType.ILLEGAL){ // We don't want to show legal events because of spam plugin.getAlerts().alert(message, player, playerMessage, type, AlertTrigger.USE_ITEM); } } // ################# Drop Item @EventHandler (priority = EventPriority.LOWEST, ignoreCancelled = true) public void onDrop(PlayerDropItemEvent event){ Player player = event.getPlayer(); Item item = event.getItemDrop(); ItemStack itemStack = item.getItemStack(); AlertType type = AlertType.ILLEGAL; boolean region = false; // Check if they should be blocked if(!plugin.isBlocked(player, PermissionNodes.ALLOW_DROP, player.getWorld())){ type = AlertType.LEGAL; } if(!config.get(player.getWorld()).isBlocked(itemStack.getType(), ListType.DROP)){ type = AlertType.LEGAL; } // Region Check if(plugin.getRegionManager().getRegion(player.getLocation()) != plugin.getRegionManager().getRegion(item.getLocation()) && type == AlertType.LEGAL){ if(!plugin.getPermissions().has(player, PermissionNodes.REGION_THROW)){ type = AlertType.ILLEGAL; region = true; } } // Handle event if(type == AlertType.ILLEGAL){ event.setCancelled(true); } // Alert (with sanity check) String message = ChatColor.YELLOW + player.getName() + ChatColor.WHITE + (type == AlertType.ILLEGAL ? " tried to throw " : " threw ") + (type == AlertType.ILLEGAL ? ChatColor.RED : ChatColor.GREEN) + itemStack.getType().name().replace("_", " "); String playerMessage = plugin.getMessage("blocked-action.drop-item"); if(region){ message = ChatColor.YELLOW + player.getName() + ChatColor.WHITE + (type == AlertType.ILLEGAL ? " tried to throw " : " threw ") + (type == AlertType.ILLEGAL ? ChatColor.RED : ChatColor.GREEN) + itemStack.getType().name().replace("_", " ") + ChatColor.WHITE + " into a region."; playerMessage = ChatColor.RED + "You cannot throw items into another region!"; } plugin.getAlerts().alert(message, player, playerMessage, type, AlertTrigger.ITEM_DROP); } // ################# Pickup Item @EventHandler (priority = EventPriority.LOWEST, ignoreCancelled = true) public void onPickup(PlayerPickupItemEvent event){ Player player = event.getPlayer(); Item item = event.getItem(); ItemStack itemStack = item.getItemStack(); AlertType type = AlertType.ILLEGAL; boolean region = false; // Check if they should be blocked if(!plugin.isBlocked(player, PermissionNodes.ALLOW_PICKUP, player.getWorld())){ type = AlertType.LEGAL; } if(!config.get(player.getWorld()).isBlocked(itemStack.getType(), ListType.PICKUP)){ type = AlertType.LEGAL; } // Region Check if(plugin.getRegionManager().getRegion(player.getLocation()) != plugin.getRegionManager().getRegion(item.getLocation()) && type == AlertType.LEGAL){ if(!plugin.getPermissions().has(player, PermissionNodes.REGION_PICKUP)){ type = AlertType.ILLEGAL; region = true; } } // Handle event if(type == AlertType.ILLEGAL){ event.setCancelled(true); } // Alert (with sanity check) String message = ChatColor.YELLOW + player.getName() + ChatColor.WHITE + (type == AlertType.ILLEGAL ? " tried to pickup " : " picked up ") + (type == AlertType.ILLEGAL ? ChatColor.RED : ChatColor.GREEN) + itemStack.getType().name().replace("_", " "); String playerMessage = plugin.getMessage("blocked-action.pickup-item"); if(region){ message = ChatColor.YELLOW + player.getName() + ChatColor.WHITE + (type == AlertType.ILLEGAL ? " tried to pickup " : " picked up ") + (type == AlertType.ILLEGAL ? ChatColor.RED : ChatColor.GREEN) + itemStack.getType().name().replace("_", " ") + ChatColor.WHITE + " from a region."; playerMessage = ChatColor.RED + "You cannot pickup items from another region!"; } plugin.getAlerts().alert(message, player, playerMessage, type, AlertTrigger.ITEM_PICKUP); } // ################# Player Death @EventHandler (priority = EventPriority.LOWEST, ignoreCancelled = true) public void onDeath(PlayerDeathEvent event){ Player player = event.getEntity(); List<ItemStack> drops = event.getDrops(); AlertType type = AlertType.ILLEGAL; int illegalItems = 0; // Check if they should be blocked if(!plugin.isBlocked(player, PermissionNodes.ALLOW_DEATH, player.getWorld())){ type = AlertType.LEGAL; } // Handle event if(type == AlertType.ILLEGAL){ List<ItemStack> remove = new ArrayList<ItemStack>(); for(ItemStack item : drops){ if(config.get(player.getWorld()).isBlocked(item.getType(), ListType.DEATH)){ illegalItems++; remove.add(item); } } // Remove items for(ItemStack item : remove){ drops.remove(item); } } // Determine new status if(illegalItems == 0){ type = AlertType.LEGAL; } // Alert String message = ChatColor.YELLOW + player.getName() + ChatColor.WHITE + " died with " + (type == AlertType.ILLEGAL ? ChatColor.RED : ChatColor.GREEN) + illegalItems + " illegal item(s)."; String playerMessage = plugin.getMessage("blocked-action.die-with-item"); plugin.getAlerts().alert(message, player, playerMessage, type, AlertTrigger.PLAYER_DEATH); } // ################# Player Command @EventHandler (priority = EventPriority.LOWEST, ignoreCancelled = true) public void onCommand(PlayerCommandPreprocessEvent event){ Player player = event.getPlayer(); String command = event.getMessage().toLowerCase(); AlertType type = AlertType.ILLEGAL; // Game Mode command GameModeCommand.onPlayerCommand(event); if(event.isCancelled()){ return; } // Check if they should be blocked if(!plugin.isBlocked(player, PermissionNodes.ALLOW_PICKUP, player.getWorld())){ type = AlertType.LEGAL; } if(!config.get(player.getWorld()).isBlocked(command, ListType.COMMAND)){ type = AlertType.LEGAL; } // Handle event if(type == AlertType.ILLEGAL){ event.setCancelled(true); } // Alert (with sanity check) String message = ChatColor.YELLOW + player.getName() + ChatColor.WHITE + (type == AlertType.ILLEGAL ? " tried to use the command " : " used the command ") + (type == AlertType.ILLEGAL ? ChatColor.RED : ChatColor.GREEN) + command; String playerMessage = plugin.getMessage("blocked-action.command"); plugin.getAlerts().alert(message, player, playerMessage, type, AlertTrigger.COMMAND); } // ################# Player Move @EventHandler (ignoreCancelled = true) public void onMove(PlayerMoveEvent event){ Player player = event.getPlayer(); ASRegion currentRegion = plugin.getRegionManager().getRegion(event.getFrom()); ASRegion toRegion = plugin.getRegionManager().getRegion(event.getTo()); // Check world split config.get(player.getWorld()).checkSplit(player); // Check regions if(currentRegion != toRegion){ if(currentRegion != null){ currentRegion.alertExit(player); } if(toRegion != null){ toRegion.alertEntry(player); } } } // ################# Player Game Mode Change @EventHandler (priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onGameModeChange(PlayerGameModeChangeEvent event){ Player player = event.getPlayer(); GameMode from = player.getGameMode(); GameMode to = event.getNewGameMode(); boolean ignore = true; boolean checkRegion = true; // Check to see if we should even bother if(!plugin.getConfig().getBoolean("handled-actions.gamemode-inventories")){ return; } // Tag check if(player.hasMetadata("antishare-regionleave")){ player.removeMetadata("antishare-regionleave", plugin); checkRegion = false; } // Region Check if(!plugin.getPermissions().has(player, PermissionNodes.REGION_ROAM) && checkRegion){ ASRegion region = plugin.getRegionManager().getRegion(player.getLocation()); if(region != null){ ASUtils.sendToPlayer(player, ChatColor.RED + "You are in a region and therefore cannot change Game Mode"); event.setCancelled(true); return; } } // Check temp if(plugin.getInventoryManager().isInTemporary(player)){ plugin.getInventoryManager().removeFromTemporary(player); } if(!plugin.getPermissions().has(player, PermissionNodes.NO_SWAP)){ // Save from switch (from){ case CREATIVE: plugin.getInventoryManager().saveCreativeInventory(player, player.getWorld()); break; case SURVIVAL: plugin.getInventoryManager().saveSurvivalInventory(player, player.getWorld()); break; } // Set to switch (to){ case CREATIVE: plugin.getInventoryManager().getCreativeInventory(player, player.getWorld()).setTo(player); break; case SURVIVAL: plugin.getInventoryManager().getSurvivalInventory(player, player.getWorld()).setTo(player); break; } // For alerts ignore = false; } // Alerts String message = ChatColor.YELLOW + player.getName() + ChatColor.WHITE + " changed to Game Mode " + ChatColor.YELLOW + to.name(); String playerMessage = ignore ? "no message" : "Your inventory has been changed to " + ChatColor.YELLOW + to.name(); plugin.getAlerts().alert(message, player, playerMessage, AlertType.GENERAL, AlertTrigger.GENERAL); } // ################# Player Combat @EventHandler (priority = EventPriority.LOWEST, ignoreCancelled = true) public void onCombat(EntityDamageByEntityEvent event){ DamageCause cause = event.getCause(); Entity attacker = event.getDamager(); Entity target = event.getEntity(); AlertType type = AlertType.ILLEGAL; boolean playerCombat = false; Player playerAttacker = null; // Check case switch (cause){ case ENTITY_ATTACK: // attacker = entity if(attacker instanceof Player){ playerAttacker = (Player) attacker; }else{ return; } break; case PROJECTILE: // attacker = Projectile Projectile projectile = (Projectile) attacker; LivingEntity shooter = projectile.getShooter(); if(shooter instanceof Player){ playerAttacker = (Player) shooter; }else{ return; } break; default: return; } // Determine if we are hitting a mob or not, and whether it is legal if(target instanceof Player){ // target = Player playerCombat = true; if(!plugin.isBlocked(playerAttacker, PermissionNodes.ALLOW_COMBAT_PLAYERS, playerAttacker.getWorld())){ type = AlertType.LEGAL; } }else{ // target = other entity if(!plugin.isBlocked(playerAttacker, PermissionNodes.ALLOW_COMBAT_MOBS, playerAttacker.getWorld())){ type = AlertType.LEGAL; } } // Check if we need to continue based on settings if(playerCombat){ if(!plugin.getConfig().getBoolean("blocked-actions.combat-against-players")){ return; } }else{ if(!plugin.getConfig().getBoolean("blocked-actions.combat-against-mobs")){ return; } } // Handle event if(type == AlertType.ILLEGAL){ event.setCancelled(true); } // Alert String message = "no message"; String playerMessage = "no message"; AlertTrigger trigger = AlertTrigger.HIT_MOB; if(playerCombat){ String playerName = ((Player) target).getName(); message = ChatColor.YELLOW + playerAttacker.getName() + ChatColor.WHITE + (type == AlertType.ILLEGAL ? " tried to hit " + ChatColor.RED : " hit " + ChatColor.GREEN) + playerName; playerMessage = plugin.getMessage("blocked-action.hit-player"); trigger = AlertTrigger.HIT_PLAYER; }else{ String targetName = target.getClass().getName().replace("Craft", "").replace("org.bukkit.craftbukkit.entity.", "").trim(); message = ChatColor.YELLOW + playerAttacker.getName() + ChatColor.WHITE + (type == AlertType.ILLEGAL ? " tried to hit a " + ChatColor.RED : " hit a " + ChatColor.GREEN) + targetName; playerMessage = plugin.getMessage("blocked-action.hit-mob"); } plugin.getAlerts().alert(message, playerAttacker, playerMessage, type, trigger); } // ################# Entity Target @EventHandler (priority = EventPriority.LOWEST, ignoreCancelled = true) public void onEntityTarget(EntityTargetEvent event){ Entity target = event.getTarget(); Player playerTarget = null; AlertType type = AlertType.ILLEGAL; // Check target if(target instanceof Player){ playerTarget = (Player) target; }else{ return; } // Check permissions if(!plugin.isBlocked(playerTarget, PermissionNodes.ALLOW_COMBAT_MOBS, playerTarget.getWorld())){ type = AlertType.LEGAL; } // Handle event if(type == AlertType.ILLEGAL){ event.setCancelled(true); } } // ################# Piston Move (Extend) @EventHandler (priority = EventPriority.LOWEST, ignoreCancelled = true) public void onPistonExtend(BlockPistonExtendEvent event){ for(Block block : event.getBlocks()){ // Check for block type GameMode type = plugin.getBlockManager().getType(block); // Sanity if(type == null){ continue; } // Setup Location oldLocation = block.getLocation(); Location newLocation = block.getRelative(event.getDirection()).getLocation(); // Move plugin.getBlockManager().moveBlock(oldLocation, newLocation); } } // ################# Piston Move (Retract) @EventHandler (priority = EventPriority.LOWEST, ignoreCancelled = true) public void onPistonRetract(BlockPistonRetractEvent event){ if(!event.isSticky()){ // Only handle moving blocks return; } Block block = event.getBlock().getRelative(event.getDirection()).getRelative(event.getDirection()); // Check for block type GameMode type = plugin.getBlockManager().getType(block); // Sanity if(type == null){ return; } // Setup Location oldLocation = block.getLocation(); Location newLocation = block.getRelative(event.getDirection().getOppositeFace()).getLocation(); // Move plugin.getBlockManager().moveBlock(oldLocation, newLocation); } // ################# Player Join @EventHandler (ignoreCancelled = true) public void onJoin(PlayerJoinEvent event){ Player player = event.getPlayer(); // Tell the inventory manager to prepare this player plugin.getInventoryManager().loadPlayer(player); // Check region ASRegion region = plugin.getRegionManager().getRegion(player.getLocation()); if(region != null){ region.alertSilentEntry(player); // Sets inventory and Game Mode // This must be done because when the inventory manager releases // a player it resets the inventory to "non-temp" } } // ################# Player Quit @EventHandler (ignoreCancelled = true) public void onQuit(PlayerQuitEvent event){ Player player = event.getPlayer(); // Tell the inventory manager to release this player plugin.getInventoryManager().releasePlayer(player); } // ################# Player Kicked @EventHandler (ignoreCancelled = true) public void onKick(PlayerKickEvent event){ Player player = event.getPlayer(); // Tell the inventory manager to release this player plugin.getInventoryManager().releasePlayer(player); } // ################# Player World Change @EventHandler (priority = EventPriority.LOWEST, ignoreCancelled = true) public void onWorldChange(PlayerChangedWorldEvent event){ Player player = event.getPlayer(); World to = player.getWorld(); World from = event.getFrom(); boolean ignore = true; // Check to see if we should even bother checking if(!plugin.getConfig().getBoolean("handled-actions.world-transfers")){ return; } // Check temp if(plugin.getInventoryManager().isInTemporary(player)){ plugin.getInventoryManager().removeFromTemporary(player); } // Inventory check if(!plugin.getPermissions().has(player, PermissionNodes.NO_SWAP)){ // Save from switch (player.getGameMode()){ case CREATIVE: plugin.getInventoryManager().saveCreativeInventory(player, from); break; case SURVIVAL: plugin.getInventoryManager().saveSurvivalInventory(player, from); break; } // Set to switch (player.getGameMode()){ case CREATIVE: plugin.getInventoryManager().getCreativeInventory(player, to).setTo(player); break; case SURVIVAL: plugin.getInventoryManager().getSurvivalInventory(player, to).setTo(player); break; } // For alerts ignore = false; } // Alerts String message = ChatColor.YELLOW + player.getName() + ChatColor.WHITE + " changed to world " + ChatColor.YELLOW + to.getName(); String playerMessage = ignore ? "no message" : "Your inventory has been changed to " + ChatColor.YELLOW + to.getName(); plugin.getAlerts().alert(message, player, playerMessage, AlertType.GENERAL, AlertTrigger.GENERAL); } }
false
true
public void onBlockBreak(BlockBreakEvent event){ Player player = event.getPlayer(); Block block = event.getBlock(); AlertType type = AlertType.ILLEGAL; boolean special = false; boolean region = false; Boolean drops = null; AlertType specialType = AlertType.LEGAL; String blockGM = "Unknown"; // Check if they should be blocked if(!plugin.isBlocked(player, PermissionNodes.ALLOW_BLOCK_BREAK, block.getWorld())){ type = AlertType.LEGAL; } if(!config.get(block.getWorld()).isBlocked(block.getType(), ListType.BLOCK_BREAK)){ type = AlertType.LEGAL; } // Check creative/survival blocks if(!plugin.getPermissions().has(player, PermissionNodes.FREE_PLACE)){ GameMode blockGamemode = plugin.getBlockManager().getType(block); if(blockGamemode != null){ special = true; blockGM = blockGamemode.name().toLowerCase(); String oGM = blockGM.equalsIgnoreCase("creative") ? "survival" : "creative"; if(player.getGameMode() != blockGamemode){ boolean deny = plugin.getConfig().getBoolean("settings." + oGM + "-breaking-" + blockGM + "-blocks.deny"); drops = plugin.getConfig().getBoolean("settings." + oGM + "-breaking-" + blockGM + "-blocks.block-drops"); if(deny){ specialType = AlertType.ILLEGAL; } } } } // Check regions if(!plugin.getPermissions().has(player, PermissionNodes.REGION_BREAK)){ ASRegion playerRegion = plugin.getRegionManager().getRegion(player.getLocation()); ASRegion blockRegion = plugin.getRegionManager().getRegion(block.getLocation()); if(playerRegion != blockRegion){ special = true; region = true; specialType = AlertType.ILLEGAL; } } // Handle event if(type == AlertType.ILLEGAL || specialType == AlertType.ILLEGAL){ event.setCancelled(true); } // Handle drops if(drops != null){ if(drops){ if(event.isCancelled()){ block.breakNaturally(); } }else{ block.setType(Material.AIR); } } // Alert if(special){ if(region){ if(specialType == AlertType.ILLEGAL){ String specialMessage = ChatColor.YELLOW + player.getName() + ChatColor.WHITE + (specialType == AlertType.ILLEGAL ? " tried to break " : " broke ") + (specialType == AlertType.ILLEGAL ? ChatColor.RED : ChatColor.GREEN) + block.getType().name().replace("_", " ") + ChatColor.WHITE + " in a region."; String specialPlayerMessage = ChatColor.RED + "You cannot break blocks that are not in your region"; plugin.getAlerts().alert(specialMessage, player, specialPlayerMessage, specialType, AlertTrigger.BLOCK_BREAK); } }else{ String specialMessage = ChatColor.YELLOW + player.getName() + ChatColor.WHITE + (specialType == AlertType.ILLEGAL ? " tried to break the " + blockGM + " block " : " broke the " + blockGM + " block ") + (specialType == AlertType.ILLEGAL ? ChatColor.RED : ChatColor.GREEN) + block.getType().name().replace("_", " "); String specialPlayerMessage = plugin.getMessage("blocked-action." + blockGM + "-block-break"); plugin.getAlerts().alert(specialMessage, player, specialPlayerMessage, specialType, (blockGM.equalsIgnoreCase("creative") ? AlertTrigger.CREATIVE_BLOCK : AlertTrigger.SURVIVAL_BLOCK)); } }else{ String message = ChatColor.YELLOW + player.getName() + ChatColor.WHITE + (type == AlertType.ILLEGAL ? " tried to break " : " broke ") + (type == AlertType.ILLEGAL ? ChatColor.RED : ChatColor.GREEN) + block.getType().name().replace("_", " "); String playerMessage = plugin.getMessage("blocked-action.break-block"); plugin.getAlerts().alert(message, player, playerMessage, type, AlertTrigger.BLOCK_BREAK); } // Check for 'attached' blocks and internal inventories if(player.getGameMode() == GameMode.CREATIVE && !plugin.getPermissions().has(player, PermissionNodes.BREAK_ANYTHING)){ // Check inventories if(config.get(block.getWorld()).clearBlockInventoryOnBreak()){ if(block.getState() instanceof Chest){ Chest state = (Chest) block.getState(); state.getBlockInventory().clear(); }else if(block.getState() instanceof Jukebox){ Jukebox state = (Jukebox) block.getState(); state.setPlaying(null); }else if(block.getState() instanceof Furnace){ Furnace state = (Furnace) block.getState(); state.getInventory().clear(); } } // Check for attached blocks if(config.get(block.getWorld()).removeAttachedBlocksOnBreak()){ for(BlockFace face : BlockFace.values()){ Block rel = block.getRelative(face); if(ASUtils.isDroppedOnBreak(rel, block)){ rel.setType(Material.AIR); } } } } }
public void onBlockBreak(BlockBreakEvent event){ Player player = event.getPlayer(); Block block = event.getBlock(); AlertType type = AlertType.ILLEGAL; boolean special = false; boolean region = false; Boolean drops = null; AlertType specialType = AlertType.LEGAL; String blockGM = "Unknown"; // Check if they should be blocked if(!plugin.isBlocked(player, PermissionNodes.ALLOW_BLOCK_BREAK, block.getWorld())){ type = AlertType.LEGAL; } if(!config.get(block.getWorld()).isBlocked(block.getType(), ListType.BLOCK_BREAK)){ type = AlertType.LEGAL; } // Check creative/survival blocks if(!plugin.getPermissions().has(player, PermissionNodes.FREE_PLACE)){ GameMode blockGamemode = plugin.getBlockManager().getType(block); if(blockGamemode != null){ special = true; blockGM = blockGamemode.name().toLowerCase(); String oGM = blockGM.equalsIgnoreCase("creative") ? "survival" : "creative"; if(player.getGameMode() != blockGamemode){ boolean deny = plugin.getConfig().getBoolean("settings." + oGM + "-breaking-" + blockGM + "-blocks.deny"); drops = plugin.getConfig().getBoolean("settings." + oGM + "-breaking-" + blockGM + "-blocks.block-drops"); if(deny){ specialType = AlertType.ILLEGAL; } } } } // Check regions if(!plugin.getPermissions().has(player, PermissionNodes.REGION_BREAK)){ ASRegion playerRegion = plugin.getRegionManager().getRegion(player.getLocation()); ASRegion blockRegion = plugin.getRegionManager().getRegion(block.getLocation()); if(playerRegion != blockRegion){ special = true; region = true; specialType = AlertType.ILLEGAL; } } // Handle event if(type == AlertType.ILLEGAL || specialType == AlertType.ILLEGAL){ event.setCancelled(true); }else{ plugin.getBlockManager().removeBlock(block); } // Handle drops if(drops != null){ if(drops){ if(event.isCancelled()){ plugin.getBlockManager().removeBlock(block); block.breakNaturally(); } }else{ plugin.getBlockManager().removeBlock(block); block.setType(Material.AIR); } } // Alert if(special){ if(region){ if(specialType == AlertType.ILLEGAL){ String specialMessage = ChatColor.YELLOW + player.getName() + ChatColor.WHITE + (specialType == AlertType.ILLEGAL ? " tried to break " : " broke ") + (specialType == AlertType.ILLEGAL ? ChatColor.RED : ChatColor.GREEN) + block.getType().name().replace("_", " ") + ChatColor.WHITE + " in a region."; String specialPlayerMessage = ChatColor.RED + "You cannot break blocks that are not in your region"; plugin.getAlerts().alert(specialMessage, player, specialPlayerMessage, specialType, AlertTrigger.BLOCK_BREAK); } }else{ String specialMessage = ChatColor.YELLOW + player.getName() + ChatColor.WHITE + (specialType == AlertType.ILLEGAL ? " tried to break the " + blockGM + " block " : " broke the " + blockGM + " block ") + (specialType == AlertType.ILLEGAL ? ChatColor.RED : ChatColor.GREEN) + block.getType().name().replace("_", " "); String specialPlayerMessage = plugin.getMessage("blocked-action." + blockGM + "-block-break"); plugin.getAlerts().alert(specialMessage, player, specialPlayerMessage, specialType, (blockGM.equalsIgnoreCase("creative") ? AlertTrigger.CREATIVE_BLOCK : AlertTrigger.SURVIVAL_BLOCK)); } }else{ String message = ChatColor.YELLOW + player.getName() + ChatColor.WHITE + (type == AlertType.ILLEGAL ? " tried to break " : " broke ") + (type == AlertType.ILLEGAL ? ChatColor.RED : ChatColor.GREEN) + block.getType().name().replace("_", " "); String playerMessage = plugin.getMessage("blocked-action.break-block"); plugin.getAlerts().alert(message, player, playerMessage, type, AlertTrigger.BLOCK_BREAK); } // Check for 'attached' blocks and internal inventories if(player.getGameMode() == GameMode.CREATIVE && !plugin.getPermissions().has(player, PermissionNodes.BREAK_ANYTHING)){ // Check inventories if(config.get(block.getWorld()).clearBlockInventoryOnBreak()){ if(block.getState() instanceof Chest){ Chest state = (Chest) block.getState(); state.getBlockInventory().clear(); }else if(block.getState() instanceof Jukebox){ Jukebox state = (Jukebox) block.getState(); state.setPlaying(null); }else if(block.getState() instanceof Furnace){ Furnace state = (Furnace) block.getState(); state.getInventory().clear(); } } // Check for attached blocks if(config.get(block.getWorld()).removeAttachedBlocksOnBreak()){ for(BlockFace face : BlockFace.values()){ Block rel = block.getRelative(face); if(ASUtils.isDroppedOnBreak(rel, block)){ plugin.getBlockManager().removeBlock(rel); rel.setType(Material.AIR); } } } } }
diff --git a/software/caTissue/modules/core/src/main/java/edu/wustl/catissuecore/action/DynamicEventAction.java b/software/caTissue/modules/core/src/main/java/edu/wustl/catissuecore/action/DynamicEventAction.java index 3864ccf3c..f33950263 100644 --- a/software/caTissue/modules/core/src/main/java/edu/wustl/catissuecore/action/DynamicEventAction.java +++ b/software/caTissue/modules/core/src/main/java/edu/wustl/catissuecore/action/DynamicEventAction.java @@ -1,392 +1,392 @@ package edu.wustl.catissuecore.action; import java.util.Calendar; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import edu.wustl.cab2b.common.util.Utility; import edu.wustl.catissuecore.actionForm.DynamicEventForm; import edu.wustl.catissuecore.bizlogic.CatissueDefaultBizLogic; import edu.wustl.catissuecore.bizlogic.UserBizLogic; import edu.wustl.catissuecore.domain.Specimen; import edu.wustl.catissuecore.domain.processingprocedure.Action; import edu.wustl.catissuecore.domain.processingprocedure.ActionApplication; import edu.wustl.catissuecore.domain.processingprocedure.DefaultAction; import edu.wustl.catissuecore.processor.SPPEventProcessor; import edu.wustl.catissuecore.util.global.AppUtility; import edu.wustl.catissuecore.util.global.Constants; import edu.wustl.catissuecore.util.global.SpecimenEventsUtility; import edu.wustl.common.action.BaseAction; import edu.wustl.common.beans.SessionDataBean; import edu.wustl.common.bizlogic.IBizLogic; import edu.wustl.common.factory.AbstractFactoryConfig; import edu.wustl.common.factory.IFactory; import edu.wustl.common.util.global.CommonServiceLocator; import edu.wustl.common.util.global.CommonUtilities; public class DynamicEventAction extends BaseAction { /** * Overrides the executeSecureAction method of SecureAction class. * @param mapping * object of ActionMapping * @param form * object of ActionForm * @param request * object of HttpServletRequest * @param response : HttpServletResponse * @throws Exception * generic exception * @return ActionForward : ActionForward */ @Override protected ActionForward executeAction(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { if (request.getParameter(Constants.REFRESH_EVENT_GRID) != null) { request.setAttribute(Constants.REFRESH_EVENT_GRID, request .getParameter(Constants.REFRESH_EVENT_GRID)); } //this.setCommonRequestParameters(request); DynamicEventForm dynamicEventForm = (DynamicEventForm) form; resetFormParameters(request, dynamicEventForm); // if operation is add if (dynamicEventForm.isAddOperation()) { if (dynamicEventForm.getUserId() == 0) { final SessionDataBean sessionData = this.getSessionData(request); if (sessionData != null && sessionData.getUserId() != null) { final long userId = sessionData.getUserId().longValue(); dynamicEventForm.setUserId(userId); } } // set the current Date and Time for the event. final Calendar cal = Calendar.getInstance(); if (dynamicEventForm.getDateOfEvent() == null) { dynamicEventForm.setDateOfEvent(CommonUtilities.parseDateToString(cal.getTime(), CommonServiceLocator.getInstance().getDatePattern())); } if (dynamicEventForm.getTimeInHours() == null) { dynamicEventForm.setTimeInHours(Integer.toString(cal.get(Calendar.HOUR_OF_DAY))); } if (dynamicEventForm.getTimeInMinutes() == null) { dynamicEventForm.setTimeInMinutes(Integer.toString(cal.get(Calendar.MINUTE))); } } else { String specimenId = (String) request.getAttribute(Constants.SPECIMEN_ID); if (specimenId == null) { request.setAttribute(Constants.SPECIMEN_ID, specimenId); } } String reasonDeviation = ""; reasonDeviation = dynamicEventForm.getReasonDeviation(); if (reasonDeviation == null) { reasonDeviation = ""; } String currentEventParametersDate = ""; currentEventParametersDate = dynamicEventForm.getDateOfEvent(); if (currentEventParametersDate == null) { currentEventParametersDate = ""; } final Integer dynamicEventParametersYear = new Integer(AppUtility .getYear(currentEventParametersDate)); final Integer dynamicEventParametersMonth = new Integer(AppUtility .getMonth(currentEventParametersDate)); final Integer dynamicEventParametersDay = new Integer(AppUtility .getDay(currentEventParametersDate)); request.setAttribute("minutesList", Constants.MINUTES_ARRAY); // Sets the hourList attribute to be used in the Add/Edit // FrozenEventParameters Page. request.setAttribute("hourList", Constants.HOUR_ARRAY); request.setAttribute("dynamicEventParametersYear", dynamicEventParametersYear); request.setAttribute("dynamicEventParametersDay", dynamicEventParametersDay); request.setAttribute("dynamicEventParametersMonth", dynamicEventParametersMonth); request.setAttribute("formName", Constants.DYNAMIC_EVENT_ACTION); request.setAttribute("addForJSP", Constants.ADD); request.setAttribute("editForJSP", Constants.EDIT); request.setAttribute("reasonDeviation", reasonDeviation); request.setAttribute("userListforJSP", Constants.USERLIST); request.setAttribute("currentEventParametersDate", currentEventParametersDate); request.setAttribute(Constants.PAGE_OF, "pageOfDynamicEvent"); request.setAttribute(Constants.SPECIMEN_ID, request.getSession().getAttribute( Constants.SPECIMEN_ID)); //request.setAttribute(Constants.SPECIMEN_ID, request.getAttribute(Constants.SPECIMEN_ID)); //request.setAttribute(Constants.PAGE_OF, request.getParameter(Constants.PAGE_OF)); //request.setAttribute("changeAction", Constants.CELL_SPECIMEN_REVIEW_PARAMETERS_ADD_ACTION); final String operation = request.getParameter(Constants.OPERATION); final IFactory factory = AbstractFactoryConfig.getInstance().getBizLogicFactory(); final UserBizLogic userBizLogic = (UserBizLogic) factory .getBizLogic(Constants.USER_FORM_ID); final Collection userCollection = userBizLogic.getUsers(operation); request.setAttribute(Constants.USERLIST, userCollection); HashMap dynamicEventMap = (HashMap) request.getSession().getAttribute("dynamicEventMap"); String iframeURL=""; long recordIdentifier=0; Long eventId=null; if(dynamicEventForm.getOperation().equals(Constants.ADD)) { String eventName = request.getParameter("eventName"); if(eventName == null) { eventName = (String)request.getSession().getAttribute("eventName"); } request.getSession().setAttribute("eventName", eventName); dynamicEventForm.setEventName(eventName); eventId=(Long) dynamicEventMap.get(eventName); - String query="Select IS_CACORE_GENERATED from dyextn_entity_group where IDENTIFIER = (select ENTITY_GROUP_ID from dyextn_container where IDENTIFIER="+eventId+")"; + /*String query="Select IS_CACORE_GENERATED from dyextn_entity_group where IDENTIFIER = (select ENTITY_GROUP_ID from dyextn_container where IDENTIFIER="+eventId+")"; List result=AppUtility.executeSQLQuery(query); Boolean isCaCoreGenerated=Boolean.parseBoolean(((List) result.get(0)).get(0).toString()); if(!isCaCoreGenerated) { request.setAttribute("isCaCoreGenerated", true); - } + }*/ if (Boolean.parseBoolean(request.getParameter("showDefaultValues"))) { IBizLogic defaultBizLogic = new CatissueDefaultBizLogic(); List<Action> actionList = defaultBizLogic.retrieve(Action.class.getName(), Constants.ID, request.getParameter("formContextId")); if (actionList != null && !actionList.isEmpty()) { Action action = (Action) actionList.get(0); if (action.getApplicationDefaultValue() != null) { recordIdentifier = SpecimenEventsUtility.getRecordIdentifier(action .getApplicationDefaultValue().getId(), action.getContainerId()); } } } else { IBizLogic defaultBizLogic = new CatissueDefaultBizLogic(); List<DefaultAction> actionList = defaultBizLogic.retrieve(DefaultAction.class .getName(), Constants.CONTAINER_ID, eventId); DefaultAction action =null; if (actionList != null && !actionList.isEmpty()) { action = (DefaultAction) actionList.get(0); } else { action=new DefaultAction(); action.setContainerId(eventId); defaultBizLogic.insert(action); } request.setAttribute("formContextId",action.getId()); } if(eventName != null) { request.setAttribute("formDisplayName", Utility.getFormattedString(eventName)); } if(eventId != null) { request.getSession().setAttribute("OverrideCaption", "_" + eventId.toString()); iframeURL = "/catissuecore/LoadDataEntryFormAction.do?dataEntryOperation=insertParentData&useApplicationStylesheet=true&showInDiv=false&overrideCSS=true&overrideScroll=true"+(Boolean.parseBoolean(request.getParameter(Constants.CONTAINS_ERROR))?"&containerId=":"&containerIdentifier=") + eventId.toString() + "&OverrideCaption=" + "_" + eventId.toString(); if (recordIdentifier != 0) { iframeURL = iframeURL + "&recordIdentifier=" + recordIdentifier; } } } else { String actionApplicationId = request.getParameter("id"); if(actionApplicationId ==null) { actionApplicationId = (String) request.getAttribute("id"); } if(Boolean.parseBoolean(request.getParameter(Constants.CONTAINS_ERROR)) && request.getSession().getAttribute("dynamicEventsForm") != null) { dynamicEventForm = (DynamicEventForm) request.getSession().getAttribute("dynamicEventsForm"); actionApplicationId = String.valueOf(dynamicEventForm.getId()); } recordIdentifier = SpecimenEventsUtility.getRecordIdentifier(dynamicEventForm .getRecordEntry(), dynamicEventForm.getContId()); Long containerId = dynamicEventForm.getContId(); IBizLogic defaultBizLogic = new CatissueDefaultBizLogic(); String specimenId = (String) request.getAttribute(Constants.SPECIMEN_ID); boolean isDefaultAction = true; if(specimenId!=null && !"".equals(specimenId)) { List<Specimen> specimentList = defaultBizLogic.retrieve( Specimen.class.getName(), Constants.ID, specimenId); if (specimentList != null && !specimentList.isEmpty()) { Specimen specimen = (Specimen) specimentList.get(0); if(specimen.getProcessingSPPApplication() != null) { for(ActionApplication actionApplication : new SPPEventProcessor().getFilteredActionApplication(specimen.getProcessingSPPApplication().getSppActionApplicationCollection())) { if(actionApplication.getId().toString().equals(actionApplicationId)) { for(Action action : specimen.getSpecimenRequirement().getProcessingSPP().getActionCollection()) { if(action.getContainerId().equals(containerId)) { request.setAttribute("formContextId", action.getId()); break; } } isDefaultAction = false; break; } } } } } if(isDefaultAction) { List<DefaultAction> actionList = defaultBizLogic.retrieve( DefaultAction.class.getName(), Constants.CONTAINER_ID, dynamicEventForm .getContId()); if (actionList != null && !actionList.isEmpty()) { DefaultAction action = (DefaultAction) actionList.get(0); request.setAttribute("formContextId", action.getId()); } } dynamicEventForm.setRecordIdentifier(recordIdentifier); iframeURL = "/catissuecore/LoadDataEntryFormAction.do?dataEntryOperation=edit&useApplicationStylesheet=true&showInDiv=false"+(Boolean.parseBoolean(request.getParameter(Constants.CONTAINS_ERROR))?"&containerId=":"&containerIdentifier=") + dynamicEventForm.getContId() + "&recordIdentifier=" + recordIdentifier + "&OverrideCaption=" + "_" + dynamicEventForm.getContId(); List contList = AppUtility .executeSQLQuery("select caption from dyextn_container where identifier=" + dynamicEventForm.getContId()); String eventName = (String) ((List) contList.get(0)).get(0); request.setAttribute("formDisplayName", Utility.getFormattedString(eventName)); } if (request.getSession().getAttribute("specimenId") == null) { request.getSession().setAttribute("specimenId", request.getParameter("specimenId")); } request.setAttribute("recordIdentifier", recordIdentifier); request.getSession().setAttribute("recordIdentifier", recordIdentifier); request.getSession().setAttribute("containerId", dynamicEventForm.getContId()); request.getSession().setAttribute("mandatory_Message", "false"); String formContxtId = getFormContextFromRequest(request); if(!"".equals(iframeURL)) { iframeURL = iframeURL + "&FormContextIdentifier=" + formContxtId; } populateStaticAttributes(request, dynamicEventForm); request.setAttribute("iframeURL", iframeURL+"&showCalculateDefaultValue=false"); return mapping.findForward((String) request.getAttribute(Constants.PAGE_OF)); } /** * @param request * @param dynamicEventForm */ private void resetFormParameters(HttpServletRequest request, DynamicEventForm dynamicEventForm) { if("edit".equals(request.getParameter(Constants.OPERATION)) && request.getSession().getAttribute(Constants.DYN_EVENT_FORM)!= null) { DynamicEventForm originalForm = (DynamicEventForm) request.getSession().getAttribute(Constants.DYN_EVENT_FORM); dynamicEventForm.setContId(originalForm.getContId()); dynamicEventForm.setReasonDeviation(originalForm.getReasonDeviation()); dynamicEventForm.setRecordEntry(originalForm.getRecordEntry()); dynamicEventForm.setRecordIdentifier(originalForm.getRecordIdentifier()); dynamicEventForm.setUserId(originalForm.getUserId()); dynamicEventForm.setTimeInHours(originalForm.getTimeInHours()); dynamicEventForm.setTimeInMinutes(originalForm.getTimeInMinutes()); dynamicEventForm.setId(originalForm.getId()); } } /** * @param request * @param dynamicEventForm */ private void populateStaticAttributes(HttpServletRequest request, final DynamicEventForm dynamicEventForm) { String sessionMapName = "formContextParameterMap"+ getFormContextFromRequest(request); Map<String, Object> formContextParameterMap = (Map<String, Object>) request.getSession().getAttribute(sessionMapName); if(formContextParameterMap !=null && Boolean.parseBoolean(request.getParameter(Constants.CONTAINS_ERROR))) { setDateParameters(request, formContextParameterMap); dynamicEventForm.setTimeInMinutes((String) formContextParameterMap.get("timeInMinutes")); dynamicEventForm.setTimeInHours((String) formContextParameterMap.get("timeInHours")); dynamicEventForm.setUserId(Long.valueOf((String)formContextParameterMap.get(Constants.USER_ID))); dynamicEventForm.setDateOfEvent((String) formContextParameterMap.get(Constants.DATE_OF_EVENT)); dynamicEventForm.setReasonDeviation((String) formContextParameterMap.get(Constants.REASON_DEVIATION)); request.getSession().removeAttribute(sessionMapName); request.getSession().removeAttribute(Constants.DYN_EVENT_FORM); } } /** * @param request * @param formContextParameterMap */ private void setDateParameters(HttpServletRequest request, Map<String, Object> formContextParameterMap) { if(formContextParameterMap.get(Constants.DATE_OF_EVENT)!= null) { String currentEventParametersDate = (String) formContextParameterMap.get(Constants.DATE_OF_EVENT); request.setAttribute("currentEventParametersDate", currentEventParametersDate); request.setAttribute("dynamicEventParametersYear", AppUtility .getYear(currentEventParametersDate)); request.setAttribute("dynamicEventParametersDay", AppUtility .getDay(currentEventParametersDate)); request.setAttribute("dynamicEventParametersMonth", AppUtility .getMonth(currentEventParametersDate)); } } /** * @param request * @return */ private String getFormContextFromRequest(HttpServletRequest request) { String formContxtId = request.getParameter("formContextId"); if(formContxtId == null) { formContxtId = String.valueOf(request.getAttribute("formContextId")); } return formContxtId; } }
false
true
protected ActionForward executeAction(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { if (request.getParameter(Constants.REFRESH_EVENT_GRID) != null) { request.setAttribute(Constants.REFRESH_EVENT_GRID, request .getParameter(Constants.REFRESH_EVENT_GRID)); } //this.setCommonRequestParameters(request); DynamicEventForm dynamicEventForm = (DynamicEventForm) form; resetFormParameters(request, dynamicEventForm); // if operation is add if (dynamicEventForm.isAddOperation()) { if (dynamicEventForm.getUserId() == 0) { final SessionDataBean sessionData = this.getSessionData(request); if (sessionData != null && sessionData.getUserId() != null) { final long userId = sessionData.getUserId().longValue(); dynamicEventForm.setUserId(userId); } } // set the current Date and Time for the event. final Calendar cal = Calendar.getInstance(); if (dynamicEventForm.getDateOfEvent() == null) { dynamicEventForm.setDateOfEvent(CommonUtilities.parseDateToString(cal.getTime(), CommonServiceLocator.getInstance().getDatePattern())); } if (dynamicEventForm.getTimeInHours() == null) { dynamicEventForm.setTimeInHours(Integer.toString(cal.get(Calendar.HOUR_OF_DAY))); } if (dynamicEventForm.getTimeInMinutes() == null) { dynamicEventForm.setTimeInMinutes(Integer.toString(cal.get(Calendar.MINUTE))); } } else { String specimenId = (String) request.getAttribute(Constants.SPECIMEN_ID); if (specimenId == null) { request.setAttribute(Constants.SPECIMEN_ID, specimenId); } } String reasonDeviation = ""; reasonDeviation = dynamicEventForm.getReasonDeviation(); if (reasonDeviation == null) { reasonDeviation = ""; } String currentEventParametersDate = ""; currentEventParametersDate = dynamicEventForm.getDateOfEvent(); if (currentEventParametersDate == null) { currentEventParametersDate = ""; } final Integer dynamicEventParametersYear = new Integer(AppUtility .getYear(currentEventParametersDate)); final Integer dynamicEventParametersMonth = new Integer(AppUtility .getMonth(currentEventParametersDate)); final Integer dynamicEventParametersDay = new Integer(AppUtility .getDay(currentEventParametersDate)); request.setAttribute("minutesList", Constants.MINUTES_ARRAY); // Sets the hourList attribute to be used in the Add/Edit // FrozenEventParameters Page. request.setAttribute("hourList", Constants.HOUR_ARRAY); request.setAttribute("dynamicEventParametersYear", dynamicEventParametersYear); request.setAttribute("dynamicEventParametersDay", dynamicEventParametersDay); request.setAttribute("dynamicEventParametersMonth", dynamicEventParametersMonth); request.setAttribute("formName", Constants.DYNAMIC_EVENT_ACTION); request.setAttribute("addForJSP", Constants.ADD); request.setAttribute("editForJSP", Constants.EDIT); request.setAttribute("reasonDeviation", reasonDeviation); request.setAttribute("userListforJSP", Constants.USERLIST); request.setAttribute("currentEventParametersDate", currentEventParametersDate); request.setAttribute(Constants.PAGE_OF, "pageOfDynamicEvent"); request.setAttribute(Constants.SPECIMEN_ID, request.getSession().getAttribute( Constants.SPECIMEN_ID)); //request.setAttribute(Constants.SPECIMEN_ID, request.getAttribute(Constants.SPECIMEN_ID)); //request.setAttribute(Constants.PAGE_OF, request.getParameter(Constants.PAGE_OF)); //request.setAttribute("changeAction", Constants.CELL_SPECIMEN_REVIEW_PARAMETERS_ADD_ACTION); final String operation = request.getParameter(Constants.OPERATION); final IFactory factory = AbstractFactoryConfig.getInstance().getBizLogicFactory(); final UserBizLogic userBizLogic = (UserBizLogic) factory .getBizLogic(Constants.USER_FORM_ID); final Collection userCollection = userBizLogic.getUsers(operation); request.setAttribute(Constants.USERLIST, userCollection); HashMap dynamicEventMap = (HashMap) request.getSession().getAttribute("dynamicEventMap"); String iframeURL=""; long recordIdentifier=0; Long eventId=null; if(dynamicEventForm.getOperation().equals(Constants.ADD)) { String eventName = request.getParameter("eventName"); if(eventName == null) { eventName = (String)request.getSession().getAttribute("eventName"); } request.getSession().setAttribute("eventName", eventName); dynamicEventForm.setEventName(eventName); eventId=(Long) dynamicEventMap.get(eventName); String query="Select IS_CACORE_GENERATED from dyextn_entity_group where IDENTIFIER = (select ENTITY_GROUP_ID from dyextn_container where IDENTIFIER="+eventId+")"; List result=AppUtility.executeSQLQuery(query); Boolean isCaCoreGenerated=Boolean.parseBoolean(((List) result.get(0)).get(0).toString()); if(!isCaCoreGenerated) { request.setAttribute("isCaCoreGenerated", true); } if (Boolean.parseBoolean(request.getParameter("showDefaultValues"))) { IBizLogic defaultBizLogic = new CatissueDefaultBizLogic(); List<Action> actionList = defaultBizLogic.retrieve(Action.class.getName(), Constants.ID, request.getParameter("formContextId")); if (actionList != null && !actionList.isEmpty()) { Action action = (Action) actionList.get(0); if (action.getApplicationDefaultValue() != null) { recordIdentifier = SpecimenEventsUtility.getRecordIdentifier(action .getApplicationDefaultValue().getId(), action.getContainerId()); } } } else { IBizLogic defaultBizLogic = new CatissueDefaultBizLogic(); List<DefaultAction> actionList = defaultBizLogic.retrieve(DefaultAction.class .getName(), Constants.CONTAINER_ID, eventId); DefaultAction action =null; if (actionList != null && !actionList.isEmpty()) { action = (DefaultAction) actionList.get(0); } else { action=new DefaultAction(); action.setContainerId(eventId); defaultBizLogic.insert(action); } request.setAttribute("formContextId",action.getId()); } if(eventName != null) { request.setAttribute("formDisplayName", Utility.getFormattedString(eventName)); } if(eventId != null) { request.getSession().setAttribute("OverrideCaption", "_" + eventId.toString()); iframeURL = "/catissuecore/LoadDataEntryFormAction.do?dataEntryOperation=insertParentData&useApplicationStylesheet=true&showInDiv=false&overrideCSS=true&overrideScroll=true"+(Boolean.parseBoolean(request.getParameter(Constants.CONTAINS_ERROR))?"&containerId=":"&containerIdentifier=") + eventId.toString() + "&OverrideCaption=" + "_" + eventId.toString(); if (recordIdentifier != 0) { iframeURL = iframeURL + "&recordIdentifier=" + recordIdentifier; } } } else { String actionApplicationId = request.getParameter("id"); if(actionApplicationId ==null) { actionApplicationId = (String) request.getAttribute("id"); } if(Boolean.parseBoolean(request.getParameter(Constants.CONTAINS_ERROR)) && request.getSession().getAttribute("dynamicEventsForm") != null) { dynamicEventForm = (DynamicEventForm) request.getSession().getAttribute("dynamicEventsForm"); actionApplicationId = String.valueOf(dynamicEventForm.getId()); } recordIdentifier = SpecimenEventsUtility.getRecordIdentifier(dynamicEventForm .getRecordEntry(), dynamicEventForm.getContId()); Long containerId = dynamicEventForm.getContId(); IBizLogic defaultBizLogic = new CatissueDefaultBizLogic(); String specimenId = (String) request.getAttribute(Constants.SPECIMEN_ID); boolean isDefaultAction = true; if(specimenId!=null && !"".equals(specimenId)) { List<Specimen> specimentList = defaultBizLogic.retrieve( Specimen.class.getName(), Constants.ID, specimenId); if (specimentList != null && !specimentList.isEmpty()) { Specimen specimen = (Specimen) specimentList.get(0); if(specimen.getProcessingSPPApplication() != null) { for(ActionApplication actionApplication : new SPPEventProcessor().getFilteredActionApplication(specimen.getProcessingSPPApplication().getSppActionApplicationCollection())) { if(actionApplication.getId().toString().equals(actionApplicationId)) { for(Action action : specimen.getSpecimenRequirement().getProcessingSPP().getActionCollection()) { if(action.getContainerId().equals(containerId)) { request.setAttribute("formContextId", action.getId()); break; } } isDefaultAction = false; break; } } } } } if(isDefaultAction) { List<DefaultAction> actionList = defaultBizLogic.retrieve( DefaultAction.class.getName(), Constants.CONTAINER_ID, dynamicEventForm .getContId()); if (actionList != null && !actionList.isEmpty()) { DefaultAction action = (DefaultAction) actionList.get(0); request.setAttribute("formContextId", action.getId()); } } dynamicEventForm.setRecordIdentifier(recordIdentifier); iframeURL = "/catissuecore/LoadDataEntryFormAction.do?dataEntryOperation=edit&useApplicationStylesheet=true&showInDiv=false"+(Boolean.parseBoolean(request.getParameter(Constants.CONTAINS_ERROR))?"&containerId=":"&containerIdentifier=") + dynamicEventForm.getContId() + "&recordIdentifier=" + recordIdentifier + "&OverrideCaption=" + "_" + dynamicEventForm.getContId(); List contList = AppUtility .executeSQLQuery("select caption from dyextn_container where identifier=" + dynamicEventForm.getContId()); String eventName = (String) ((List) contList.get(0)).get(0); request.setAttribute("formDisplayName", Utility.getFormattedString(eventName)); } if (request.getSession().getAttribute("specimenId") == null) { request.getSession().setAttribute("specimenId", request.getParameter("specimenId")); } request.setAttribute("recordIdentifier", recordIdentifier); request.getSession().setAttribute("recordIdentifier", recordIdentifier); request.getSession().setAttribute("containerId", dynamicEventForm.getContId()); request.getSession().setAttribute("mandatory_Message", "false"); String formContxtId = getFormContextFromRequest(request); if(!"".equals(iframeURL)) { iframeURL = iframeURL + "&FormContextIdentifier=" + formContxtId; } populateStaticAttributes(request, dynamicEventForm); request.setAttribute("iframeURL", iframeURL+"&showCalculateDefaultValue=false"); return mapping.findForward((String) request.getAttribute(Constants.PAGE_OF)); }
protected ActionForward executeAction(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { if (request.getParameter(Constants.REFRESH_EVENT_GRID) != null) { request.setAttribute(Constants.REFRESH_EVENT_GRID, request .getParameter(Constants.REFRESH_EVENT_GRID)); } //this.setCommonRequestParameters(request); DynamicEventForm dynamicEventForm = (DynamicEventForm) form; resetFormParameters(request, dynamicEventForm); // if operation is add if (dynamicEventForm.isAddOperation()) { if (dynamicEventForm.getUserId() == 0) { final SessionDataBean sessionData = this.getSessionData(request); if (sessionData != null && sessionData.getUserId() != null) { final long userId = sessionData.getUserId().longValue(); dynamicEventForm.setUserId(userId); } } // set the current Date and Time for the event. final Calendar cal = Calendar.getInstance(); if (dynamicEventForm.getDateOfEvent() == null) { dynamicEventForm.setDateOfEvent(CommonUtilities.parseDateToString(cal.getTime(), CommonServiceLocator.getInstance().getDatePattern())); } if (dynamicEventForm.getTimeInHours() == null) { dynamicEventForm.setTimeInHours(Integer.toString(cal.get(Calendar.HOUR_OF_DAY))); } if (dynamicEventForm.getTimeInMinutes() == null) { dynamicEventForm.setTimeInMinutes(Integer.toString(cal.get(Calendar.MINUTE))); } } else { String specimenId = (String) request.getAttribute(Constants.SPECIMEN_ID); if (specimenId == null) { request.setAttribute(Constants.SPECIMEN_ID, specimenId); } } String reasonDeviation = ""; reasonDeviation = dynamicEventForm.getReasonDeviation(); if (reasonDeviation == null) { reasonDeviation = ""; } String currentEventParametersDate = ""; currentEventParametersDate = dynamicEventForm.getDateOfEvent(); if (currentEventParametersDate == null) { currentEventParametersDate = ""; } final Integer dynamicEventParametersYear = new Integer(AppUtility .getYear(currentEventParametersDate)); final Integer dynamicEventParametersMonth = new Integer(AppUtility .getMonth(currentEventParametersDate)); final Integer dynamicEventParametersDay = new Integer(AppUtility .getDay(currentEventParametersDate)); request.setAttribute("minutesList", Constants.MINUTES_ARRAY); // Sets the hourList attribute to be used in the Add/Edit // FrozenEventParameters Page. request.setAttribute("hourList", Constants.HOUR_ARRAY); request.setAttribute("dynamicEventParametersYear", dynamicEventParametersYear); request.setAttribute("dynamicEventParametersDay", dynamicEventParametersDay); request.setAttribute("dynamicEventParametersMonth", dynamicEventParametersMonth); request.setAttribute("formName", Constants.DYNAMIC_EVENT_ACTION); request.setAttribute("addForJSP", Constants.ADD); request.setAttribute("editForJSP", Constants.EDIT); request.setAttribute("reasonDeviation", reasonDeviation); request.setAttribute("userListforJSP", Constants.USERLIST); request.setAttribute("currentEventParametersDate", currentEventParametersDate); request.setAttribute(Constants.PAGE_OF, "pageOfDynamicEvent"); request.setAttribute(Constants.SPECIMEN_ID, request.getSession().getAttribute( Constants.SPECIMEN_ID)); //request.setAttribute(Constants.SPECIMEN_ID, request.getAttribute(Constants.SPECIMEN_ID)); //request.setAttribute(Constants.PAGE_OF, request.getParameter(Constants.PAGE_OF)); //request.setAttribute("changeAction", Constants.CELL_SPECIMEN_REVIEW_PARAMETERS_ADD_ACTION); final String operation = request.getParameter(Constants.OPERATION); final IFactory factory = AbstractFactoryConfig.getInstance().getBizLogicFactory(); final UserBizLogic userBizLogic = (UserBizLogic) factory .getBizLogic(Constants.USER_FORM_ID); final Collection userCollection = userBizLogic.getUsers(operation); request.setAttribute(Constants.USERLIST, userCollection); HashMap dynamicEventMap = (HashMap) request.getSession().getAttribute("dynamicEventMap"); String iframeURL=""; long recordIdentifier=0; Long eventId=null; if(dynamicEventForm.getOperation().equals(Constants.ADD)) { String eventName = request.getParameter("eventName"); if(eventName == null) { eventName = (String)request.getSession().getAttribute("eventName"); } request.getSession().setAttribute("eventName", eventName); dynamicEventForm.setEventName(eventName); eventId=(Long) dynamicEventMap.get(eventName); /*String query="Select IS_CACORE_GENERATED from dyextn_entity_group where IDENTIFIER = (select ENTITY_GROUP_ID from dyextn_container where IDENTIFIER="+eventId+")"; List result=AppUtility.executeSQLQuery(query); Boolean isCaCoreGenerated=Boolean.parseBoolean(((List) result.get(0)).get(0).toString()); if(!isCaCoreGenerated) { request.setAttribute("isCaCoreGenerated", true); }*/ if (Boolean.parseBoolean(request.getParameter("showDefaultValues"))) { IBizLogic defaultBizLogic = new CatissueDefaultBizLogic(); List<Action> actionList = defaultBizLogic.retrieve(Action.class.getName(), Constants.ID, request.getParameter("formContextId")); if (actionList != null && !actionList.isEmpty()) { Action action = (Action) actionList.get(0); if (action.getApplicationDefaultValue() != null) { recordIdentifier = SpecimenEventsUtility.getRecordIdentifier(action .getApplicationDefaultValue().getId(), action.getContainerId()); } } } else { IBizLogic defaultBizLogic = new CatissueDefaultBizLogic(); List<DefaultAction> actionList = defaultBizLogic.retrieve(DefaultAction.class .getName(), Constants.CONTAINER_ID, eventId); DefaultAction action =null; if (actionList != null && !actionList.isEmpty()) { action = (DefaultAction) actionList.get(0); } else { action=new DefaultAction(); action.setContainerId(eventId); defaultBizLogic.insert(action); } request.setAttribute("formContextId",action.getId()); } if(eventName != null) { request.setAttribute("formDisplayName", Utility.getFormattedString(eventName)); } if(eventId != null) { request.getSession().setAttribute("OverrideCaption", "_" + eventId.toString()); iframeURL = "/catissuecore/LoadDataEntryFormAction.do?dataEntryOperation=insertParentData&useApplicationStylesheet=true&showInDiv=false&overrideCSS=true&overrideScroll=true"+(Boolean.parseBoolean(request.getParameter(Constants.CONTAINS_ERROR))?"&containerId=":"&containerIdentifier=") + eventId.toString() + "&OverrideCaption=" + "_" + eventId.toString(); if (recordIdentifier != 0) { iframeURL = iframeURL + "&recordIdentifier=" + recordIdentifier; } } } else { String actionApplicationId = request.getParameter("id"); if(actionApplicationId ==null) { actionApplicationId = (String) request.getAttribute("id"); } if(Boolean.parseBoolean(request.getParameter(Constants.CONTAINS_ERROR)) && request.getSession().getAttribute("dynamicEventsForm") != null) { dynamicEventForm = (DynamicEventForm) request.getSession().getAttribute("dynamicEventsForm"); actionApplicationId = String.valueOf(dynamicEventForm.getId()); } recordIdentifier = SpecimenEventsUtility.getRecordIdentifier(dynamicEventForm .getRecordEntry(), dynamicEventForm.getContId()); Long containerId = dynamicEventForm.getContId(); IBizLogic defaultBizLogic = new CatissueDefaultBizLogic(); String specimenId = (String) request.getAttribute(Constants.SPECIMEN_ID); boolean isDefaultAction = true; if(specimenId!=null && !"".equals(specimenId)) { List<Specimen> specimentList = defaultBizLogic.retrieve( Specimen.class.getName(), Constants.ID, specimenId); if (specimentList != null && !specimentList.isEmpty()) { Specimen specimen = (Specimen) specimentList.get(0); if(specimen.getProcessingSPPApplication() != null) { for(ActionApplication actionApplication : new SPPEventProcessor().getFilteredActionApplication(specimen.getProcessingSPPApplication().getSppActionApplicationCollection())) { if(actionApplication.getId().toString().equals(actionApplicationId)) { for(Action action : specimen.getSpecimenRequirement().getProcessingSPP().getActionCollection()) { if(action.getContainerId().equals(containerId)) { request.setAttribute("formContextId", action.getId()); break; } } isDefaultAction = false; break; } } } } } if(isDefaultAction) { List<DefaultAction> actionList = defaultBizLogic.retrieve( DefaultAction.class.getName(), Constants.CONTAINER_ID, dynamicEventForm .getContId()); if (actionList != null && !actionList.isEmpty()) { DefaultAction action = (DefaultAction) actionList.get(0); request.setAttribute("formContextId", action.getId()); } } dynamicEventForm.setRecordIdentifier(recordIdentifier); iframeURL = "/catissuecore/LoadDataEntryFormAction.do?dataEntryOperation=edit&useApplicationStylesheet=true&showInDiv=false"+(Boolean.parseBoolean(request.getParameter(Constants.CONTAINS_ERROR))?"&containerId=":"&containerIdentifier=") + dynamicEventForm.getContId() + "&recordIdentifier=" + recordIdentifier + "&OverrideCaption=" + "_" + dynamicEventForm.getContId(); List contList = AppUtility .executeSQLQuery("select caption from dyextn_container where identifier=" + dynamicEventForm.getContId()); String eventName = (String) ((List) contList.get(0)).get(0); request.setAttribute("formDisplayName", Utility.getFormattedString(eventName)); } if (request.getSession().getAttribute("specimenId") == null) { request.getSession().setAttribute("specimenId", request.getParameter("specimenId")); } request.setAttribute("recordIdentifier", recordIdentifier); request.getSession().setAttribute("recordIdentifier", recordIdentifier); request.getSession().setAttribute("containerId", dynamicEventForm.getContId()); request.getSession().setAttribute("mandatory_Message", "false"); String formContxtId = getFormContextFromRequest(request); if(!"".equals(iframeURL)) { iframeURL = iframeURL + "&FormContextIdentifier=" + formContxtId; } populateStaticAttributes(request, dynamicEventForm); request.setAttribute("iframeURL", iframeURL+"&showCalculateDefaultValue=false"); return mapping.findForward((String) request.getAttribute(Constants.PAGE_OF)); }
diff --git a/src/org/eclipse/core/tests/resources/regression/AllTests.java b/src/org/eclipse/core/tests/resources/regression/AllTests.java index a7df65a..d18a534 100644 --- a/src/org/eclipse/core/tests/resources/regression/AllTests.java +++ b/src/org/eclipse/core/tests/resources/regression/AllTests.java @@ -1,59 +1,60 @@ /******************************************************************************* * Copyright (c) 2000, 2004 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.core.tests.resources.regression; import junit.framework.*; public class AllTests extends TestCase { /** * AllTests constructor comment. * @param name java.lang.String */ public AllTests() { super(null); } /** * AllTests constructor comment. * @param name java.lang.String */ public AllTests(String name) { super(name); } public static Test suite() { TestSuite suite = new TestSuite(AllTests.class.getName()); suite.addTest(Bug_126104.suite()); suite.addTest(Bug_127562.suite()); + suite.addTest(Bug_132510.suite()); suite.addTest(Bug_25457.suite()); suite.addTest(Bug_26294.suite()); suite.addTest(Bug_27271.suite()); suite.addTest(Bug_28981.suite()); suite.addTest(Bug_29116.suite()); suite.addTest(Bug_29671.suite()); suite.addTest(Bug_29851.suite()); suite.addTest(Bug_32076.suite()); suite.addTest(Bug_44106.suite()); suite.addTest(Bug_6708.suite()); suite.addTest(Bug_98740.suite()); suite.addTest(IFileTest.suite()); suite.addTest(IFolderTest.suite()); suite.addTest(IProjectTest.suite()); suite.addTest(IResourceTest.suite()); suite.addTest(IWorkspaceTest.suite()); suite.addTest(LocalStoreRegressionTests.suite()); suite.addTest(NLTest.suite()); suite.addTest(PR_1GEAB3C_Test.suite()); suite.addTest(PR_1GH2B0N_Test.suite()); suite.addTest(PR_1GHOM0N_Test.suite()); return suite; } }
true
true
public static Test suite() { TestSuite suite = new TestSuite(AllTests.class.getName()); suite.addTest(Bug_126104.suite()); suite.addTest(Bug_127562.suite()); suite.addTest(Bug_25457.suite()); suite.addTest(Bug_26294.suite()); suite.addTest(Bug_27271.suite()); suite.addTest(Bug_28981.suite()); suite.addTest(Bug_29116.suite()); suite.addTest(Bug_29671.suite()); suite.addTest(Bug_29851.suite()); suite.addTest(Bug_32076.suite()); suite.addTest(Bug_44106.suite()); suite.addTest(Bug_6708.suite()); suite.addTest(Bug_98740.suite()); suite.addTest(IFileTest.suite()); suite.addTest(IFolderTest.suite()); suite.addTest(IProjectTest.suite()); suite.addTest(IResourceTest.suite()); suite.addTest(IWorkspaceTest.suite()); suite.addTest(LocalStoreRegressionTests.suite()); suite.addTest(NLTest.suite()); suite.addTest(PR_1GEAB3C_Test.suite()); suite.addTest(PR_1GH2B0N_Test.suite()); suite.addTest(PR_1GHOM0N_Test.suite()); return suite; }
public static Test suite() { TestSuite suite = new TestSuite(AllTests.class.getName()); suite.addTest(Bug_126104.suite()); suite.addTest(Bug_127562.suite()); suite.addTest(Bug_132510.suite()); suite.addTest(Bug_25457.suite()); suite.addTest(Bug_26294.suite()); suite.addTest(Bug_27271.suite()); suite.addTest(Bug_28981.suite()); suite.addTest(Bug_29116.suite()); suite.addTest(Bug_29671.suite()); suite.addTest(Bug_29851.suite()); suite.addTest(Bug_32076.suite()); suite.addTest(Bug_44106.suite()); suite.addTest(Bug_6708.suite()); suite.addTest(Bug_98740.suite()); suite.addTest(IFileTest.suite()); suite.addTest(IFolderTest.suite()); suite.addTest(IProjectTest.suite()); suite.addTest(IResourceTest.suite()); suite.addTest(IWorkspaceTest.suite()); suite.addTest(LocalStoreRegressionTests.suite()); suite.addTest(NLTest.suite()); suite.addTest(PR_1GEAB3C_Test.suite()); suite.addTest(PR_1GH2B0N_Test.suite()); suite.addTest(PR_1GHOM0N_Test.suite()); return suite; }
diff --git a/alerts/web/src/main/java/org/kuali/mobility/alerts/controllers/AlertsController.java b/alerts/web/src/main/java/org/kuali/mobility/alerts/controllers/AlertsController.java index 9812a7f..0daac07 100644 --- a/alerts/web/src/main/java/org/kuali/mobility/alerts/controllers/AlertsController.java +++ b/alerts/web/src/main/java/org/kuali/mobility/alerts/controllers/AlertsController.java @@ -1,47 +1,47 @@ /** * Copyright 2011 The Kuali Foundation Licensed under the * Educational Community License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may * obtain a copy of the License at * * http://www.osedu.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS IS" * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing * permissions and limitations under the License. */ package org.kuali.mobility.alerts.controllers; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.kuali.mobility.alerts.entity.Alert; import org.kuali.mobility.alerts.service.AlertsService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller @RequestMapping("/alerts") public class AlertsController { @Autowired private AlertsService alertsService; public void setAlertsService(AlertsService alertsService) { this.alertsService = alertsService; } @RequestMapping(method = RequestMethod.GET) public String getList(HttpServletRequest request, Model uiModel) { - List<Alert> alerts = alertsService.findAllAlertsFromJson(request.getScheme() + "://" + request.getRemoteHost() + ":" + request.getServerPort() + request.getContextPath() + "/testdata/alerts.json"); + List<Alert> alerts = alertsService.findAllAlertsFromJson(request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/testdata/alerts.json"); uiModel.addAttribute("alerts", alerts); return "alerts/list"; } }
true
true
public String getList(HttpServletRequest request, Model uiModel) { List<Alert> alerts = alertsService.findAllAlertsFromJson(request.getScheme() + "://" + request.getRemoteHost() + ":" + request.getServerPort() + request.getContextPath() + "/testdata/alerts.json"); uiModel.addAttribute("alerts", alerts); return "alerts/list"; }
public String getList(HttpServletRequest request, Model uiModel) { List<Alert> alerts = alertsService.findAllAlertsFromJson(request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/testdata/alerts.json"); uiModel.addAttribute("alerts", alerts); return "alerts/list"; }
diff --git a/src/lib/com/izforge/izpack/installer/Unpacker.java b/src/lib/com/izforge/izpack/installer/Unpacker.java index 471c4a98..da55a91f 100644 --- a/src/lib/com/izforge/izpack/installer/Unpacker.java +++ b/src/lib/com/izforge/izpack/installer/Unpacker.java @@ -1,400 +1,410 @@ /* * $Id$ * IzPack * Copyright (C) 2001-2003 Julien Ponge * * File : Unpacker.java * Description : The unpacker class. * Author's email : [email protected] * Author's Website : http://www.izforge.com * * Portions are Copyright (c) 2001 Johannes Lehtinen * [email protected] * http://www.iki.fi/jle/ * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package com.izforge.izpack.installer; import com.izforge.izpack.util.*; import com.izforge.izpack.*; import java.io.*; import java.net.*; import java.util.*; import java.util.zip.*; /** * Unpacker class. * * @author Julien Ponge * @author Johannes Lehtinen * @created October 27, 2002 */ public class Unpacker extends Thread { /** The installdata. */ private AutomatedInstallData idata; /** The installer listener. */ private AbstractUIProgressHandler handler; /** The uninstallation data. */ private UninstallData udata; /** The jar location. */ private String jarLocation; /** The variables substitutor. */ private VariableSubstitutor vs; /** The instances of the unpacker objects. */ private static ArrayList instances = new ArrayList(); /** * The constructor. * * @param idata The installation data. * @param handler The installation progress handler. */ public Unpacker(AutomatedInstallData idata, AbstractUIProgressHandler handler) { super("IzPack - Unpacker thread"); this.idata = idata; this.handler = handler; // Initialize the variable substitutor vs = new VariableSubstitutor(idata.getVariableValueMap()); } /** * Returns the active unpacker instances. * * @return The active unpacker instances. */ public static ArrayList getRunningInstances() { return instances; } /** The run method. */ public void run() { instances.add(this); try { // // Initialisations FileOutputStream out = null; ArrayList parsables = new ArrayList(); ArrayList executables = new ArrayList(); List packs = idata.selectedPacks; int npacks = packs.size(); handler.startAction ("Unpacking", npacks); udata = UninstallData.getInstance(); // Specific to the web installers if (idata.kind.equalsIgnoreCase("web") || idata.kind.equalsIgnoreCase("web-kunststoff")) { InputStream kin = getClass().getResourceAsStream("/res/WebInstallers.url"); BufferedReader kreader = new BufferedReader(new InputStreamReader(kin)); jarLocation = kreader.readLine(); } // We unpack the selected packs for (int i = 0; i < npacks; i++) { // We get the pack stream int n = idata.allPacks.indexOf(packs.get(i)); ObjectInputStream objIn = new ObjectInputStream(getPackAsStream(n)); // We unpack the files int nfiles = objIn.readInt(); handler.nextStep (((Pack) packs.get(i)).name, i+1, nfiles); for (int j = 0; j < nfiles; j++) { // We read the header PackFile pf = (PackFile) objIn.readObject(); if (OsConstraint.oneMatchesCurrentSystem(pf.osConstraints)) { // We translate & build the path String path = translatePath(pf.targetPath); File pathFile = new File(path); File dest = pathFile.getParentFile(); if (!dest.exists()) - dest.mkdirs(); + { + if (! dest.mkdirs()) + { + handler.emitError("Error creating directories", "Could not create directory\n"+dest.getPath()); + handler.stopAction (); + return; + } + } // We add the path to the log, udata.addFile(path); handler.progress (j, path); //if this file exists and should not be overwritten, check //what to do if ((pathFile.exists ()) && (pf.override != PackFile.OVERRIDE_TRUE)) { boolean overwritefile = false; // don't overwrite file if the user said so if (pf.override != PackFile.OVERRIDE_FALSE) { if (pf.override == PackFile.OVERRIDE_TRUE) { overwritefile = true; } else if (pf.override == PackFile.OVERRIDE_UPDATE) { // check mtime of involved files // (this is not 100% perfect, because the already existing file might // still be modified but the new installed is just a bit newer; we would // need the creation time of the existing file or record with which mtime // it was installed...) overwritefile = (pathFile.lastModified() < pf.mtime); } else { int def_choice = -1; if (pf.override == PackFile.OVERRIDE_ASK_FALSE) def_choice = AbstractUIHandler.ANSWER_NO; if (pf.override == PackFile.OVERRIDE_ASK_TRUE) def_choice = AbstractUIHandler.ANSWER_YES; int answer = handler.askQuestion ( idata.langpack.getString ("InstallPanel.overwrite.title") + pathFile.getName (), idata.langpack.getString ("InstallPanel.overwrite.question") + pathFile.getAbsolutePath(), AbstractUIHandler.CHOICES_YES_NO, def_choice); overwritefile = (answer == AbstractUIHandler.ANSWER_YES); } } if (! overwritefile) { objIn.skip(pf.length); continue; } } // We copy the file out = new FileOutputStream(pathFile); byte[] buffer = new byte[5120]; long bytesCopied = 0; while (bytesCopied < pf.length) { int maxBytes = (pf.length - bytesCopied < buffer.length ? (int) (pf.length - bytesCopied) : buffer.length); int bytesInBuffer = objIn.read(buffer, 0, maxBytes); if (bytesInBuffer == -1) throw new IOException("Unexpected end of stream"); out.write(buffer, 0, bytesInBuffer); bytesCopied += bytesInBuffer; } // Cleanings out.close(); // Set file modification time if specified if (pf.mtime >= 0) pathFile.setLastModified (pf.mtime); // Empty dirs restoring String _n = pathFile.getName(); if (_n.startsWith("izpack-keepme") && _n.endsWith(".tmp")) pathFile.delete(); } else objIn.skip(pf.length); } // Load information about parsable files int numParsables = objIn.readInt(); int k; for (k = 0; k < numParsables; k++) { ParsableFile pf = (ParsableFile) objIn.readObject(); pf.path = translatePath(pf.path); parsables.add(pf); } // Load information about executable files int numExecutables = objIn.readInt(); for (k = 0; k < numExecutables; k++) { ExecutableFile ef = (ExecutableFile) objIn.readObject(); ef.path = translatePath(ef.path); if (null != ef.argList && !ef.argList.isEmpty()) { String arg = null; for (int j = 0; j < ef.argList.size(); j++) { arg = (String) ef.argList.get(j); arg = translatePath(arg); ef.argList.set(j, arg); } } executables.add(ef); if(ef.executionStage == ExecutableFile.UNINSTALL) { udata.addExecutable(ef); } } objIn.close(); } // We use the scripts parser ScriptParser parser = new ScriptParser(parsables, vs); parser.parseFiles(); // We use the file executor FileExecutor executor = new FileExecutor(executables); if (executor.executeFiles(ExecutableFile.POSTINSTALL, handler) != 0) handler.emitError ("File execution failed", "The installation was not completed"); // We put the uninstaller if (idata.info.getWriteUninstaller()) putUninstaller(); // The end :-) handler.stopAction(); } catch (Exception err) { // TODO: finer grained error handling with useful error messages handler.stopAction(); - handler.emitError ("An exception was caught", err.toString()); + handler.emitError ("An error occured", err.toString()); err.printStackTrace (); } - instances.remove(instances.indexOf(this)); + finally + { + instances.remove(instances.indexOf(this)); + } } /** * Puts the uninstaller. * * @exception Exception Description of the Exception */ private void putUninstaller() throws Exception { // Me make the .uninstaller directory String dest = translatePath("$INSTALL_PATH") + File.separator + "Uninstaller"; String jar = dest + File.separator + "uninstaller.jar"; File pathMaker = new File(dest); pathMaker.mkdirs(); // We log the uninstaller deletion information UninstallData udata = UninstallData.getInstance(); udata.setUninstallerJarFilename(jar); udata.setUninstallerPath(dest); // We open our final jar file FileOutputStream out = new FileOutputStream(jar); ZipOutputStream outJar = new ZipOutputStream(out); idata.uninstallOutJar = outJar; outJar.setLevel(9); udata.addFile(jar); // We copy the uninstaller InputStream in = getClass().getResourceAsStream("/res/IzPack.uninstaller"); ZipInputStream inRes = new ZipInputStream(in); ZipEntry zentry = inRes.getNextEntry(); while (zentry != null) { // Puts a new entry outJar.putNextEntry(new ZipEntry(zentry.getName())); // Byte to byte copy int unc = inRes.read(); while (unc != -1) { outJar.write(unc); unc = inRes.read(); } // Next one please inRes.closeEntry(); outJar.closeEntry(); zentry = inRes.getNextEntry(); } inRes.close(); // We put the langpack in = getClass().getResourceAsStream("/langpacks/" + idata.localeISO3 + ".xml"); outJar.putNextEntry(new ZipEntry("langpack.xml")); int read = in.read(); while (read != -1) { outJar.write(read); read = in.read(); } outJar.closeEntry(); } /** * Returns a stream to a pack, depending on the installation kind. * * @param n The pack number. * @return The stream. * @exception Exception Description of the Exception */ private InputStream getPackAsStream(int n) throws Exception { InputStream in = null; if (idata.kind.equalsIgnoreCase("standard") || idata.kind.equalsIgnoreCase("standard-kunststoff")) in = getClass().getResourceAsStream("/packs/pack" + n); else if (idata.kind.equalsIgnoreCase("web") || idata.kind.equalsIgnoreCase("web-kunststoff")) { URL url = new URL("jar:" + jarLocation + "!/packs/pack" + n); JarURLConnection jarConnection = (JarURLConnection) url.openConnection(); in = jarConnection.getInputStream(); } return in; } /** * Translates a relative path to a local system path. * * @param destination The path to translate. * @return The translated path. */ private String translatePath(String destination) { // Parse for variables destination = vs.substitute(destination, null); // Convert the file separator characters return destination.replace('/', File.separatorChar); } }
false
true
public void run() { instances.add(this); try { // // Initialisations FileOutputStream out = null; ArrayList parsables = new ArrayList(); ArrayList executables = new ArrayList(); List packs = idata.selectedPacks; int npacks = packs.size(); handler.startAction ("Unpacking", npacks); udata = UninstallData.getInstance(); // Specific to the web installers if (idata.kind.equalsIgnoreCase("web") || idata.kind.equalsIgnoreCase("web-kunststoff")) { InputStream kin = getClass().getResourceAsStream("/res/WebInstallers.url"); BufferedReader kreader = new BufferedReader(new InputStreamReader(kin)); jarLocation = kreader.readLine(); } // We unpack the selected packs for (int i = 0; i < npacks; i++) { // We get the pack stream int n = idata.allPacks.indexOf(packs.get(i)); ObjectInputStream objIn = new ObjectInputStream(getPackAsStream(n)); // We unpack the files int nfiles = objIn.readInt(); handler.nextStep (((Pack) packs.get(i)).name, i+1, nfiles); for (int j = 0; j < nfiles; j++) { // We read the header PackFile pf = (PackFile) objIn.readObject(); if (OsConstraint.oneMatchesCurrentSystem(pf.osConstraints)) { // We translate & build the path String path = translatePath(pf.targetPath); File pathFile = new File(path); File dest = pathFile.getParentFile(); if (!dest.exists()) dest.mkdirs(); // We add the path to the log, udata.addFile(path); handler.progress (j, path); //if this file exists and should not be overwritten, check //what to do if ((pathFile.exists ()) && (pf.override != PackFile.OVERRIDE_TRUE)) { boolean overwritefile = false; // don't overwrite file if the user said so if (pf.override != PackFile.OVERRIDE_FALSE) { if (pf.override == PackFile.OVERRIDE_TRUE) { overwritefile = true; } else if (pf.override == PackFile.OVERRIDE_UPDATE) { // check mtime of involved files // (this is not 100% perfect, because the already existing file might // still be modified but the new installed is just a bit newer; we would // need the creation time of the existing file or record with which mtime // it was installed...) overwritefile = (pathFile.lastModified() < pf.mtime); } else { int def_choice = -1; if (pf.override == PackFile.OVERRIDE_ASK_FALSE) def_choice = AbstractUIHandler.ANSWER_NO; if (pf.override == PackFile.OVERRIDE_ASK_TRUE) def_choice = AbstractUIHandler.ANSWER_YES; int answer = handler.askQuestion ( idata.langpack.getString ("InstallPanel.overwrite.title") + pathFile.getName (), idata.langpack.getString ("InstallPanel.overwrite.question") + pathFile.getAbsolutePath(), AbstractUIHandler.CHOICES_YES_NO, def_choice); overwritefile = (answer == AbstractUIHandler.ANSWER_YES); } } if (! overwritefile) { objIn.skip(pf.length); continue; } } // We copy the file out = new FileOutputStream(pathFile); byte[] buffer = new byte[5120]; long bytesCopied = 0; while (bytesCopied < pf.length) { int maxBytes = (pf.length - bytesCopied < buffer.length ? (int) (pf.length - bytesCopied) : buffer.length); int bytesInBuffer = objIn.read(buffer, 0, maxBytes); if (bytesInBuffer == -1) throw new IOException("Unexpected end of stream"); out.write(buffer, 0, bytesInBuffer); bytesCopied += bytesInBuffer; } // Cleanings out.close(); // Set file modification time if specified if (pf.mtime >= 0) pathFile.setLastModified (pf.mtime); // Empty dirs restoring String _n = pathFile.getName(); if (_n.startsWith("izpack-keepme") && _n.endsWith(".tmp")) pathFile.delete(); } else objIn.skip(pf.length); } // Load information about parsable files int numParsables = objIn.readInt(); int k; for (k = 0; k < numParsables; k++) { ParsableFile pf = (ParsableFile) objIn.readObject(); pf.path = translatePath(pf.path); parsables.add(pf); } // Load information about executable files int numExecutables = objIn.readInt(); for (k = 0; k < numExecutables; k++) { ExecutableFile ef = (ExecutableFile) objIn.readObject(); ef.path = translatePath(ef.path); if (null != ef.argList && !ef.argList.isEmpty()) { String arg = null; for (int j = 0; j < ef.argList.size(); j++) { arg = (String) ef.argList.get(j); arg = translatePath(arg); ef.argList.set(j, arg); } } executables.add(ef); if(ef.executionStage == ExecutableFile.UNINSTALL) { udata.addExecutable(ef); } } objIn.close(); } // We use the scripts parser ScriptParser parser = new ScriptParser(parsables, vs); parser.parseFiles(); // We use the file executor FileExecutor executor = new FileExecutor(executables); if (executor.executeFiles(ExecutableFile.POSTINSTALL, handler) != 0) handler.emitError ("File execution failed", "The installation was not completed"); // We put the uninstaller if (idata.info.getWriteUninstaller()) putUninstaller(); // The end :-) handler.stopAction(); } catch (Exception err) { // TODO: finer grained error handling with useful error messages handler.stopAction(); handler.emitError ("An exception was caught", err.toString()); err.printStackTrace (); } instances.remove(instances.indexOf(this)); }
public void run() { instances.add(this); try { // // Initialisations FileOutputStream out = null; ArrayList parsables = new ArrayList(); ArrayList executables = new ArrayList(); List packs = idata.selectedPacks; int npacks = packs.size(); handler.startAction ("Unpacking", npacks); udata = UninstallData.getInstance(); // Specific to the web installers if (idata.kind.equalsIgnoreCase("web") || idata.kind.equalsIgnoreCase("web-kunststoff")) { InputStream kin = getClass().getResourceAsStream("/res/WebInstallers.url"); BufferedReader kreader = new BufferedReader(new InputStreamReader(kin)); jarLocation = kreader.readLine(); } // We unpack the selected packs for (int i = 0; i < npacks; i++) { // We get the pack stream int n = idata.allPacks.indexOf(packs.get(i)); ObjectInputStream objIn = new ObjectInputStream(getPackAsStream(n)); // We unpack the files int nfiles = objIn.readInt(); handler.nextStep (((Pack) packs.get(i)).name, i+1, nfiles); for (int j = 0; j < nfiles; j++) { // We read the header PackFile pf = (PackFile) objIn.readObject(); if (OsConstraint.oneMatchesCurrentSystem(pf.osConstraints)) { // We translate & build the path String path = translatePath(pf.targetPath); File pathFile = new File(path); File dest = pathFile.getParentFile(); if (!dest.exists()) { if (! dest.mkdirs()) { handler.emitError("Error creating directories", "Could not create directory\n"+dest.getPath()); handler.stopAction (); return; } } // We add the path to the log, udata.addFile(path); handler.progress (j, path); //if this file exists and should not be overwritten, check //what to do if ((pathFile.exists ()) && (pf.override != PackFile.OVERRIDE_TRUE)) { boolean overwritefile = false; // don't overwrite file if the user said so if (pf.override != PackFile.OVERRIDE_FALSE) { if (pf.override == PackFile.OVERRIDE_TRUE) { overwritefile = true; } else if (pf.override == PackFile.OVERRIDE_UPDATE) { // check mtime of involved files // (this is not 100% perfect, because the already existing file might // still be modified but the new installed is just a bit newer; we would // need the creation time of the existing file or record with which mtime // it was installed...) overwritefile = (pathFile.lastModified() < pf.mtime); } else { int def_choice = -1; if (pf.override == PackFile.OVERRIDE_ASK_FALSE) def_choice = AbstractUIHandler.ANSWER_NO; if (pf.override == PackFile.OVERRIDE_ASK_TRUE) def_choice = AbstractUIHandler.ANSWER_YES; int answer = handler.askQuestion ( idata.langpack.getString ("InstallPanel.overwrite.title") + pathFile.getName (), idata.langpack.getString ("InstallPanel.overwrite.question") + pathFile.getAbsolutePath(), AbstractUIHandler.CHOICES_YES_NO, def_choice); overwritefile = (answer == AbstractUIHandler.ANSWER_YES); } } if (! overwritefile) { objIn.skip(pf.length); continue; } } // We copy the file out = new FileOutputStream(pathFile); byte[] buffer = new byte[5120]; long bytesCopied = 0; while (bytesCopied < pf.length) { int maxBytes = (pf.length - bytesCopied < buffer.length ? (int) (pf.length - bytesCopied) : buffer.length); int bytesInBuffer = objIn.read(buffer, 0, maxBytes); if (bytesInBuffer == -1) throw new IOException("Unexpected end of stream"); out.write(buffer, 0, bytesInBuffer); bytesCopied += bytesInBuffer; } // Cleanings out.close(); // Set file modification time if specified if (pf.mtime >= 0) pathFile.setLastModified (pf.mtime); // Empty dirs restoring String _n = pathFile.getName(); if (_n.startsWith("izpack-keepme") && _n.endsWith(".tmp")) pathFile.delete(); } else objIn.skip(pf.length); } // Load information about parsable files int numParsables = objIn.readInt(); int k; for (k = 0; k < numParsables; k++) { ParsableFile pf = (ParsableFile) objIn.readObject(); pf.path = translatePath(pf.path); parsables.add(pf); } // Load information about executable files int numExecutables = objIn.readInt(); for (k = 0; k < numExecutables; k++) { ExecutableFile ef = (ExecutableFile) objIn.readObject(); ef.path = translatePath(ef.path); if (null != ef.argList && !ef.argList.isEmpty()) { String arg = null; for (int j = 0; j < ef.argList.size(); j++) { arg = (String) ef.argList.get(j); arg = translatePath(arg); ef.argList.set(j, arg); } } executables.add(ef); if(ef.executionStage == ExecutableFile.UNINSTALL) { udata.addExecutable(ef); } } objIn.close(); } // We use the scripts parser ScriptParser parser = new ScriptParser(parsables, vs); parser.parseFiles(); // We use the file executor FileExecutor executor = new FileExecutor(executables); if (executor.executeFiles(ExecutableFile.POSTINSTALL, handler) != 0) handler.emitError ("File execution failed", "The installation was not completed"); // We put the uninstaller if (idata.info.getWriteUninstaller()) putUninstaller(); // The end :-) handler.stopAction(); } catch (Exception err) { // TODO: finer grained error handling with useful error messages handler.stopAction(); handler.emitError ("An error occured", err.toString()); err.printStackTrace (); } finally { instances.remove(instances.indexOf(this)); } }
diff --git a/source/org/jivesoftware/smackx/debugger/EnhancedDebuggerWindow.java b/source/org/jivesoftware/smackx/debugger/EnhancedDebuggerWindow.java index 672c2bdd..fe873528 100644 --- a/source/org/jivesoftware/smackx/debugger/EnhancedDebuggerWindow.java +++ b/source/org/jivesoftware/smackx/debugger/EnhancedDebuggerWindow.java @@ -1,340 +1,340 @@ /** * $RCSfile$ * $Revision$ * $Date$ * * Copyright (C) 2002-2003 Jive Software. All rights reserved. * ==================================================================== * The Jive Software License (based on Apache Software License, Version 1.1) * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by * Jive Software (http://www.jivesoftware.com)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Smack" and "Jive Software" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please * contact [email protected]. * * 5. Products derived from this software may not be called "Smack", * nor may "Smack" appear in their name, without prior written * permission of Jive Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL JIVE SOFTWARE OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== */ package org.jivesoftware.smackx.debugger; import java.awt.*; import java.awt.event.*; import java.net.*; import java.util.*; import javax.swing.*; import org.jivesoftware.smack.SmackConfiguration; import org.jivesoftware.smack.provider.ProviderManager; /** * The EnhancedDebuggerWindow is the main debug window that will show all the EnhancedDebuggers. * For each connection to debug there will be an EnhancedDebugger that will be shown in the * EnhancedDebuggerWindow.<p> * * This class also provides information about Smack like for example the Smack version and the * installed providers. * * @author Gaston Dombiak */ class EnhancedDebuggerWindow { private static EnhancedDebuggerWindow instance; private static ImageIcon connectionCreatedIcon; private static ImageIcon connectionActiveIcon; private static ImageIcon connectionClosedIcon; private static ImageIcon connectionClosedOnErrorIcon; { URL url; url = Thread.currentThread().getContextClassLoader().getResource( "images/trafficlight_off.png"); if (url != null) { connectionCreatedIcon = new ImageIcon(url); } url = Thread.currentThread().getContextClassLoader().getResource( "images/trafficlight_green.png"); if (url != null) { connectionActiveIcon = new ImageIcon(url); } url = Thread.currentThread().getContextClassLoader().getResource( "images/trafficlight_red.png"); if (url != null) { connectionClosedIcon = new ImageIcon(url); } url = Thread.currentThread().getContextClassLoader().getResource("images/warning.png"); if (url != null) { connectionClosedOnErrorIcon = new ImageIcon(url); } } private JFrame frame = null; private JTabbedPane tabbedPane = null; private java.util.List debuggers = new ArrayList(); private EnhancedDebuggerWindow() { } /** * Returns the unique EnhancedDebuggerWindow instance available in the system. * * @return the unique EnhancedDebuggerWindow instance */ private static EnhancedDebuggerWindow getInstance() { if (instance == null) { instance = new EnhancedDebuggerWindow(); } return instance; } /** * Adds the new specified debugger to the list of debuggers to show in the main window. * * @param debugger the new debugger to show in the debug window */ synchronized static void addDebugger(EnhancedDebugger debugger) { getInstance().showNewDebugger(debugger); } /** * Shows the new debugger in the debug window. * * @param debugger the new debugger to show */ private void showNewDebugger(EnhancedDebugger debugger) { if (frame == null) { createDebug(); } debugger.tabbedPane.setName("Connection_" + tabbedPane.getComponentCount()); tabbedPane.add(debugger.tabbedPane, tabbedPane.getComponentCount() - 1); tabbedPane.setIconAt(tabbedPane.indexOfComponent(debugger.tabbedPane), connectionCreatedIcon); frame.setTitle( "Smack Debug Window -- Total connections: " + (tabbedPane.getComponentCount() - 1)); // Keep the added debugger for later access debuggers.add(debugger); } /** * Notification that a user has logged in to the server. A new title will be set * to the tab of the given debugger. * * @param debugger the debugger whose connection logged in to the server * @param user the user@host/resource that has just logged in */ synchronized static void userHasLogged(EnhancedDebugger debugger, String user) { int index = getInstance().tabbedPane.indexOfComponent(debugger.tabbedPane); getInstance().tabbedPane.setTitleAt( index, user); getInstance().tabbedPane.setIconAt( index, connectionActiveIcon); } /** * Notification that the connection was properly closed. * * @param debugger the debugger whose connection was properly closed. */ synchronized static void connectionClosed(EnhancedDebugger debugger) { getInstance().tabbedPane.setIconAt( getInstance().tabbedPane.indexOfComponent(debugger.tabbedPane), connectionClosedIcon); } /** * Notification that the connection was closed due to an exception. * * @param debugger the debugger whose connection was closed due to an exception. * @param e the exception. */ synchronized static void connectionClosedOnError(EnhancedDebugger debugger, Exception e) { int index = getInstance().tabbedPane.indexOfComponent(debugger.tabbedPane); getInstance().tabbedPane.setToolTipTextAt( index, "Connection closed due to the exception: " + e.getMessage()); getInstance().tabbedPane.setIconAt( index, connectionClosedOnErrorIcon); } /** * Creates the main debug window that provides information about Smack and also shows * a tab panel for each connection that is being debugged. */ private void createDebug() { frame = new JFrame("Smack Debug Window"); // Add listener for window closing event frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent evt) { rootWindowClosing(evt); } }); // We'll arrange the UI into tabs. The last tab contains Smack's information. // All the connection debugger tabs will be shown before the Smack info tab. tabbedPane = new JTabbedPane(); // Create the Smack info panel JPanel informationPanel = new JPanel(); informationPanel.setLayout(new BoxLayout(informationPanel, BoxLayout.Y_AXIS)); // Add the Smack version label JPanel versionPanel = new JPanel(); versionPanel.setLayout(new BoxLayout(versionPanel, BoxLayout.X_AXIS)); versionPanel.setMaximumSize(new Dimension(2000, 31)); versionPanel.add(new JLabel(" Smack version: ")); - JFormattedTextField field = new JFormattedTextField(SmackConfiguration.getVersionNumber()); + JFormattedTextField field = new JFormattedTextField(SmackConfiguration.getVersion()); field.setEditable(false); field.setBorder(null); versionPanel.add(field); informationPanel.add(versionPanel); // Add the list of installed IQ Providers JPanel iqProvidersPanel = new JPanel(); iqProvidersPanel.setLayout(new GridLayout(1, 1)); iqProvidersPanel.setBorder(BorderFactory.createTitledBorder("Installed IQ Providers")); Vector providers = new Vector(); for (Iterator it = ProviderManager.getIQProviders(); it.hasNext();) { Object provider = it.next(); providers.add( (provider.getClass() == Class.class ? provider : provider.getClass().getName())); } JList list = new JList(providers); iqProvidersPanel.add(new JScrollPane(list)); informationPanel.add(iqProvidersPanel); // Add the list of installed Extension Providers JPanel extensionProvidersPanel = new JPanel(); extensionProvidersPanel.setLayout(new GridLayout(1, 1)); extensionProvidersPanel.setBorder(BorderFactory.createTitledBorder("Installed Extension Providers")); providers = new Vector(); for (Iterator it = ProviderManager.getExtensionProviders(); it.hasNext();) { Object provider = it.next(); providers.add( (provider.getClass() == Class.class ? provider : provider.getClass().getName())); } list = new JList(providers); extensionProvidersPanel.add(new JScrollPane(list)); informationPanel.add(extensionProvidersPanel); tabbedPane.add("Smack Info", informationPanel); // Add pop-up menu. JPopupMenu menu = new JPopupMenu(); JMenuItem menuItem = new JMenuItem("Close"); menuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Remove the selected tab pane if it's not the Smack info pane if (tabbedPane.getSelectedIndex() < tabbedPane.getComponentCount() - 1) { int index = tabbedPane.getSelectedIndex(); // Notify to the debugger to stop debugging EnhancedDebugger debugger = (EnhancedDebugger)debuggers.get(index); debugger.cancel(); // Remove the debugger from the root window tabbedPane.remove(debugger.tabbedPane); debuggers.remove(debugger); // Update the root window title frame.setTitle( "Smack Debug Window -- Total connections: " + (tabbedPane.getComponentCount() - 1)); } } }); menu.add(menuItem); // Add listener to the text area so the popup menu can come up. tabbedPane.addMouseListener(new PopupListener(menu)); frame.getContentPane().add(tabbedPane); frame.setSize(650, 400); frame.setVisible(true); } /** * Notification that the root window is closing. Stop listening for received and * transmitted packets in all the debugged connections. * * @param evt the event that indicates that the root window is closing */ public void rootWindowClosing(WindowEvent evt) { // Notify to all the debuggers to stop debugging for (Iterator it = debuggers.iterator(); it.hasNext();) { EnhancedDebugger debugger = (EnhancedDebugger)it.next(); debugger.cancel(); } // Release any reference to the debuggers debuggers.removeAll(debuggers); // Release the default instance instance = null; } /** * Listens for debug window popup dialog events. */ private class PopupListener extends MouseAdapter { JPopupMenu popup; PopupListener(JPopupMenu popupMenu) { popup = popupMenu; } public void mousePressed(MouseEvent e) { maybeShowPopup(e); } public void mouseReleased(MouseEvent e) { maybeShowPopup(e); } private void maybeShowPopup(MouseEvent e) { if (e.isPopupTrigger()) { popup.show(e.getComponent(), e.getX(), e.getY()); } } } }
true
true
private void createDebug() { frame = new JFrame("Smack Debug Window"); // Add listener for window closing event frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent evt) { rootWindowClosing(evt); } }); // We'll arrange the UI into tabs. The last tab contains Smack's information. // All the connection debugger tabs will be shown before the Smack info tab. tabbedPane = new JTabbedPane(); // Create the Smack info panel JPanel informationPanel = new JPanel(); informationPanel.setLayout(new BoxLayout(informationPanel, BoxLayout.Y_AXIS)); // Add the Smack version label JPanel versionPanel = new JPanel(); versionPanel.setLayout(new BoxLayout(versionPanel, BoxLayout.X_AXIS)); versionPanel.setMaximumSize(new Dimension(2000, 31)); versionPanel.add(new JLabel(" Smack version: ")); JFormattedTextField field = new JFormattedTextField(SmackConfiguration.getVersionNumber()); field.setEditable(false); field.setBorder(null); versionPanel.add(field); informationPanel.add(versionPanel); // Add the list of installed IQ Providers JPanel iqProvidersPanel = new JPanel(); iqProvidersPanel.setLayout(new GridLayout(1, 1)); iqProvidersPanel.setBorder(BorderFactory.createTitledBorder("Installed IQ Providers")); Vector providers = new Vector(); for (Iterator it = ProviderManager.getIQProviders(); it.hasNext();) { Object provider = it.next(); providers.add( (provider.getClass() == Class.class ? provider : provider.getClass().getName())); } JList list = new JList(providers); iqProvidersPanel.add(new JScrollPane(list)); informationPanel.add(iqProvidersPanel); // Add the list of installed Extension Providers JPanel extensionProvidersPanel = new JPanel(); extensionProvidersPanel.setLayout(new GridLayout(1, 1)); extensionProvidersPanel.setBorder(BorderFactory.createTitledBorder("Installed Extension Providers")); providers = new Vector(); for (Iterator it = ProviderManager.getExtensionProviders(); it.hasNext();) { Object provider = it.next(); providers.add( (provider.getClass() == Class.class ? provider : provider.getClass().getName())); } list = new JList(providers); extensionProvidersPanel.add(new JScrollPane(list)); informationPanel.add(extensionProvidersPanel); tabbedPane.add("Smack Info", informationPanel); // Add pop-up menu. JPopupMenu menu = new JPopupMenu(); JMenuItem menuItem = new JMenuItem("Close"); menuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Remove the selected tab pane if it's not the Smack info pane if (tabbedPane.getSelectedIndex() < tabbedPane.getComponentCount() - 1) { int index = tabbedPane.getSelectedIndex(); // Notify to the debugger to stop debugging EnhancedDebugger debugger = (EnhancedDebugger)debuggers.get(index); debugger.cancel(); // Remove the debugger from the root window tabbedPane.remove(debugger.tabbedPane); debuggers.remove(debugger); // Update the root window title frame.setTitle( "Smack Debug Window -- Total connections: " + (tabbedPane.getComponentCount() - 1)); } } }); menu.add(menuItem); // Add listener to the text area so the popup menu can come up. tabbedPane.addMouseListener(new PopupListener(menu)); frame.getContentPane().add(tabbedPane); frame.setSize(650, 400); frame.setVisible(true); }
private void createDebug() { frame = new JFrame("Smack Debug Window"); // Add listener for window closing event frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent evt) { rootWindowClosing(evt); } }); // We'll arrange the UI into tabs. The last tab contains Smack's information. // All the connection debugger tabs will be shown before the Smack info tab. tabbedPane = new JTabbedPane(); // Create the Smack info panel JPanel informationPanel = new JPanel(); informationPanel.setLayout(new BoxLayout(informationPanel, BoxLayout.Y_AXIS)); // Add the Smack version label JPanel versionPanel = new JPanel(); versionPanel.setLayout(new BoxLayout(versionPanel, BoxLayout.X_AXIS)); versionPanel.setMaximumSize(new Dimension(2000, 31)); versionPanel.add(new JLabel(" Smack version: ")); JFormattedTextField field = new JFormattedTextField(SmackConfiguration.getVersion()); field.setEditable(false); field.setBorder(null); versionPanel.add(field); informationPanel.add(versionPanel); // Add the list of installed IQ Providers JPanel iqProvidersPanel = new JPanel(); iqProvidersPanel.setLayout(new GridLayout(1, 1)); iqProvidersPanel.setBorder(BorderFactory.createTitledBorder("Installed IQ Providers")); Vector providers = new Vector(); for (Iterator it = ProviderManager.getIQProviders(); it.hasNext();) { Object provider = it.next(); providers.add( (provider.getClass() == Class.class ? provider : provider.getClass().getName())); } JList list = new JList(providers); iqProvidersPanel.add(new JScrollPane(list)); informationPanel.add(iqProvidersPanel); // Add the list of installed Extension Providers JPanel extensionProvidersPanel = new JPanel(); extensionProvidersPanel.setLayout(new GridLayout(1, 1)); extensionProvidersPanel.setBorder(BorderFactory.createTitledBorder("Installed Extension Providers")); providers = new Vector(); for (Iterator it = ProviderManager.getExtensionProviders(); it.hasNext();) { Object provider = it.next(); providers.add( (provider.getClass() == Class.class ? provider : provider.getClass().getName())); } list = new JList(providers); extensionProvidersPanel.add(new JScrollPane(list)); informationPanel.add(extensionProvidersPanel); tabbedPane.add("Smack Info", informationPanel); // Add pop-up menu. JPopupMenu menu = new JPopupMenu(); JMenuItem menuItem = new JMenuItem("Close"); menuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Remove the selected tab pane if it's not the Smack info pane if (tabbedPane.getSelectedIndex() < tabbedPane.getComponentCount() - 1) { int index = tabbedPane.getSelectedIndex(); // Notify to the debugger to stop debugging EnhancedDebugger debugger = (EnhancedDebugger)debuggers.get(index); debugger.cancel(); // Remove the debugger from the root window tabbedPane.remove(debugger.tabbedPane); debuggers.remove(debugger); // Update the root window title frame.setTitle( "Smack Debug Window -- Total connections: " + (tabbedPane.getComponentCount() - 1)); } } }); menu.add(menuItem); // Add listener to the text area so the popup menu can come up. tabbedPane.addMouseListener(new PopupListener(menu)); frame.getContentPane().add(tabbedPane); frame.setSize(650, 400); frame.setVisible(true); }
diff --git a/src/main/java/com/jayway/maven/plugins/android/phase04processclasses/ProguardMojo.java b/src/main/java/com/jayway/maven/plugins/android/phase04processclasses/ProguardMojo.java index ceb46e3e..10fcb31f 100644 --- a/src/main/java/com/jayway/maven/plugins/android/phase04processclasses/ProguardMojo.java +++ b/src/main/java/com/jayway/maven/plugins/android/phase04processclasses/ProguardMojo.java @@ -1,716 +1,716 @@ package com.jayway.maven.plugins.android.phase04processclasses; import com.jayway.maven.plugins.android.AbstractAndroidMojo; import com.jayway.maven.plugins.android.CommandExecutor; import com.jayway.maven.plugins.android.ExecutionException; import com.jayway.maven.plugins.android.config.ConfigHandler; import com.jayway.maven.plugins.android.config.ConfigPojo; import com.jayway.maven.plugins.android.config.PullParameter; import com.jayway.maven.plugins.android.configuration.Proguard; import org.apache.commons.lang.StringUtils; import org.apache.maven.RepositoryUtils; import org.apache.maven.artifact.Artifact; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.eclipse.aether.artifact.DefaultArtifact; import org.eclipse.aether.util.artifact.JavaScopes; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; /** * Processes both application and dependency classes using the ProGuard byte code obfuscator, * minimzer, and optimizer. For more information, see https://proguard.sourceforge.net. * * @author Jonson * @author Matthias Kaeppler * @author Manfred Moser * @author Michal Harakal * @goal proguard * @phase process-classes * @requiresDependencyResolution compile */ public class ProguardMojo extends AbstractAndroidMojo { /** * <p> * ProGuard configuration. ProGuard is disabled by default. Set the skip parameter to false to activate proguard. * A complete configuartion can include any of the following: * </p> * <p/> * <pre> * &lt;proguard&gt; * &lt;skip&gt;true|false&lt;/skip&gt; * &lt;config&gt;proguard.cfg&lt;/config&gt; * &lt;configs&gt; * &lt;config&gt;${env.ANDROID_HOME}/tools/proguard/proguard-android.txt&lt;/config&gt; * &lt;/configs&gt; * &lt;proguardJarPath&gt;someAbsolutePathToProguardJar&lt;/proguardJarPath&gt; * &lt;filterMavenDescriptor&gt;true|false&lt;/filterMavenDescriptor&gt; * &lt;filterManifest&gt;true|false&lt;/filterManifest&gt; * &lt;jvmArguments&gt; * &lt;jvmArgument&gt;-Xms256m&lt;/jvmArgument&gt; * &lt;jvmArgument&gt;-Xmx512m&lt;/jvmArgument&gt; * &lt;/jvmArguments&gt; * &lt;/proguard&gt; * </pre> * <p> * A good practice is to create a release profile in your POM, in which you enable ProGuard. * ProGuard should be disabled for development builds, since it obfuscates class and field * names, and it may interfere with test projects that rely on your application classes. * All parameters can be overridden in profiles or the the proguard* properties. Default values apply and are * documented with these properties. * </p> * * @parameter */ @ConfigPojo protected Proguard proguard; /** * Whether ProGuard is enabled or not. Defaults to true. * * @parameter expression="${android.proguard.skip}" * @optional */ private Boolean proguardSkip; @PullParameter( defaultValue = "true" ) private Boolean parsedSkip; /** * Path to the ProGuard configuration file (relative to project root). Defaults to "proguard.cfg" * * @parameter expression="${android.proguard.config}" * @optional */ private String proguardConfig; @PullParameter( defaultValue = "proguard.cfg" ) private String parsedConfig; /** * Additional ProGuard configuration files (relative to project root). * * @parameter expression="${android.proguard.configs}" * @optional */ private String[] proguardConfigs; @PullParameter( defaultValueGetterMethod = "getDefaultProguardConfigs" ) private String[] parsedConfigs; /** * Additional ProGuard options * * @parameter expression="${android.proguard.options}" * @optional */ private String[] proguardOptions; @PullParameter( defaultValueGetterMethod = "getDefaultProguardOptions" ) private String[] parsedOptions; /** * Path to the proguard jar and therefore version of proguard to be used. By default this will load the jar from * the Android SDK install. Overriding it with an absolute path allows you to use a newer or custom proguard * version.. * <p/> * You can also reference an external Proguard version as a plugin dependency like this: * <pre> * &lt;plugin&gt; * &lt;groupId&gt;com.jayway.maven.plugins.android.generation2&lt;/groupId&gt; * &lt;artifactId&gt;android-maven-plugin&lt;/artifactId&gt; * &lt;dependencies&gt; * &lt;dependency&gt; * &lt;groupId&gt;net.sf.proguard&lt;/groupId&gt; * &lt;artifactId&gt;proguard-base&lt;/artifactId&gt; * &lt;version&gt;4.7&lt;/version&gt; * &lt;/dependency&gt; * &lt;/dependencies&gt; * </pre> * <p/> * which will download and use Proguard 4.7 as deployed to the Central Repository. * * @parameter expression="${android.proguard.proguardJarPath} * @optional */ private String proguardProguardJarPath; @PullParameter( defaultValueGetterMethod = "getProguardJarPath" ) private String parsedProguardJarPath; /** * Path relative to the project's build directory (target) where proguard puts folowing files: * <p/> * <ul> * <li>dump.txt</li> * <li>seeds.txt</li> * <li>usage.txt</li> * <li>mapping.txt</li> * </ul> * <p/> * You can define the directory like this: * <pre> * &lt;proguard&gt; * &lt;skip&gt;false&lt;/skip&gt; * &lt;config&gt;proguard.cfg&lt;/config&gt; * &lt;outputDirectory&gt;my_proguard&lt;/outputDirectory&gt; * &lt;/proguard&gt; * </pre> * <p/> * Output directory is defined relatively so it could be also outside of the target directory. * <p/> * * @parameter expression="${android.proguard.outputDirectory}" default-value="proguard" * @optional */ private String outputDirectory; @PullParameter( defaultValue = "proguard" ) private String parsedOutputDirectory; /** * Extra JVM Arguments. Using these you can e.g. increase memory for the jvm running the build. * Defaults to "-Xmx512M". * * @parameter expression="${android.proguard.jvmArguments}" * @optional */ private String[] proguardJvmArguments; @PullParameter( defaultValueGetterMethod = "getDefaultJvmArguments" ) private String[] parsedJvmArguments; /** * If set to true will add a filter to remove META-INF/maven/* files. Defaults to false. * * @parameter expression="${android.proguard.filterMavenDescriptor}" * @optional */ private Boolean proguardFilterMavenDescriptor; @PullParameter( defaultValue = "true" ) private Boolean parsedFilterMavenDescriptor; /** * If set to true will add a filter to remove META-INF/MANIFEST.MF files. Defaults to false. * * @parameter expression="${android.proguard.filterManifest}" * @optional */ private Boolean proguardFilterManifest; @PullParameter( defaultValue = "true" ) private Boolean parsedFilterManifest; /** * If set to true JDK jars will be included as library jars and corresponding filters * will be applied to android.jar. Defaults to true. * @parameter expression="${android.proguard.includeJdkLibs}" */ private Boolean includeJdkLibs; @PullParameter( defaultValue = "true" ) private Boolean parsedIncludeJdkLibs; /** * The plugin dependencies. * * @parameter expression="${plugin.artifacts}" * @required * @readonly */ protected List<Artifact> pluginDependencies; public static final String PROGUARD_OBFUSCATED_JAR = "proguard-obfuscated.jar"; private static final Collection<String> ANDROID_LIBRARY_EXCLUDED_FILTER = Arrays .asList( "org/xml/**", "org/w3c/**", "java/**", "javax/**" ); private static final Collection<String> MAVEN_DESCRIPTOR = Arrays.asList( "META-INF/maven/**" ); private static final Collection<String> META_INF_MANIFEST = Arrays.asList( "META-INF/MANIFEST.MF" ); /** * For Proguard is required only jar type dependencies, all other like .so or .apklib can be skipped. */ private static final String USED_DEPENDENCY_TYPE = "jar"; private Collection<String> globalInJarExcludes = new HashSet<String>(); private List<Artifact> artifactBlacklist = new LinkedList<Artifact>(); private List<Artifact> artifactsToShift = new LinkedList<Artifact>(); private List<ProGuardInput> inJars = new LinkedList<ProguardMojo.ProGuardInput>(); private List<ProGuardInput> libraryJars = new LinkedList<ProguardMojo.ProGuardInput>(); private File javaHomeDir; private File javaLibDir; private File altJavaLibDir; private static class ProGuardInput { private String path; private Collection<String> excludedFilter; public ProGuardInput( String path, Collection<String> excludedFilter ) { this.path = path; this.excludedFilter = excludedFilter; } public String toCommandLine() { if ( excludedFilter != null && ! excludedFilter.isEmpty() ) { StringBuilder sb = new StringBuilder( path ); sb.append( '(' ); for ( Iterator<String> it = excludedFilter.iterator(); it.hasNext(); ) { sb.append( '!' ).append( it.next() ); if ( it.hasNext() ) { sb.append( ',' ); } } sb.append( ')' ); return sb.toString(); } else { return "\'" + path + "\'"; } } } @Override public void execute() throws MojoExecutionException, MojoFailureException { ConfigHandler configHandler = new ConfigHandler( this ); configHandler.parseConfiguration(); if ( ! parsedSkip ) { executeProguard(); } } private void executeProguard() throws MojoExecutionException { final File proguardDir = new File( project.getBuild().getDirectory(), parsedOutputDirectory ); if ( ! proguardDir.exists() && ! proguardDir.mkdir() ) { throw new MojoExecutionException( "Cannot create proguard output directory" ); } else { if ( proguardDir.exists() && ! proguardDir.isDirectory() ) { throw new MojoExecutionException( "Non-directory exists at " + proguardDir.getAbsolutePath() ); } } CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor(); executor.setLogger( this.getLog() ); List<String> commands = new ArrayList<String>(); collectJvmArguments( commands ); commands.add( "-jar" ); commands.add( parsedProguardJarPath ); commands.add( "@" + parsedConfig ); for ( String config : parsedConfigs ) { commands.add( "@" + config ); } if ( proguardFile != null ) { commands.add( "@" + proguardFile.getAbsolutePath() ); } collectInputFiles( commands ); commands.add( "-outjars" ); commands.add( "'" + project.getBuild().getDirectory() + File.separator + PROGUARD_OBFUSCATED_JAR + "'" ); commands.add( "-dump" ); commands.add( "'" + proguardDir + File.separator + "dump.txt'" ); commands.add( "-printseeds" ); commands.add( "'" + proguardDir + File.separator + "seeds.txt'" ); commands.add( "-printusage" ); commands.add( "'" + proguardDir + File.separator + "usage.txt'" ); commands.add( "-printmapping" ); commands.add( "'" + proguardDir + File.separator + "mapping.txt'" ); - commands.addAll( Arrays.asList( proguardOptions ) ); + commands.addAll( Arrays.asList( parsedOptions ) ); final String javaExecutable = getJavaExecutable().getAbsolutePath(); getLog().info( javaExecutable + " " + commands.toString() ); try { executor.executeCommand( javaExecutable, commands, project.getBasedir(), false ); } catch ( ExecutionException e ) { throw new MojoExecutionException( "", e ); } } /** * Convert the jvm arguments in parsedJvmArguments as populated by the config in format as needed by the java * command. Also preserve backwards compatibility in terms of dashes required or not.. * * @param commands */ private void collectJvmArguments( List<String> commands ) { if ( parsedJvmArguments != null ) { for ( String jvmArgument : parsedJvmArguments ) { // preserve backward compatibility allowing argument with or without dash (e.g. // Xmx512m as well as -Xmx512m should work) (see // http://code.google.com/p/maven-android-plugin/issues/detail?id=153) if ( ! jvmArgument.startsWith( "-" ) ) { jvmArgument = "-" + jvmArgument; } commands.add( jvmArgument ); } } } private void collectInputFiles( List<String> commands ) { // commons-logging breaks everything horribly, so we skip it from the program // dependencies and declare it to be a library dependency instead skipArtifact( "commons-logging", "commons-logging", true ); collectProgramInputFiles(); for ( ProGuardInput injar : inJars ) { commands.add( "-injars" ); commands.add( injar.toCommandLine() ); } collectLibraryInputFiles(); for ( ProGuardInput libraryjar : libraryJars ) { commands.add( "-libraryjars" ); commands.add( libraryjar.toCommandLine() ); } } /** * Figure out the full path to the current java executable. * * @return the full path to the current java executable. */ private static File getJavaExecutable() { final String javaHome = System.getProperty( "java.home" ); final String slash = File.separator; return new File( javaHome + slash + "bin" + slash + "java" ); } private void skipArtifact( String groupId, String artifactId, boolean shiftToLibraries ) { artifactBlacklist.add( RepositoryUtils.toArtifact( new DefaultArtifact( groupId, artifactId, null, null ) ) ); if ( shiftToLibraries ) { artifactsToShift .add( RepositoryUtils.toArtifact( new DefaultArtifact( groupId, artifactId, null, null ) ) ); } } private boolean isBlacklistedArtifact( Artifact artifact ) { for ( Artifact artifactToSkip : artifactBlacklist ) { if ( artifactToSkip.getGroupId().equals( artifact.getGroupId() ) && artifactToSkip.getArtifactId() .equals( artifact.getArtifactId() ) ) { return true; } } return false; } private boolean isShiftedArtifact( Artifact artifact ) { for ( Artifact artifactToShift : artifactsToShift ) { if ( artifactToShift.getGroupId().equals( artifact.getGroupId() ) && artifactToShift.getArtifactId() .equals( artifact.getArtifactId() ) ) { return true; } } return false; } private void collectProgramInputFiles() { if ( parsedFilterManifest ) { globalInJarExcludes.addAll( META_INF_MANIFEST ); } if ( parsedFilterMavenDescriptor ) { globalInJarExcludes.addAll( MAVEN_DESCRIPTOR ); } // we first add the application's own class files addInJar( project.getBuild().getOutputDirectory() ); // we then add all its dependencies (incl. transitive ones), unless they're blacklisted for ( Artifact artifact : getAllRelevantDependencyArtifacts() ) { if ( isBlacklistedArtifact( artifact ) || !USED_DEPENDENCY_TYPE.equals( artifact.getType() ) ) { continue; } addInJar( artifact.getFile().getAbsolutePath(), globalInJarExcludes ); } } private void addInJar( String path, Collection<String> filterExpression ) { inJars.add( new ProGuardInput( path, filterExpression ) ); } private void addInJar( String path ) { addInJar( path, null ); } private void addLibraryJar( String path, Collection<String> filterExpression ) { libraryJars.add( new ProGuardInput( path, filterExpression ) ); } private void addLibraryJar( String path ) { addLibraryJar( path, null ); } private void collectLibraryInputFiles() { if ( parsedIncludeJdkLibs ) { // we have to add the Java framework classes to the library JARs, since they are not // distributed with the JAR on Central, and since we'll strip them out of the android.jar // that is shipped with the SDK (since that is not a complete Java distribution) File rtJar = getJVMLibrary( "rt.jar" ); if ( rtJar == null ) { rtJar = getJVMLibrary( "classes.jar" ); } if ( rtJar != null ) { addLibraryJar( rtJar.getPath() ); } // we also need to add the JAR containing e.g. javax.servlet File jsseJar = getJVMLibrary( "jsse.jar" ); if ( jsseJar != null ) { addLibraryJar( jsseJar.getPath() ); } // and the javax.crypto stuff File jceJar = getJVMLibrary( "jce.jar" ); if ( jceJar != null ) { addLibraryJar( jceJar.getPath() ); } } // we treat any dependencies with provided scope as library JARs for ( Artifact artifact : project.getArtifacts() ) { if ( artifact.getScope().equals( JavaScopes.PROVIDED ) ) { if ( artifact.getArtifactId().equals( "android" ) && parsedIncludeJdkLibs ) { addLibraryJar( artifact.getFile().getAbsolutePath(), ANDROID_LIBRARY_EXCLUDED_FILTER ); } else { addLibraryJar( artifact.getFile().getAbsolutePath() ); } } else { if ( isShiftedArtifact( artifact ) ) { // this is a blacklisted artifact that should be processed as a library instead addLibraryJar( artifact.getFile().getAbsolutePath() ); } } } } /** * Get the path to the proguard jar. * * @return * @throws MojoExecutionException */ private String getProguardJarPath() throws MojoExecutionException { String proguardJarPath = getProguardJarPathFromDependencies(); if ( StringUtils.isEmpty( proguardJarPath ) ) { File proguardJarPathFile = new File( getAndroidSdk().getToolsPath(), "proguard/lib/proguard.jar" ); return proguardJarPathFile.getAbsolutePath(); } return proguardJarPath; } private String getProguardJarPathFromDependencies() throws MojoExecutionException { Artifact proguardArtifact = null; int proguardArtifactDistance = - 1; for ( Artifact artifact : pluginDependencies ) { getLog().debug( "pluginArtifact: " + artifact.getFile() ); if ( ( "proguard".equals( artifact.getArtifactId() ) ) || ( "proguard-base" .equals( artifact.getArtifactId() ) ) ) { int distance = artifact.getDependencyTrail().size(); getLog().debug( "proguard DependencyTrail: " + distance ); if ( proguardArtifactDistance == - 1 ) { proguardArtifact = artifact; proguardArtifactDistance = distance; } else { if ( distance < proguardArtifactDistance ) { proguardArtifact = artifact; proguardArtifactDistance = distance; } } } } if ( proguardArtifact != null ) { getLog().debug( "proguardArtifact: " + proguardArtifact.getFile() ); return proguardArtifact.getFile().getAbsoluteFile().toString(); } else { return null; } } /** * Get the default JVM arguments for the proguard invocation. * * @return * @see #parsedJvmArguments */ private String[] getDefaultJvmArguments() { return new String[]{ "-Xmx512M" }; } /** * Get the default ProGuard config files. * * @return * @see #parsedConfigs */ private String[] getDefaultProguardConfigs() { return new String[0]; } /** * Get the default ProGuard options. * * @return * @see #parsedOptions */ private String[] getDefaultProguardOptions() { return new String[0]; } /** * Finds a library file in either the primary or alternate lib directory. * @param fileName The base name of the file. * @return Either a canonical filename, or {@code null} if not found. */ private File getJVMLibrary( String fileName ) { File libFile = new File( getJavaLibDir(), fileName ); if ( !libFile.exists() ) { libFile = new File( getAltJavaLibDir(), fileName ); if ( !libFile.exists() ) { libFile = null; } } return libFile; } /** * Determines the java.home directory. * @return The java.home directory, as a File. */ private File getJavaHomeDir() { if ( javaHomeDir == null ) { javaHomeDir = new File( System.getProperty( "java.home" ) ); } return javaHomeDir; } /** * Determines the primary JVM library location. * @return The primary library directory, as a File. */ private File getJavaLibDir() { if ( javaLibDir == null ) { javaLibDir = new File( getJavaHomeDir(), "lib" ); } return javaLibDir; } /** * Determines the alternate JVM library location (applies with older * MacOSX JVMs). * @return The alternate JVM library location, as a File. */ private File getAltJavaLibDir() { if ( altJavaLibDir == null ) { altJavaLibDir = new File( getJavaHomeDir().getParent(), "Classes" ); } return altJavaLibDir; } }
true
true
private void executeProguard() throws MojoExecutionException { final File proguardDir = new File( project.getBuild().getDirectory(), parsedOutputDirectory ); if ( ! proguardDir.exists() && ! proguardDir.mkdir() ) { throw new MojoExecutionException( "Cannot create proguard output directory" ); } else { if ( proguardDir.exists() && ! proguardDir.isDirectory() ) { throw new MojoExecutionException( "Non-directory exists at " + proguardDir.getAbsolutePath() ); } } CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor(); executor.setLogger( this.getLog() ); List<String> commands = new ArrayList<String>(); collectJvmArguments( commands ); commands.add( "-jar" ); commands.add( parsedProguardJarPath ); commands.add( "@" + parsedConfig ); for ( String config : parsedConfigs ) { commands.add( "@" + config ); } if ( proguardFile != null ) { commands.add( "@" + proguardFile.getAbsolutePath() ); } collectInputFiles( commands ); commands.add( "-outjars" ); commands.add( "'" + project.getBuild().getDirectory() + File.separator + PROGUARD_OBFUSCATED_JAR + "'" ); commands.add( "-dump" ); commands.add( "'" + proguardDir + File.separator + "dump.txt'" ); commands.add( "-printseeds" ); commands.add( "'" + proguardDir + File.separator + "seeds.txt'" ); commands.add( "-printusage" ); commands.add( "'" + proguardDir + File.separator + "usage.txt'" ); commands.add( "-printmapping" ); commands.add( "'" + proguardDir + File.separator + "mapping.txt'" ); commands.addAll( Arrays.asList( proguardOptions ) ); final String javaExecutable = getJavaExecutable().getAbsolutePath(); getLog().info( javaExecutable + " " + commands.toString() ); try { executor.executeCommand( javaExecutable, commands, project.getBasedir(), false ); } catch ( ExecutionException e ) { throw new MojoExecutionException( "", e ); } }
private void executeProguard() throws MojoExecutionException { final File proguardDir = new File( project.getBuild().getDirectory(), parsedOutputDirectory ); if ( ! proguardDir.exists() && ! proguardDir.mkdir() ) { throw new MojoExecutionException( "Cannot create proguard output directory" ); } else { if ( proguardDir.exists() && ! proguardDir.isDirectory() ) { throw new MojoExecutionException( "Non-directory exists at " + proguardDir.getAbsolutePath() ); } } CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor(); executor.setLogger( this.getLog() ); List<String> commands = new ArrayList<String>(); collectJvmArguments( commands ); commands.add( "-jar" ); commands.add( parsedProguardJarPath ); commands.add( "@" + parsedConfig ); for ( String config : parsedConfigs ) { commands.add( "@" + config ); } if ( proguardFile != null ) { commands.add( "@" + proguardFile.getAbsolutePath() ); } collectInputFiles( commands ); commands.add( "-outjars" ); commands.add( "'" + project.getBuild().getDirectory() + File.separator + PROGUARD_OBFUSCATED_JAR + "'" ); commands.add( "-dump" ); commands.add( "'" + proguardDir + File.separator + "dump.txt'" ); commands.add( "-printseeds" ); commands.add( "'" + proguardDir + File.separator + "seeds.txt'" ); commands.add( "-printusage" ); commands.add( "'" + proguardDir + File.separator + "usage.txt'" ); commands.add( "-printmapping" ); commands.add( "'" + proguardDir + File.separator + "mapping.txt'" ); commands.addAll( Arrays.asList( parsedOptions ) ); final String javaExecutable = getJavaExecutable().getAbsolutePath(); getLog().info( javaExecutable + " " + commands.toString() ); try { executor.executeCommand( javaExecutable, commands, project.getBasedir(), false ); } catch ( ExecutionException e ) { throw new MojoExecutionException( "", e ); } }
diff --git a/src/contributions/resources/data-repo-sitetree/src/java/org/wyona/yanel/impl/resources/DataRepoSitetreeResource.java b/src/contributions/resources/data-repo-sitetree/src/java/org/wyona/yanel/impl/resources/DataRepoSitetreeResource.java index 7f4ec118d..715fb3c6c 100644 --- a/src/contributions/resources/data-repo-sitetree/src/java/org/wyona/yanel/impl/resources/DataRepoSitetreeResource.java +++ b/src/contributions/resources/data-repo-sitetree/src/java/org/wyona/yanel/impl/resources/DataRepoSitetreeResource.java @@ -1,148 +1,150 @@ /* * Copyright 2006 Wyona */ package org.wyona.yanel.impl.resources; import org.wyona.yanel.core.Resource; import org.wyona.yanel.core.api.attributes.ViewableV2; import org.wyona.yanel.core.attributes.viewable.View; import org.wyona.yanel.core.attributes.viewable.ViewDescriptor; import org.wyona.yanel.core.navigation.Node; import org.wyona.yanel.core.navigation.Sitetree; import org.apache.log4j.Category; /** * */ public class DataRepoSitetreeResource extends Resource implements ViewableV2 { private static Category log = Category.getInstance(DataRepoSitetreeResource.class); /** * */ public DataRepoSitetreeResource() { } /** * */ public String getMimeType(String viewId) throws Exception { if (viewId != null && viewId.equals("xml")) return "application/xml"; return "application/xhtml+xml"; } /** * */ public long getSize() throws Exception { return -1; } /** * */ public boolean exists() throws Exception { return true; } /** * */ public View getView(String viewId) throws Exception { StringBuffer sb = new StringBuffer("<?xml version=\"1.0\"?>"); if (viewId != null && viewId.equals("xml")) { sb.append(getSitetreeAsXML()); //sb.append(getSitetreeAsXML(getPath().toString())); } else { sb.append("<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:xhtml=\"http://www.w3.org/1999/xhtml\"><head><title>Browse Data Repository Sitetree</title></head><body><a href=\"?yanel.resource.viewid=xml\">Show XML</a><br/><br/>This content is being generated by the resource <![CDATA[" + getResourceTypeUniversalName() + "]]></body></html>"); } View view = new View(); view.setMimeType(getMimeType(viewId)); view.setInputStream(new java.io.StringBufferInputStream(sb.toString())); return view; } /** * */ public ViewDescriptor[] getViewDescriptors() { try { ViewDescriptor[] vd = new ViewDescriptor[2]; vd[0] = new ViewDescriptor("default"); vd[0].setMimeType(getMimeType(null)); vd[1] = new ViewDescriptor("xml"); vd[1].setMimeType(getMimeType("xml")); return vd; } catch (Exception e) { log.error(e.getMessage(), e); return null; } } /** * Get sitetree as XML */ private String getSitetreeAsXML() { StringBuffer sb = new StringBuffer("<sitetree>"); sb.append(getNodeAsXML("/")); // TODO: Sitetree generated out of RDF resources and statements /* com.hp.hpl.jena.rdf.model.Resource rootResource = getRealm().getSitetreeRootResource(); sb.append(getNodeAsXML(rootResource)); */ sb.append("</sitetree>"); return sb.toString(); } /** * Get node as XML */ private String getNodeAsXML(String path) { //private String getNodeAsXML(com.hp.hpl.jena.rdf.model.Resource resource) { //log.error("DEBUG: Path: " + path); Sitetree sitetree = getRealm().getRepoNavigation(); Node node = sitetree.getNode(getRealm(), path); StringBuffer sb = new StringBuffer(""); // TODO: Check for statements "parentOf" for this resource /* Statement[] st = resource.getStatements("parentOf"); if (st.length > 0) { for (int i = 0; i < st.length; i++) { Resource child = st.getObject(); URL url = getReal().getURLBuilder(child); } } else { // Is not a collection, there are no children } */ if (node != null) { - if (node.isCollection()) { - sb.append("<collection path=\"" + path + "\" name=\" " + node.getName() + "\">"); - Node[] children = node.getChildren(); - for (int i = 0; i < children.length; i++) { - if (children[i].isCollection()) { - sb.append(getNodeAsXML(children[i].getPath())); - } else if (children[i].isResource()) { - sb.append("<resource path=\"" + children[i].getPath() + "\" name=\"" + children[i].getName() + "\"/>"); - } else { - sb.append("<neither-resource-nor-collection path=\"" + children[i].getPath() + "\" name=\"" + children[i].getName() + "\"/>"); + if (node.isCollection()) { + sb.append("<collection path=\"" + path + "\" name=\" " + node.getName() + "\">"); + Node[] children = node.getChildren(); + for (int i = 0; i < children.length; i++) { + if (children[i].isCollection()) { + sb.append(getNodeAsXML(children[i].getPath())); + } else if (children[i].isResource()) { + sb.append("<resource path=\"" + children[i].getPath() + "\" name=\"" + children[i].getName() + "\"/>"); + } else { + sb.append("<neither-resource-nor-collection path=\"" + children[i].getPath() + "\" name=\"" + children[i].getName() + "\"/>"); + } } + sb.append("</collection>"); + } else { + sb.append("<resource path=\"" + path + "\" name=\"" + node.getName() + "\"/>"); } - sb.append("</collection>"); } else { - sb.append("<resource path=\"" + path + "\" name=\"" + node.getName() + "\"/>"); - } - } else { - sb.append("<exception>node is null for path: " + path + "</exception>"); + String errorMessage = "node is null for path: " + path; + sb.append("<exception>" + errorMessage + "</exception>"); + log.error(errorMessage); } return sb.toString(); } }
false
true
private String getNodeAsXML(String path) { //private String getNodeAsXML(com.hp.hpl.jena.rdf.model.Resource resource) { //log.error("DEBUG: Path: " + path); Sitetree sitetree = getRealm().getRepoNavigation(); Node node = sitetree.getNode(getRealm(), path); StringBuffer sb = new StringBuffer(""); // TODO: Check for statements "parentOf" for this resource /* Statement[] st = resource.getStatements("parentOf"); if (st.length > 0) { for (int i = 0; i < st.length; i++) { Resource child = st.getObject(); URL url = getReal().getURLBuilder(child); } } else { // Is not a collection, there are no children } */ if (node != null) { if (node.isCollection()) { sb.append("<collection path=\"" + path + "\" name=\" " + node.getName() + "\">"); Node[] children = node.getChildren(); for (int i = 0; i < children.length; i++) { if (children[i].isCollection()) { sb.append(getNodeAsXML(children[i].getPath())); } else if (children[i].isResource()) { sb.append("<resource path=\"" + children[i].getPath() + "\" name=\"" + children[i].getName() + "\"/>"); } else { sb.append("<neither-resource-nor-collection path=\"" + children[i].getPath() + "\" name=\"" + children[i].getName() + "\"/>"); } } sb.append("</collection>"); } else { sb.append("<resource path=\"" + path + "\" name=\"" + node.getName() + "\"/>"); } } else { sb.append("<exception>node is null for path: " + path + "</exception>"); } return sb.toString(); }
private String getNodeAsXML(String path) { //private String getNodeAsXML(com.hp.hpl.jena.rdf.model.Resource resource) { //log.error("DEBUG: Path: " + path); Sitetree sitetree = getRealm().getRepoNavigation(); Node node = sitetree.getNode(getRealm(), path); StringBuffer sb = new StringBuffer(""); // TODO: Check for statements "parentOf" for this resource /* Statement[] st = resource.getStatements("parentOf"); if (st.length > 0) { for (int i = 0; i < st.length; i++) { Resource child = st.getObject(); URL url = getReal().getURLBuilder(child); } } else { // Is not a collection, there are no children } */ if (node != null) { if (node.isCollection()) { sb.append("<collection path=\"" + path + "\" name=\" " + node.getName() + "\">"); Node[] children = node.getChildren(); for (int i = 0; i < children.length; i++) { if (children[i].isCollection()) { sb.append(getNodeAsXML(children[i].getPath())); } else if (children[i].isResource()) { sb.append("<resource path=\"" + children[i].getPath() + "\" name=\"" + children[i].getName() + "\"/>"); } else { sb.append("<neither-resource-nor-collection path=\"" + children[i].getPath() + "\" name=\"" + children[i].getName() + "\"/>"); } } sb.append("</collection>"); } else { sb.append("<resource path=\"" + path + "\" name=\"" + node.getName() + "\"/>"); } } else { String errorMessage = "node is null for path: " + path; sb.append("<exception>" + errorMessage + "</exception>"); log.error(errorMessage); } return sb.toString(); }
diff --git a/src/main/java/com/anzymus/neogeo/hiscores/success/AbstractGenreTitleStrategy.java b/src/main/java/com/anzymus/neogeo/hiscores/success/AbstractGenreTitleStrategy.java index 9a94362..3db1ca6 100644 --- a/src/main/java/com/anzymus/neogeo/hiscores/success/AbstractGenreTitleStrategy.java +++ b/src/main/java/com/anzymus/neogeo/hiscores/success/AbstractGenreTitleStrategy.java @@ -1,110 +1,110 @@ /** * Copyright (C) 2011 Julien SMADJA <julien dot smadja at gmail dot com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.anzymus.neogeo.hiscores.success; import java.util.ArrayList; import java.util.List; import com.anzymus.neogeo.hiscores.common.IntegerToRank; import com.anzymus.neogeo.hiscores.domain.Achievement; import com.anzymus.neogeo.hiscores.domain.Player; import com.anzymus.neogeo.hiscores.domain.Scores; public abstract class AbstractGenreTitleStrategy extends AbstractTitleStrategy { private static final int THRESHOLD = 3; @Override public boolean isUnlockable(Player player) { List<Scores> scoresByGame = titleService.getScoresByGameGenre(getGenre()); if (scoresByGame.isEmpty()) { return false; } int countNok = 0; int unplayedGame = 0; int countOk = 0; for (Scores scores : scoresByGame) { int rank = scores.getRank(player); if (rank == Integer.MAX_VALUE) { unplayedGame++; } else if (rank > 3) { countNok++; } else { countOk++; } } if (unplayedGame == scoresByGame.size()) { return false; } return countOk >= THRESHOLD && countNok <= countOk; } @Override public Achievement getAchievementFor(Player player) { List<Scores> scoresByGame = titleService.getScoresByGameGenre(getGenre()); if (scoresByGame.isEmpty()) { Achievement achievement = new Achievement(getTitle(), 0); Step step = new Step("Have a rank Between 1st and 3rd place in " + getGenre() + " games", false); achievement.addStep(step); return achievement; } int countNok = 0; int countOk = 0; List<Step> steps = new ArrayList<Step>(); for (Scores scores : scoresByGame) { boolean complete = false; int rank = scores.getRank(player); if (rank == Integer.MAX_VALUE) { } else if (rank > 3) { countNok++; } else { complete = true; countOk++; } if (rank != Integer.MAX_VALUE) { String gameName = scores.asSortedList().get(0).getGame().getName(); steps.add(new Step(gameName, IntegerToRank.getOrdinalFor(rank), complete)); } } boolean allIsComplete = countOk >= THRESHOLD && countNok <= countOk; int percent; if (allIsComplete) { percent = countOk > 0 ? 100 : 0; } else { - int ceil = (int) Math.ceil((double) scoresByGame.size() / 2); + int ceil = (int) Math.ceil((double) steps.size() / 2); if (ceil < 3) { ceil = 3; } percent = percent(countOk, ceil); } Achievement achievement = new Achievement(title, percent); for (Step step : steps) { if (allIsComplete) { if (step.isComplete()) { achievement.addStep(step); } } else { achievement.addStep(step); } } return achievement; } protected abstract String getGenre(); }
true
true
public Achievement getAchievementFor(Player player) { List<Scores> scoresByGame = titleService.getScoresByGameGenre(getGenre()); if (scoresByGame.isEmpty()) { Achievement achievement = new Achievement(getTitle(), 0); Step step = new Step("Have a rank Between 1st and 3rd place in " + getGenre() + " games", false); achievement.addStep(step); return achievement; } int countNok = 0; int countOk = 0; List<Step> steps = new ArrayList<Step>(); for (Scores scores : scoresByGame) { boolean complete = false; int rank = scores.getRank(player); if (rank == Integer.MAX_VALUE) { } else if (rank > 3) { countNok++; } else { complete = true; countOk++; } if (rank != Integer.MAX_VALUE) { String gameName = scores.asSortedList().get(0).getGame().getName(); steps.add(new Step(gameName, IntegerToRank.getOrdinalFor(rank), complete)); } } boolean allIsComplete = countOk >= THRESHOLD && countNok <= countOk; int percent; if (allIsComplete) { percent = countOk > 0 ? 100 : 0; } else { int ceil = (int) Math.ceil((double) scoresByGame.size() / 2); if (ceil < 3) { ceil = 3; } percent = percent(countOk, ceil); } Achievement achievement = new Achievement(title, percent); for (Step step : steps) { if (allIsComplete) { if (step.isComplete()) { achievement.addStep(step); } } else { achievement.addStep(step); } } return achievement; }
public Achievement getAchievementFor(Player player) { List<Scores> scoresByGame = titleService.getScoresByGameGenre(getGenre()); if (scoresByGame.isEmpty()) { Achievement achievement = new Achievement(getTitle(), 0); Step step = new Step("Have a rank Between 1st and 3rd place in " + getGenre() + " games", false); achievement.addStep(step); return achievement; } int countNok = 0; int countOk = 0; List<Step> steps = new ArrayList<Step>(); for (Scores scores : scoresByGame) { boolean complete = false; int rank = scores.getRank(player); if (rank == Integer.MAX_VALUE) { } else if (rank > 3) { countNok++; } else { complete = true; countOk++; } if (rank != Integer.MAX_VALUE) { String gameName = scores.asSortedList().get(0).getGame().getName(); steps.add(new Step(gameName, IntegerToRank.getOrdinalFor(rank), complete)); } } boolean allIsComplete = countOk >= THRESHOLD && countNok <= countOk; int percent; if (allIsComplete) { percent = countOk > 0 ? 100 : 0; } else { int ceil = (int) Math.ceil((double) steps.size() / 2); if (ceil < 3) { ceil = 3; } percent = percent(countOk, ceil); } Achievement achievement = new Achievement(title, percent); for (Step step : steps) { if (allIsComplete) { if (step.isComplete()) { achievement.addStep(step); } } else { achievement.addStep(step); } } return achievement; }
diff --git a/freeplane/src/org/freeplane/view/swing/map/NodeView.java b/freeplane/src/org/freeplane/view/swing/map/NodeView.java index becdf2cd1..728950cd2 100644 --- a/freeplane/src/org/freeplane/view/swing/map/NodeView.java +++ b/freeplane/src/org/freeplane/view/swing/map/NodeView.java @@ -1,1516 +1,1516 @@ /* * Freeplane - mind map editor * Copyright (C) 2008 Joerg Mueller, Daniel Polansky, Christian Foltin, Dimitry Polivaev * * This file is modified by Dimitry Polivaev in 2008. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.freeplane.view.swing.map; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.dnd.DnDConstants; import java.awt.dnd.DragGestureListener; import java.awt.dnd.DragSource; import java.awt.dnd.DropTarget; import java.awt.dnd.DropTargetListener; import java.util.LinkedList; import java.util.ListIterator; import javax.swing.JComponent; import javax.swing.tree.TreeNode; import org.freeplane.core.controller.Controller; import org.freeplane.core.resources.ResourceController; import org.freeplane.core.ui.IUserInputListenerFactory; import org.freeplane.core.ui.components.UITools; import org.freeplane.features.common.attribute.AttributeController; import org.freeplane.features.common.attribute.NodeAttributeTableModel; import org.freeplane.features.common.cloud.CloudController; import org.freeplane.features.common.cloud.CloudModel; import org.freeplane.features.common.edge.EdgeController; import org.freeplane.features.common.edge.EdgeStyle; import org.freeplane.features.common.icon.HierarchicalIcons; import org.freeplane.features.common.map.BranchesOverlap; import org.freeplane.features.common.map.HistoryInformationModel; import org.freeplane.features.common.map.INodeView; import org.freeplane.features.common.map.MapChangeEvent; import org.freeplane.features.common.map.ModeController; import org.freeplane.features.common.map.NodeChangeEvent; import org.freeplane.features.common.map.NodeModel; import org.freeplane.features.common.map.SummaryNode; import org.freeplane.features.common.map.NodeModel.NodeChangeType; import org.freeplane.features.common.nodelocation.LocationModel; import org.freeplane.features.common.nodestyle.NodeStyleController; import org.freeplane.features.common.styles.MapViewLayout; import org.freeplane.features.common.text.TextController; import org.freeplane.view.swing.map.MapView.PaintingMode; import org.freeplane.view.swing.map.attribute.AttributeView; import org.freeplane.view.swing.map.cloud.CloudView; import org.freeplane.view.swing.map.cloud.CloudViewFactory; import org.freeplane.view.swing.map.edge.EdgeView; import org.freeplane.view.swing.map.edge.EdgeViewFactory; import org.freeplane.view.swing.map.edge.SummaryEdgeView; /** * This class represents a single Node of a MindMap (in analogy to * TreeCellRenderer). */ public class NodeView extends JComponent implements INodeView { final static int ALIGN_BOTTOM = -1; final static int ALIGN_CENTER = 0; final static int ALIGN_TOP = 1; protected final static Color dragColor = Color.lightGray; public final static int DRAGGED_OVER_NO = 0; public final static int DRAGGED_OVER_SIBLING = 2; public final static int DRAGGED_OVER_SON = 1; /** For RootNodeView. */ public final static int DRAGGED_OVER_SON_LEFT = 3; static private int FOLDING_SYMBOL_WIDTH = -1; private static final long serialVersionUID = 1L; public final static int SHIFT = -2; static final int SPACE_AROUND = 50; public static final int MAIN_VIEWER_POSITION = 1; public static final int NOTE_VIEWER_POSITION = 10; final static boolean PAINT_DEBUG_BORDER; static{ boolean paintDebugBorder = false; try{ paintDebugBorder = System.getProperty("org.freeplane.view.swing.map.NodeView.PAINT_DEBUG_BORDER", "false").equalsIgnoreCase("true"); } catch(Exception e){ } PAINT_DEBUG_BORDER = paintDebugBorder; }; static final boolean DONT_MARK_FORMULAS = Controller.getCurrentController().getResourceController() .getBooleanProperty("formula_dont_mark_formulas"); static private int maxToolTipWidth; private AttributeView attributeView; private JComponent contentPane; private MainView mainView; private final MapView map; private NodeModel model; private NodeMotionListenerView motionListenerView; private NodeView preferredChild; private EdgeStyle edgeStyle = EdgeStyle.EDGESTYLE_HIDDEN; private int edgeWidth = 1; private Color edgeColor = Color.BLACK; private Color modelBackgroundColor; public static final int DETAIL_VIEWER_POSITION = 2; private int summedContentHeight; public int getSummedContentHeight() { return summedContentHeight; } public void setSummedContentHeight(int summedContentHeight) { this.summedContentHeight = summedContentHeight; } protected NodeView(final NodeModel model, final int position, final MapView map, final Container parent) { setFocusCycleRoot(true); this.model = model; this.map = map; final TreeNode parentNode = model.getParent(); final int index = parentNode == null ? 0 : parentNode.getIndex(model); parent.add(this, index); if (!model.isRoot()) { motionListenerView = new NodeMotionListenerView(this); map.add(motionListenerView, map.getComponentCount() - 1); } } void addDragListener(final DragGestureListener dgl) { if (dgl == null) { return; } final DragSource dragSource = DragSource.getDefaultDragSource(); dragSource.createDefaultDragGestureRecognizer(getMainView(), DnDConstants.ACTION_COPY | DnDConstants.ACTION_MOVE | DnDConstants.ACTION_LINK, dgl); } void addDropListener(final DropTargetListener dtl) { if (dtl == null) { return; } final DropTarget dropTarget = new DropTarget(getMainView(), dtl); dropTarget.setActive(true); } private int calcShiftY(final LocationModel locationModel) { try { final NodeModel parent = model.getParentNode(); return locationModel.getShiftY() + (getMap().getModeController().hasOneVisibleChild(parent) ? SHIFT : 0); } catch (final NullPointerException e) { return 0; } } @Override public boolean contains(final int x, final int y) { // if (!isValid()) { // return false; // } final int space = getMap().getZoomed(NodeView.SPACE_AROUND) - 2 * getZoomedFoldingSymbolHalfWidth(); return (x >= space) && (x < getWidth() - space) && (y >= space) && (y < getHeight() - space); } protected void convertPointToMap(final Point p) { UITools.convertPointToAncestor(this, p, getMap()); } public void createAttributeView() { if (attributeView == null && NodeAttributeTableModel.getModel(model).getNode() != null) { attributeView = new AttributeView(this, true); } syncronizeAttributeView(); } public boolean focused() { return mainView.hasFocus(); } /** */ public AttributeView getAttributeView() { if (attributeView == null) { AttributeController.getController(getMap().getModeController()).createAttributeTableModel(model); attributeView = new AttributeView(this, true); } return attributeView; } public Color getBackgroundColor() { final Color cloudColor = getCloudColor(); if (cloudColor != null) { return cloudColor; } if (isRoot()) { return getMap().getBackground(); } return getParentView().getBackgroundColor(); } public Color getCloudColor() { final CloudModel cloudModel = getCloudModel(); if(cloudModel != null){ final Color cloudColor = cloudModel.getColor(); return cloudColor; } return null; } /** * This method returns the NodeViews that are children of this node. */ public LinkedList<NodeView> getChildrenViews() { final LinkedList<NodeView> childrenViews = new LinkedList<NodeView>(); final Component[] components = getComponents(); for (int i = 0; i < components.length; i++) { if (!(components[i] instanceof NodeView)) { continue; } final NodeView view = (NodeView) components[i]; childrenViews.add(view); } return childrenViews; } public JComponent getContent() { final JComponent c = contentPane == null ? mainView : contentPane; assert (c.getParent() == this); return c; } private Container getContentPane() { if (contentPane == null) { contentPane = NodeViewFactory.getInstance().newContentPane(this); final int index = getComponentCount() - 1; remove(index); contentPane.add(mainView); mainView.putClientProperty("NODE_VIEW_CONTENT_POSITION", MAIN_VIEWER_POSITION); add(contentPane, index); } return contentPane; } /** * Returns the coordinates occupied by the node and its children as a vector * of four point per node. */ public void getCoordinates(final LinkedList<Point> inList) { getCoordinates(inList, 0, false, 0, 0); } private void getCoordinates(final LinkedList<Point> inList, int additionalDistanceForConvexHull, final boolean byChildren, final int transX, final int transY) { if (!isVisible()) { return; } if (isContentVisible()) { if (byChildren) { final ModeController modeController = getMap().getModeController(); final CloudController cloudController = CloudController.getController(modeController); final CloudModel cloud = cloudController.getCloud(getModel()); if (cloud != null) { additionalDistanceForConvexHull += CloudView.getAdditionalHeigth(cloud, this) / 5; } } final int x = transX + getContent().getX() - getDeltaX(); final int y = transY + getContent().getY() - getDeltaY(); final int width = mainView.getMainViewWidthWithFoldingMark(); final int heightWithFoldingMark = mainView.getMainViewHeightWithFoldingMark(); final int height = Math.max(heightWithFoldingMark, getContent().getHeight()); inList.addLast(new Point(-additionalDistanceForConvexHull + x, -additionalDistanceForConvexHull + y)); inList .addLast(new Point(-additionalDistanceForConvexHull + x, additionalDistanceForConvexHull + y + height)); inList.addLast(new Point(additionalDistanceForConvexHull + x + width, additionalDistanceForConvexHull + y + height)); inList .addLast(new Point(additionalDistanceForConvexHull + x + width, -additionalDistanceForConvexHull + y)); } for (final NodeView child : getChildrenViews()) { child.getCoordinates(inList, additionalDistanceForConvexHull, true, transX + child.getX(), transY + child.getY()); } } /** get x coordinate including folding symbol */ public int getDeltaX() { return mainView.getDeltaX(); } /** get y coordinate including folding symbol */ public int getDeltaY() { return mainView.getDeltaY(); } /** * @param startAfter */ NodeView getFirst(Component startAfter, final boolean leftOnly, final boolean rightOnly) { final Component[] components = getComponents(); for (int i = 0; i < components.length; i++) { if (startAfter != null) { if (components[i] == startAfter) { startAfter = null; } continue; } if (!(components[i] instanceof NodeView)) { continue; } final NodeView view = (NodeView) components[i]; if (leftOnly && !view.isLeft() || rightOnly && view.isLeft()) { continue; } if (view.isContentVisible()) { return view; } final NodeView child = view.getFirst(null, leftOnly, rightOnly); if (child != null) { return child; } } return null; } public int getHGap() { return map.getZoomed(LocationModel.getModel(model).getHGap()); } Rectangle getInnerBounds() { final int space = getMap().getZoomed(NodeView.SPACE_AROUND); return new Rectangle(space, space, getWidth() - 2 * space, getHeight() - 2 * space); } private NodeView getLast(Component startBefore, final boolean leftOnly, final boolean rightOnly) { final Component[] components = getComponents(); for (int i = components.length - 1; i >= 0; i--) { if (startBefore != null) { if (components[i] == startBefore) { startBefore = null; } continue; } if (!(components[i] instanceof NodeView)) { continue; } final NodeView view = (NodeView) components[i]; if (leftOnly && !view.isLeft() || rightOnly && view.isLeft()) { continue; } if (view.isContentVisible()) { return view; } final NodeView child = view.getLast(null, leftOnly, rightOnly); if (child != null) { return child; } } return null; } LinkedList<NodeView> getLeft(final boolean onlyVisible) { final LinkedList<NodeView> left = new LinkedList<NodeView>(); for (final NodeView node : getChildrenViews()) { if (node == null) { continue; } if (node.isLeft()) { left.add(node); } } return left; } /** * Returns the Point where the Links should arrive the Node. */ public Point getLinkPoint(final Point declination) { int x, y; Point linkPoint; if (declination != null) { x = getMap().getZoomed(declination.x); y = getMap().getZoomed(declination.y); } else { x = 1; y = 0; } if (isLeft()) { x = -x; } if (y != 0) { final double ctgRect = Math.abs((double) getContent().getWidth() / getContent().getHeight()); final double ctgLine = Math.abs((double) x / y); int absLinkX, absLinkY; if (ctgRect > ctgLine) { absLinkX = Math.abs(x * getContent().getHeight() / (2 * y)); absLinkY = getContent().getHeight() / 2; } else { absLinkX = getContent().getWidth() / 2; absLinkY = Math.abs(y * getContent().getWidth() / (2 * x)); } linkPoint = new Point(getContent().getWidth() / 2 + (x > 0 ? absLinkX : -absLinkX), getContent() .getHeight() / 2 + (y > 0 ? absLinkY : -absLinkY)); } else { linkPoint = new Point((x > 0 ? getContent().getWidth() : 0), (getContent().getHeight() / 2)); } linkPoint.translate(getContent().getX(), getContent().getY()); convertPointToMap(linkPoint); return linkPoint; } public MainView getMainView() { return mainView; } public Point getMainViewConnectorPoint(NodeView target) { final Point relativeLocation = getRelativeLocation(target); relativeLocation.x += target.getMainView().getWidth()/2; relativeLocation.y += target.getMainView().getHeight()/2; return mainView.getConnectorPoint(relativeLocation); } public Point getRelativeLocation(NodeView target) { Component component; int targetX = 0; int targetY = 0; for(component = target.getMainView(); !(this.equals(component) || component.getClass().equals(MapView.class)); component = component.getParent()){ targetX += component.getX(); targetY += component.getY(); } Point relativeLocation = new Point(); UITools.convertPointToAncestor(mainView, relativeLocation, component); relativeLocation.x = targetX - relativeLocation.x; relativeLocation.y = targetY - relativeLocation.y; return relativeLocation; } public MapView getMap() { return map; } public int getMaxToolTipWidth() { if (maxToolTipWidth == 0) { try { maxToolTipWidth = ResourceController.getResourceController().getIntProperty( "toolTipManager.max_tooltip_width", 600); } catch (final NumberFormatException e) { maxToolTipWidth = 600; } } return maxToolTipWidth; } public NodeModel getModel() { return model; } public NodeMotionListenerView getMotionListenerView() { return motionListenerView; } protected NodeView getNextPage() { if (getModel().isRoot()) { return this; } NodeView sibling = getNextVisibleSibling(); if (sibling == this) { return this; } NodeView nextSibling = sibling.getNextVisibleSibling(); while (nextSibling != sibling && sibling.getParentView() == nextSibling.getParentView()) { sibling = nextSibling; nextSibling = nextSibling.getNextVisibleSibling(); } return sibling; } protected NodeView getNextSiblingSingle() { LinkedList<NodeView> v = null; if (getParentView().getModel().isRoot()) { if (this.isLeft()) { v = (getParentView()).getLeft(true); } else { v = (getParentView()).getRight(true); } } else { v = getParentView().getChildrenViews(); } final int index = v.indexOf(this); for (int i = index + 1; i < v.size(); i++) { final NodeView nextView = (NodeView) v.get(i); if (nextView.isContentVisible()) { return nextView; } else { final NodeView first = nextView.getFirst(null, false, false); if (first != null) { return first; } } } return this; } protected NodeView getNextVisibleSibling() { NodeView sibling; NodeView lastSibling = this; for (sibling = this; !sibling.getModel().isRoot(); sibling = sibling.getParentView()) { lastSibling = sibling; sibling = sibling.getNextSiblingSingle(); if (sibling != lastSibling) { break; } } while (sibling.getModel().getNodeLevel(false) < getMap().getSiblingMaxLevel()) { final NodeView first = sibling.getFirst(sibling.isRoot() ? lastSibling : null, this.isLeft(), !this.isLeft()); if (first == null) { break; } sibling = first; } if (sibling.isRoot()) { return this; } return sibling; } public NodeView getParentView() { final Container parent = getParent(); if (parent instanceof NodeView) { return (NodeView) parent; } return null; } public NodeView getPreferredVisibleChild(final boolean getUpper, final boolean left) { if (getModel().isLeaf()) { return null; } if (getUpper) { preferredChild = null; } if (preferredChild != null && (left == preferredChild.isLeft()) && preferredChild.getParent() == this) { if (preferredChild.isContentVisible()) { return preferredChild; } else { final NodeView newSelected = preferredChild.getPreferredVisibleChild(getUpper, left); if (newSelected != null) { return newSelected; } } } int yGap = Integer.MAX_VALUE; final NodeView baseComponent; if (isContentVisible()) { baseComponent = this; } else { baseComponent = getVisibleParentView(); } final int ownX = baseComponent.getContent().getX() + baseComponent.getContent().getWidth() / 2; final int ownY = baseComponent.getContent().getY() + baseComponent.getContent().getHeight() / 2; NodeView newSelected = null; for (int i = 0; i < getComponentCount(); i++) { final Component c = getComponent(i); if (!(c instanceof NodeView)) { continue; } NodeView childView = (NodeView) c; if (!(childView.isLeft() == left)) { continue; } if (!childView.isContentVisible()) { childView = childView.getPreferredVisibleChild(getUpper, left); if (childView == null) { continue; } } if (getUpper) { return childView; } final Point childPoint = new Point(childView.getContent().getWidth() / 2, childView.getContent().getHeight() / 2); UITools.convertPointToAncestor(childView.getContent(), childPoint, baseComponent); final int dy = childPoint.y - ownY; final int dx = childPoint.x - ownX; final int gapToChild = dy*dy + dx*dx; if (gapToChild < yGap) { newSelected = childView; preferredChild = (NodeView) c; yGap = gapToChild; } else { break; } } return newSelected; } protected NodeView getPreviousPage() { if (getModel().isRoot()) { return this; } NodeView sibling = getPreviousVisibleSibling(); if (sibling == this) { return this; } NodeView previousSibling = sibling.getPreviousVisibleSibling(); while (previousSibling != sibling && sibling.getParentView() == previousSibling.getParentView()) { sibling = previousSibling; previousSibling = previousSibling.getPreviousVisibleSibling(); } return sibling; } protected NodeView getPreviousSiblingSingle() { LinkedList<NodeView> v = null; if (getParentView().getModel().isRoot()) { if (this.isLeft()) { v = (getParentView()).getLeft(true); } else { v = (getParentView()).getRight(true); } } else { v = getParentView().getChildrenViews(); } final int index = v.indexOf(this); for (int i = index - 1; i >= 0; i--) { final NodeView nextView = (NodeView) v.get(i); if (nextView.isContentVisible()) { return nextView; } else { final NodeView last = nextView.getLast(null, false, false); if (last != null) { return last; } } } return this; } protected NodeView getPreviousVisibleSibling() { NodeView sibling; NodeView previousSibling = this; for (sibling = this; !sibling.getModel().isRoot(); sibling = sibling.getParentView()) { previousSibling = sibling; sibling = sibling.getPreviousSiblingSingle(); if (sibling != previousSibling) { break; } } while (sibling.getModel().getNodeLevel(false) < getMap().getSiblingMaxLevel()) { final NodeView last = sibling.getLast(sibling.isRoot() ? previousSibling : null, this.isLeft(), !this.isLeft()); if (last == null) { break; } sibling = last; } if (sibling.isRoot()) { return this; } return sibling; } LinkedList<NodeView> getRight(final boolean onlyVisible) { final LinkedList<NodeView> right = new LinkedList<NodeView>(); for (final NodeView node : getChildrenViews()) { if (node == null) { continue; } if (!node.isLeft()) { right.add(node); } } return right; } /** * @return returns the color that should used to select the node. */ public Color getSelectedColor() { return MapView.standardSelectColor; } /** * @return Returns the sHIFT.s */ public int getShift() { final LocationModel locationModel = LocationModel.getModel(model); return map.getZoomed(calcShiftY(locationModel)); } protected LinkedList<NodeView> getSiblingViews() { return getParentView().getChildrenViews(); } public Color getTextBackground() { if (modelBackgroundColor != null) { return modelBackgroundColor; } return getBackgroundColor(); } public Color getTextColor() { final Color color = NodeStyleController.getController(getMap().getModeController()).getColor(model); return color; } public Font getTextFont() { return getMainView().getFont(); } /** * @return Returns the VGAP. */ public int getVGap() { return map.getZoomed(LocationModel.getModel(model).getVGap()); } public NodeView getVisibleParentView() { final Container parent = getParent(); if (!(parent instanceof NodeView)) { return null; } final NodeView parentView = (NodeView) parent; if (parentView.isContentVisible()) { return parentView; } return parentView.getVisibleParentView(); } public int getZoomedFoldingSymbolHalfWidth() { if (NodeView.FOLDING_SYMBOL_WIDTH == -1) { NodeView.FOLDING_SYMBOL_WIDTH = ResourceController.getResourceController().getIntProperty( "foldingsymbolwidth", 8); } final int preferredFoldingSymbolHalfWidth = (int) ((NodeView.FOLDING_SYMBOL_WIDTH * map.getZoom()) / 2); return preferredFoldingSymbolHalfWidth; } void insert() { for (NodeModel child : getMap().getModeController().getMapController().childrenFolded(getModel())) { insert(child, 0); } } /** * Create views for the newNode and all his descendants, set their isLeft * attribute according to this view. */ NodeView insert(final NodeModel newNode, final int position) { final NodeView newView = NodeViewFactory.getInstance().newNodeView(newNode, position, getMap(), this); newView.insert(); return newView; } /* fc, 25.1.2004: Refactoring necessary: should call the model. */ public boolean isChildOf(final NodeView myNodeView) { return getParentView() == myNodeView; } /** */ public boolean isContentVisible() { return getModel().isVisible(); } public boolean isLeft() { if (getMap().getLayoutType() == MapViewLayout.OUTLINE) { return false; } return getModel().isLeft(); } public boolean isParentHidden() { final Container parent = getParent(); if (!(parent instanceof NodeView)) { return false; } final NodeView parentView = (NodeView) parent; return !parentView.isContentVisible(); } /* fc, 25.1.2004: Refactoring necessary: should call the model. */ public boolean isParentOf(final NodeView myNodeView) { return (this == myNodeView.getParentView()); } public boolean isRoot() { return getModel().isRoot(); } public boolean isSelected() { return (getMap().isSelected(this)); } /* fc, 25.1.2004: Refactoring necessary: should call the model. */ public boolean isSiblingOf(final NodeView myNodeView) { return getParentView() == myNodeView.getParentView(); } public void mapChanged(final MapChangeEvent event) { } public void nodeChanged(final NodeChangeEvent event) { final NodeModel node = event.getNode(); // is node is deleted, skip the rest. if (!node.isRoot() && node.getParent() == null) { return; } final Object property = event.getProperty(); if (property == NodeChangeType.FOLDING) { treeStructureChanged(); return; } // is node is not fully initialized, skip the rest. if (mainView == null) { return; } if (property.equals(NodeModel.NODE_ICON) || property.equals(HierarchicalIcons.ICONS)) { mainView.updateIcons(this); revalidate(); return; } if (property.equals(NodeModel.NOTE_TEXT)) { NodeViewFactory.getInstance().updateNoteViewer(this); return; } if (property.equals(HistoryInformationModel.class)) { updateToolTip(); return; } if(property.equals(BranchesOverlap.class)){ updateAll(); return; } update(); if (!isRoot()) getParentView().numberingChanged(node.getParent().getIndex(node) + 1); } public void onNodeDeleted(final NodeModel parent, final NodeModel child, final int index) { getMap().resetShiftSelectionOrigin(); if (getMap().getModeController().getMapController().isFolded(model)) { return; } final boolean preferredChildIsLeft = preferredChild != null && preferredChild.isLeft(); final NodeView node = (NodeView) getComponent(index); if (node == preferredChild) { preferredChild = null; for (int j = index + 1; j < getComponentCount(); j++) { final Component c = getComponent(j); if (!(c instanceof NodeView)) { break; } final NodeView candidate = (NodeView) c; if (candidate.isVisible() && node.isLeft() == candidate.isLeft()) { preferredChild = candidate; break; } } if (preferredChild == null) { for (int j = index - 1; j >= 0; j--) { final Component c = getComponent(j); if (!(c instanceof NodeView)) { break; } final NodeView candidate = (NodeView) c; if (candidate.isVisible() && node.isLeft() == candidate.isLeft()) { preferredChild = candidate; break; } } } } node.remove(); NodeView preferred = getPreferredVisibleChild(false, preferredChildIsLeft); if (preferred == null) { preferred = this; } getMap().selectVisibleAncestorOrSelf(preferred); numberingChanged(index); revalidate(); } public void onNodeInserted(final NodeModel parent, final NodeModel child, final int index) { assert parent == model; if (getMap().getModeController().getMapController().isFolded(model)) { return; } insert(child, index); numberingChanged(index + 1); revalidate(); } public void onNodeMoved(final NodeModel oldParent, final int oldIndex, final NodeModel newParent, final NodeModel child, final int newIndex) { onNodeDeleted(oldParent, child, oldIndex); onNodeInserted(newParent, child, newIndex); } public void onPreNodeDelete(final NodeModel oldParent, final NodeModel child, final int oldIndex) { } // updates children, starting from firstChangedIndex, if necessary. private void numberingChanged(int firstChangedIndex) { final TextController textController = TextController.getController(getMap().getModeController()); if (firstChangedIndex > 0 || textController.getNodeNumbering(getModel())) { final Component[] components = getComponents(); for (int i = firstChangedIndex; i < components.length; i++) { if (components[i] instanceof NodeView) { final NodeView view = (NodeView) components[i]; view.update(); view.numberingChanged(0); } } } } /* * (non-Javadoc) * @see javax.swing.JComponent#paint(java.awt.Graphics) */ @Override public void paint(final Graphics g) { final PaintingMode paintingMode = map.getPaintingMode(); if (isContentVisible()) { final Graphics2D g2 = (Graphics2D) g; final ModeController modeController = map.getModeController(); final Object renderingHint = g2.getRenderingHint(RenderingHints.KEY_ANTIALIASING); final boolean isRoot = isRoot(); switch (paintingMode) { case CLOUDS: case ALL: modeController.getController().getViewController().setEdgesRenderingHint(g2); if (isRoot) { paintCloud(g); } paintCloudsAndEdges(g2); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, renderingHint); } super.paint(g); switch (paintingMode) { case NODES: case ALL: g2.setStroke(BubbleMainView.DEF_STROKE); modeController.getController().getViewController().setEdgesRenderingHint(g2); paintDecoration(g2); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, renderingHint); } } else { super.paint(g); } if (PAINT_DEBUG_BORDER && isSelected()){ final int spaceAround = getZoomed(SPACE_AROUND); g.drawRect(spaceAround, spaceAround, getWidth() - 2 * spaceAround, getHeight() - 2 * spaceAround); } } private void paintCloud(final Graphics g) { if (!isContentVisible()) { return; } final CloudModel cloudModel = getCloudModel(); if (cloudModel == null) { return; } final CloudView cloud = new CloudViewFactory().createCloudView(cloudModel, this); cloud.paint(g); } private void paintCloudsAndEdges(final Graphics2D g) { for (int i = getComponentCount() - 1; i >= 0; i--) { final Component component = getComponent(i); if (!(component instanceof NodeView)) { continue; } final NodeView nodeView = (NodeView) component; if (nodeView.isContentVisible()) { final Point p = new Point(); UITools.convertPointToAncestor(nodeView, p, this); g.translate(p.x, p.y); nodeView.paintCloud(g); g.translate(-p.x, -p.y); if (getMap().getLayoutType() != MapViewLayout.OUTLINE && nodeView.isSummary()) { paintSummaryEdge(g, nodeView, i); } else { final EdgeView edge = EdgeViewFactory.getInstance().getEdge(nodeView); edge.paint(g); } } else { nodeView.paintCloudsAndEdges(g); } } } private void paintSummaryEdge(Graphics2D g, NodeView nodeView, int pos) { final boolean isLeft = nodeView.isLeft(); final int spaceAround = getSpaceAround(); int level = 0; int anotherLevel = 0; int i; NodeView lastView = null; int x1 = 0; boolean itemFound = false; boolean firstGroupNodeFound = false; for (i = pos - 1; i >= 0; i--) { final NodeView nodeViewSibling = (NodeView) getComponent(i); if (nodeViewSibling.isLeft() != isLeft) continue; if (lastView == null) { lastView = nodeViewSibling; if (isLeft) { x1 = nodeViewSibling.getX() + spaceAround; } else { x1 = nodeViewSibling.getX() + lastView.getWidth() - spaceAround; } firstGroupNodeFound = lastView.isFirstGroupNode(); } if(! itemFound){ if( ! nodeViewSibling.isSummary()) itemFound = true; else level++; } else if(nodeViewSibling.isSummary()){ anotherLevel++; if(anotherLevel > level) break; } else anotherLevel = 0; if(anotherLevel == level && nodeViewSibling.isFirstGroupNode()) firstGroupNodeFound = true; - if(firstGroupNodeFound && ! nodeViewSibling.isSummary()){ + if(firstGroupNodeFound && anotherLevel == level && ! nodeViewSibling.isSummary()){ i--; break; } } if (lastView == null) { final EdgeView edge = EdgeViewFactory.getInstance().getEdge(nodeView); edge.paint(g); return; } NodeView firstView = null; anotherLevel = 0; int y2 = lastView.getY() + lastView.getHeight() - spaceAround; int y1 = y2; for (i = i + 1; i < pos; i++) { final NodeView nodeViewSibling = (NodeView) getComponent(i); if (nodeViewSibling.isLeft() != isLeft) continue; if (nodeViewSibling.isSummary()) anotherLevel++; else anotherLevel = 0; if (anotherLevel == level && firstView == null) { firstView = nodeViewSibling; } y1 = Math.min(y1, nodeViewSibling.getY() + spaceAround); y2 = Math.max(y2, nodeViewSibling.getY() + nodeViewSibling.getHeight() - spaceAround); if (isLeft) { x1 = Math.min(x1, nodeViewSibling.getX() + spaceAround); } else { x1 = Math.max(x1, nodeViewSibling.getX() + nodeViewSibling.getWidth() - spaceAround); } } final JComponent content = nodeView.getContent(); int x = nodeView.getX() + content.getX(); if (isLeft) x += nodeView.getWidth() - 2 * spaceAround; final EdgeView edgeView = new SummaryEdgeView(nodeView); edgeView.setStart(new Point(x1, y1)); edgeView.paint(g); edgeView.setStart(new Point(x1, y2)); edgeView.paint(g); } int getSpaceAround() { return getZoomed(NodeView.SPACE_AROUND); } public int getZoomed(int x) { return getMap().getZoomed(x); } void paintDecoration(final Graphics2D g) { final Point origin = new Point(); UITools.convertPointToAncestor(mainView, origin, this); g.translate(origin.x, origin.y); mainView.paintDecoration(this, g); g.translate(-origin.x, -origin.y); } /** * This is a bit problematic, because getChildrenViews() only works if model * is not yet removed. (So do not _really_ delete the model before the view * removed (it needs to stay in memory) */ void remove() { for (final ListIterator<NodeView> e = getChildrenViews().listIterator(); e.hasNext();) { e.next().remove(); } if (isSelected()) { getMap().deselect(this); } getMap().getModeController().onViewRemoved(this); removeFromMap(); if (attributeView != null) { attributeView.viewRemoved(); } getModel().removeViewer(this); } protected void removeFromMap() { setFocusCycleRoot(false); getParent().remove(this); if (motionListenerView != null) { map.remove(motionListenerView); } } private void repaintEdge(final NodeView target) { final Point relativeLocation = getRelativeLocation(target); final MainView targetMainView = target.getMainView(); relativeLocation.x += targetMainView.getWidth()/2; relativeLocation.y += targetMainView.getHeight()/2; final Point inPoint = mainView.getConnectorPoint(relativeLocation); UITools.convertPointToAncestor(targetMainView, inPoint, this); relativeLocation.x -= targetMainView.getWidth()/2; relativeLocation.y -= targetMainView.getHeight()/2; relativeLocation.x = - relativeLocation.x + mainView.getWidth()/2; relativeLocation.y = - relativeLocation.y + mainView.getHeight()/2; final Point outPoint = targetMainView.getConnectorPoint(relativeLocation); UITools.convertPointToAncestor(getMainView(), outPoint, this); final int x = Math.min(inPoint.x, outPoint.x); final int y = Math.min(inPoint.y, outPoint.y); final int w = Math.abs(inPoint.x - outPoint.x); final int h = Math.abs(inPoint.y - outPoint.y); final int EXTRA = 50; repaint(x - EXTRA, y - EXTRA, w + EXTRA * 2, h + EXTRA * 2); } void repaintSelected() { // return if main view was not set if (mainView == null) { return; } // do not repaint removed nodes if (model.getParentNode() == null && !model.isRoot()) { return; } mainView.updateTextColor(this); if (getEdgeStyle().equals(EdgeStyle.EDGESTYLE_HIDDEN)) { final NodeView visibleParentView = getVisibleParentView(); if (visibleParentView != null) { visibleParentView.repaintEdge(this); } } final JComponent content = getContent(); final int EXTRA = 20; final int x = content.getX() - EXTRA; final int y = content.getY() - EXTRA; repaint(x, y, content.getWidth() + EXTRA * 2, content.getHeight() + EXTRA * 2); } @Override public boolean requestFocusInWindow() { if (mainView == null) { return false; } getMap().scrollNodeToVisible(this); Controller.getCurrentController().getViewController().addObjectTypeInfo(getModel().getUserObject()); return mainView.requestFocusInWindow(); } @Override public void requestFocus() { if (mainView == null) { return; } getMap().scrollNodeToVisible(this); Controller.getCurrentController().getViewController().addObjectTypeInfo(getModel().getUserObject()); mainView.requestFocus(); } @Override public void setBounds(final int x, final int y, final int width, final int height) { super.setBounds(x, y, width, height); if (motionListenerView != null) { motionListenerView.invalidate(); } } void setMainView(final MainView newMainView) { if (contentPane != null) { assert (contentPane.getParent() == this); if (mainView != null) removeContent(MAIN_VIEWER_POSITION); addContent(newMainView, MAIN_VIEWER_POSITION); assert (contentPane.getParent() == this); } else if (mainView != null) { final Container c = mainView.getParent(); int i; for (i = c.getComponentCount() - 1; i >= 0 && mainView != c.getComponent(i); i--) { ; } c.remove(i); c.add(newMainView, i); } else { add(newMainView); } mainView = newMainView; final IUserInputListenerFactory userInputListenerFactory = getMap().getModeController() .getUserInputListenerFactory(); mainView.addMouseListener(userInputListenerFactory.getNodeMouseMotionListener()); mainView.addMouseMotionListener(userInputListenerFactory.getNodeMouseMotionListener()); mainView.addKeyListener(userInputListenerFactory.getNodeKeyListener()); addDragListener(userInputListenerFactory.getNodeDragListener()); addDropListener(userInputListenerFactory.getNodeDropTargetListener()); } protected void setModel(final NodeModel model) { this.model = model; } public void setPreferredChild(final NodeView view) { if(view != null && ! SummaryNode.isSummaryNode(view.getModel())) preferredChild = view; final Container parent = this.getParent(); if (view == null) { return; } else if (parent instanceof NodeView) { ((NodeView) parent).setPreferredChild(this); } } /** */ public void setText(final String string) { mainView.setText(string); } @Override public void setVisible(final boolean isVisible) { super.setVisible(isVisible); if (motionListenerView != null) { motionListenerView.setVisible(isVisible); } } void syncronizeAttributeView() { if (attributeView != null) { attributeView.syncronizeAttributeView(); } } /* * (non-Javadoc) * @see java.awt.Component#toString() */ @Override public String toString() { return getModel().toString() + ", " + super.toString(); } /* * (non-Javadoc) * @see * javax.swing.event.TreeModelListener#treeStructureChanged(javax.swing. * event.TreeModelEvent) */ private void treeStructureChanged() { getMap().resetShiftSelectionOrigin(); for (final ListIterator<NodeView> i = getChildrenViews().listIterator(); i.hasNext();) { i.next().remove(); } insert(); if (map.getSelected() == null) { map.selectAsTheOnlyOneSelected(this); } map.revalidateSelecteds(); revalidate(); } public void update() { updateShape(); if (!isContentVisible()) { mainView.setVisible(false); return; } mainView.setVisible(true); mainView.updateTextColor(this); mainView.updateFont(this); createAttributeView(); if (attributeView != null) { attributeView.update(); } NodeViewFactory.getInstance().updateDetails(this); if (contentPane != null) { final int componentCount = contentPane.getComponentCount(); for (int i = 1; i < componentCount; i++) { final Component component = contentPane.getComponent(i); if (component instanceof JComponent) { ((JComponent) component).revalidate(); } } } updateShortener(getModel()); mainView.updateText(getModel()); mainView.updateIcons(this); updateToolTip(); updateCloud(); updateEdge(); modelBackgroundColor = NodeStyleController.getController(getMap().getModeController()).getBackgroundColor(model); revalidate(); } private void updateEdge() { if(! isRoot()) { final EdgeController edgeController = EdgeController.getController(getMap().getModeController()); this.edgeStyle = edgeController.getStyle(model); this.edgeWidth = edgeController.getWidth(model); this.edgeColor = edgeController.getColor(model); } } public EdgeStyle getEdgeStyle() { return edgeStyle; } public int getEdgeWidth() { return edgeWidth; } public Color getEdgeColor() { return edgeColor; } private void updateCloud() { final CloudModel cloudModel = CloudController.getController(getMap().getModeController()).getCloud(model); putClientProperty(CloudModel.class, cloudModel); } public CloudModel getCloudModel() { return (CloudModel) getClientProperty(CloudModel.class); } private void updateShortener(NodeModel nodeModel) { final ModeController modeController = getMap().getModeController(); final TextController textController = TextController.getController(modeController); final boolean textShortened = textController.getIsShortened(nodeModel); final boolean componentsVisible = !textShortened; setContentComponentVisible(componentsVisible); } private void setContentComponentVisible(final boolean componentsVisible) { final Component[] components = getContentPane().getComponents(); int index; for (index = 0; index < components.length; index++) { final Component component = components[index]; if (component == getMainView()) { continue; } if (component.isVisible() != componentsVisible) { component.setVisible(componentsVisible); } } } public void updateAll() { NodeViewFactory.getInstance().updateNoteViewer(this); update(); invalidate(); for (final NodeView child : getChildrenViews()) { child.updateAll(); } } private void updateShape() { final String shape = NodeStyleController.getController(getMap().getModeController()).getShape(model); if (mainView != null && (model.isRoot() || mainView.getStyle().equals(shape))) { return; } final MainView newMainView = NodeViewFactory.getInstance().newMainView(this); setMainView(newMainView); if (map.getSelected() == this) { requestFocusInWindow(); } } /** * */ /** * Updates the tool tip of the node. */ private void updateToolTip() { if (mainView != null) { final NodeModel nodeModel = getModel(); mainView.setToolTipText(nodeModel.getToolTip(getMap().getModeController())); } } boolean useSelectionColors() { return isSelected() && !MapView.standardDrawRectangleForSelection && !map.isPrinting(); } public void onPreNodeMoved(final NodeModel oldParent, final int oldIndex, final NodeModel newParent, final NodeModel child, final int newIndex) { } @Override protected void validateTree() { super.validateTree(); } public void addContent(JComponent component, int pos) { component.putClientProperty("NODE_VIEW_CONTENT_POSITION", pos); final Container contentPane = getContentPane(); for (int i = 0; i < contentPane.getComponentCount(); i++) { JComponent content = (JComponent) contentPane.getComponent(i); if (content == null) throw new RuntimeException("component " + i + "is null"); final Object clientProperty = content.getClientProperty("NODE_VIEW_CONTENT_POSITION"); if (clientProperty == null) throw new RuntimeException("NODE_VIEW_CONTENT_POSITION not set on component " + content.toString() + i + "/" + contentPane.getComponentCount()); if (pos < (Integer) clientProperty) { contentPane.add(component, i); return; } } contentPane.add(component); } public JComponent removeContent(int pos) { return removeContent(pos, true); } private JComponent removeContent(int pos, boolean remove) { if (contentPane == null) return null; for (int i = 0; i < contentPane.getComponentCount(); i++) { JComponent component = (JComponent) contentPane.getComponent(i); Integer contentPos = (Integer) component.getClientProperty("NODE_VIEW_CONTENT_POSITION"); if (contentPos == null) { continue; } if (contentPos == pos) { if (remove) { component.putClientProperty("NODE_VIEW_CONTENT_POSITION", null); contentPane.remove(i); } return component; } if (contentPos > pos) { return null; } } return null; } public JComponent getContent(int pos) { return removeContent(pos, false); } public boolean isSummary() { return SummaryNode.isSummaryNode(getModel()); } public boolean isFirstGroupNode() { return SummaryNode.isFirstGroupNode(getModel()); } }
true
true
private void paintSummaryEdge(Graphics2D g, NodeView nodeView, int pos) { final boolean isLeft = nodeView.isLeft(); final int spaceAround = getSpaceAround(); int level = 0; int anotherLevel = 0; int i; NodeView lastView = null; int x1 = 0; boolean itemFound = false; boolean firstGroupNodeFound = false; for (i = pos - 1; i >= 0; i--) { final NodeView nodeViewSibling = (NodeView) getComponent(i); if (nodeViewSibling.isLeft() != isLeft) continue; if (lastView == null) { lastView = nodeViewSibling; if (isLeft) { x1 = nodeViewSibling.getX() + spaceAround; } else { x1 = nodeViewSibling.getX() + lastView.getWidth() - spaceAround; } firstGroupNodeFound = lastView.isFirstGroupNode(); } if(! itemFound){ if( ! nodeViewSibling.isSummary()) itemFound = true; else level++; } else if(nodeViewSibling.isSummary()){ anotherLevel++; if(anotherLevel > level) break; } else anotherLevel = 0; if(anotherLevel == level && nodeViewSibling.isFirstGroupNode()) firstGroupNodeFound = true; if(firstGroupNodeFound && ! nodeViewSibling.isSummary()){ i--; break; } } if (lastView == null) { final EdgeView edge = EdgeViewFactory.getInstance().getEdge(nodeView); edge.paint(g); return; } NodeView firstView = null; anotherLevel = 0; int y2 = lastView.getY() + lastView.getHeight() - spaceAround; int y1 = y2; for (i = i + 1; i < pos; i++) { final NodeView nodeViewSibling = (NodeView) getComponent(i); if (nodeViewSibling.isLeft() != isLeft) continue; if (nodeViewSibling.isSummary()) anotherLevel++; else anotherLevel = 0; if (anotherLevel == level && firstView == null) { firstView = nodeViewSibling; } y1 = Math.min(y1, nodeViewSibling.getY() + spaceAround); y2 = Math.max(y2, nodeViewSibling.getY() + nodeViewSibling.getHeight() - spaceAround); if (isLeft) { x1 = Math.min(x1, nodeViewSibling.getX() + spaceAround); } else { x1 = Math.max(x1, nodeViewSibling.getX() + nodeViewSibling.getWidth() - spaceAround); } } final JComponent content = nodeView.getContent(); int x = nodeView.getX() + content.getX(); if (isLeft) x += nodeView.getWidth() - 2 * spaceAround; final EdgeView edgeView = new SummaryEdgeView(nodeView); edgeView.setStart(new Point(x1, y1)); edgeView.paint(g); edgeView.setStart(new Point(x1, y2)); edgeView.paint(g); }
private void paintSummaryEdge(Graphics2D g, NodeView nodeView, int pos) { final boolean isLeft = nodeView.isLeft(); final int spaceAround = getSpaceAround(); int level = 0; int anotherLevel = 0; int i; NodeView lastView = null; int x1 = 0; boolean itemFound = false; boolean firstGroupNodeFound = false; for (i = pos - 1; i >= 0; i--) { final NodeView nodeViewSibling = (NodeView) getComponent(i); if (nodeViewSibling.isLeft() != isLeft) continue; if (lastView == null) { lastView = nodeViewSibling; if (isLeft) { x1 = nodeViewSibling.getX() + spaceAround; } else { x1 = nodeViewSibling.getX() + lastView.getWidth() - spaceAround; } firstGroupNodeFound = lastView.isFirstGroupNode(); } if(! itemFound){ if( ! nodeViewSibling.isSummary()) itemFound = true; else level++; } else if(nodeViewSibling.isSummary()){ anotherLevel++; if(anotherLevel > level) break; } else anotherLevel = 0; if(anotherLevel == level && nodeViewSibling.isFirstGroupNode()) firstGroupNodeFound = true; if(firstGroupNodeFound && anotherLevel == level && ! nodeViewSibling.isSummary()){ i--; break; } } if (lastView == null) { final EdgeView edge = EdgeViewFactory.getInstance().getEdge(nodeView); edge.paint(g); return; } NodeView firstView = null; anotherLevel = 0; int y2 = lastView.getY() + lastView.getHeight() - spaceAround; int y1 = y2; for (i = i + 1; i < pos; i++) { final NodeView nodeViewSibling = (NodeView) getComponent(i); if (nodeViewSibling.isLeft() != isLeft) continue; if (nodeViewSibling.isSummary()) anotherLevel++; else anotherLevel = 0; if (anotherLevel == level && firstView == null) { firstView = nodeViewSibling; } y1 = Math.min(y1, nodeViewSibling.getY() + spaceAround); y2 = Math.max(y2, nodeViewSibling.getY() + nodeViewSibling.getHeight() - spaceAround); if (isLeft) { x1 = Math.min(x1, nodeViewSibling.getX() + spaceAround); } else { x1 = Math.max(x1, nodeViewSibling.getX() + nodeViewSibling.getWidth() - spaceAround); } } final JComponent content = nodeView.getContent(); int x = nodeView.getX() + content.getX(); if (isLeft) x += nodeView.getWidth() - 2 * spaceAround; final EdgeView edgeView = new SummaryEdgeView(nodeView); edgeView.setStart(new Point(x1, y1)); edgeView.paint(g); edgeView.setStart(new Point(x1, y2)); edgeView.paint(g); }
diff --git a/src/data/GameData.java b/src/data/GameData.java index c6612a3..056e5f4 100644 --- a/src/data/GameData.java +++ b/src/data/GameData.java @@ -1,1087 +1,1091 @@ package data; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Observable; import java.util.Random; import java.util.EnumSet; import javax.swing.SwingUtilities; import json.simple.JSONArray; import json.simple.JSONObject; import json.simple.parser.ParseException; import admin.Utils; import data.bonus.Bonus; /** * GameData is the class that will be used to keep track of the important game * information, including the number of weeks passed, the lists of all/active * contestants, and the number of weeks remaining. * * @author Graem Littleton, Ramesh Raj, Justin McDonald, Jonathan Demelo, Kevin * Brightwell */ public class GameData extends Observable { private int weeksRem, weeksPassed; // keep track of weeks remaining/weeks passed private int numInitialContestants, betAmount, totalAmount; private boolean seasonStarted = false, elimExists = false; private String[] tribeNames = new String[2]; // string array storing both tribe names private Contestant[] castOffs; // array storing people who were cast off private List<Contestant> allContestants; // List storing all contestants private List<User> allUsers; // list storing all users // store the current running version private static GameData currentGame = null; // store contestant who was cast off private Contestant elimCont; // used for asynchronous calls to notifyObservers() private UpdateCall updateExec; public enum UpdateTag { START_SEASON, ADVANCE_WEEK, SET_TRIBE_NAMES, ADD_CONTESTANT, REMOVE_CONTESTANT, CONTESTANT_CAST_OFF, ADD_USER, REMOVE_USER, FINAL_WEEK, END_GAME, ALLOCATE_POINTS, SAVE; } /** * JSON Keys */ private static final String KEY_CONTESTANTS = "cons", KEY_NUM_CONTEST = "cons_num", KEY_USERS = "users", KEY_WEEKS_REMAIN = "weeks_rem", KEY_WEEKS_PASSED = "weeks_pass", KEY_TRIBES = "tribes_arr", KEY_SEASON_STARTED = "season_started", KEY_BET_AMOUNT = "bet_amount", KEY_POOL_TOTAL = "pool_total", KEY_CAST_OFFS = "cast_offs"; /** * Constructor method that takes a set number of contestants. Will not * proceed if numInitialContestants is NOT between 6 and 15, inclusive. Sets * number of weeks passed to 0 and weeks remaining to number of contestants * - 3. * * @param numInitialContestants * number of contestants to be in game */ // TODO: Make throw exception, its not enough to return, the object is still // created. public GameData(int numInitialContestants) { // check if within parameters if (numInitialContestants > 15 || numInitialContestants < 6) return; // if not, do not create GameData item weeksRem = numInitialContestants - 2; weeksPassed = 0; setBetAmount(0); this.numInitialContestants = numInitialContestants; // containers for contestants and users allContestants = new ArrayList<Contestant>(numInitialContestants); allUsers = new ArrayList<User>(5); castOffs = new Contestant[numInitialContestants]; currentGame = this; } // ----------------- ACCESSOR METHODS -----------------// // CONTESTANT // /** * Returns whether or not a contestant has been selected to be cast off. * * @return elimExists */ public boolean doesElimExist() { return elimExists; } /** * getAllContestants returns a list of all current and former contestants * that are/have been involved with the game. * * @return this.allContestants */ public List<Contestant> getAllContestants() { return allContestants; } /** * Returns the contestant who was cast off on a specified week. * @param week * @return castOffs[week] */ public Contestant getCastOff(int week){ return castOffs[week]; } /** * Get contestant based on unique id * * @param id * an unique id * @return the Contestant that matches id or null */ public Contestant getContestant(String id) { int i = getContestantIndexID(id); if (i >= 0) return allContestants.get(i); else return null; } /** * Returns the contestant who is to be eliminated. * * @return elimCont */ protected Contestant getElimCont() { return elimCont; } /** * getInitialContestants returns an integer of the number of initial * contestants that are in the game. * * @return The current amount of contestants */ public int getInitialContestants() { return numInitialContestants; } /** * getNumCurrentContestants returns an integer of the number of contestants * that are in the game. * * @return The current amount of contestants */ public int getNumCurrentContestants() { return allContestants.size(); } // SPECIALTY GETTERS - CONTESTANT // /** * getActiveContestants returns an array (list) of the contestants that are * still competing in the game. * * @return The contestants active */ public List<Contestant> getActiveContestants(boolean active) { List<Contestant> list = new ArrayList<Contestant>( allContestants.size()); for (Contestant c : allContestants) { if (c != null) { if (active && !c.isCastOff()) { list.add(c); } else if (!active && c.isCastOff()) { list.add(c); } } } return list; } /** * getContestant takes the first and last name of a contestant as input and * searches the array of current contestants for him/her. Returns * information found in the Contestant class to the caller. * * @param first * First name * @param last * Last name * @return contestant or string object */ public Contestant getContestant(String first, String last) { // loop through array for (Contestant j : allContestants) { if (first.equals(j.getFirstName()) && last.equals(j.getLastName())) { // ensure match // return info on player return j; } } // otherwise return message saying contestant is no longer/is not in the game return null; } // USER // /** * Gets the list of all users. * * @return Vector containing all users. */ public List<User> getAllUsers() { return allUsers; } /** * Gets a user from the stored users by ID. * * @param ID * User ID of the User to get from the stored data. * @return User if ID found, null otherwise. */ public User getUser(String ID) { for (User u : allUsers) { if (u.getID().equalsIgnoreCase(ID)) { return u; } } return null; } // ----------------- MUTATOR METHODS ----------------- // // CONTESTANT // /** * Adds a new contestant into the Game, this will maintain the list of * contestants as sorted by ID. * * @param c * New contestant, will not add if ID of contestant is null. */ public void addContestant(Contestant c) throws InvalidFieldException { if (allContestants.size() == numInitialContestants) { System.out.println("Too many contestants."); return; } if (isContestantIDInUse(c.getID())) { throw new InvalidFieldException( InvalidFieldException.Field.CONT_ID_DUP, "Contestant ID invald (in use)"); } allContestants.add(c); notifyAdd(UpdateTag.ADD_CONTESTANT); } /** * Sets the contestant who is to be eliminated. * * @param elimCont */ protected void setElimCont(Contestant elimCont) { this.elimCont = elimCont; } /** * Sets the elimExists variable * * @param elimExists true or false */ protected void setElimExists(boolean elimExists) { this.elimExists = elimExists; } /** * removeContestant takes a Contestant object as input and attempts to * remove it from the array of active contestants. Maintains order of data * * @param target * Contestant to remove */ public void removeContestant(Contestant target) { // is the contestant there? allContestants.remove(target); Collections.sort(allContestants); notifyAdd(UpdateTag.REMOVE_CONTESTANT); } /** * Sets who was cast off on a certain week * @param week */ public void setCastOff(int week, Contestant c){ castOffs[week] = c; } /** * setCastOff method specifically for JSON. */ public void setCastOffJSON(int week, Contestant c){ castOffs[week] = c; } // USER // /** * Adds a user to the list of users. * * @param u * New user to add. * @throws InvalidFieldException * Thrown if ID already in use. */ public void addUser(User u) throws InvalidFieldException { if (isUserIDInUse(u.getID())) { throw new InvalidFieldException( InvalidFieldException.Field.CONT_ID_DUP, "Contestant ID invald (in use)"); } allUsers.add(u); notifyAdd(UpdateTag.REMOVE_USER); } /** * Removes a user from the list. * * @param u * User to remove. */ public void removeUser(User u) { allUsers.remove(u); notifyAdd(UpdateTag.REMOVE_USER); } // ---- GAMEDATA INFORMATION ---- // // ACCESSOR METHODS // /** * Returns the initial bet amount. * @return */ public int getBetAmount() { return betAmount; } /** * Returns the currently stored Game, this removed need to reference the * game data all the time. But also allows objects to read data, cleanly. * * @return Currently started game, null if none present. */ public static GameData getCurrentGame() { return GameData.currentGame; } /** * Get the current week in play. Starts from Week 1. * * @return Current week */ public int getCurrentWeek() { return weeksPassed + 1; } /** * Returns the overall prize pool. * @return totalAmount */ public int getTotalAmount(){ return totalAmount; } /** * getTribeName returns a String array with two entries: the name of the * first tribe, and the name of the second tribe. * * @return String array tribe names */ public String[] getTribeNames() { return tribeNames; } /** * Checks if there are any more weeks remaining * * @return true if weeks remaining = 1 */ public boolean isFinalWeek() { return weeksRem == 1; } /** * Checks if there are any more weeks remaining * * @return true if weeks remaining = 0 */ public boolean isSeasonEnded() { return weeksRem == 0; } /** * Checks if a season has been started * * @see startGame to set to true. * @return true if a season has started(different from created) */ public boolean isSeasonStarted() { return seasonStarted; } /** * weeksLeft returns the number of weeks remaining before the game ends. * * @return this.weeksRem */ public int weeksLeft() { return weeksRem; } // MUTATOR METHODS // /** * Sets the initial bet amount. * @param betAmount */ public void setBetAmount(int betAmount) { this.betAmount = betAmount; } /** * Sets the overall prize pool. * @param total */ public void setTotalAmount(int total){ this.totalAmount = total; } /** * setTribeNames sets both tribe names accordingly and stores them in the * tribeNames string array. Updates all contestants accordingly * * @param tribeOne * name of tribe one * @param tribeTwo * name of tribe two */ public String[] setTribeNames(String tribeOne, String tribeTwo){ // temp tribe vars. String oldT1 = tribeNames[0]; String oldT2 = tribeNames[1]; // set the new tribes (Contestant requires this) tribeNames[0] = Utils.strCapitalize(tribeOne.toLowerCase().trim()); tribeNames[1] = Utils.strCapitalize(tribeTwo.toLowerCase().trim()); // update all tribes first.. for (Contestant c : allContestants) { if (c.getTribe().equalsIgnoreCase(oldT1)) { try { c.setTribe(tribeOne); } catch (InvalidFieldException e) { } } else if (c.getTribe().equalsIgnoreCase(oldT2)) { try { c.setTribe(tribeTwo); } catch (InvalidFieldException e) { } } } notifyAdd(UpdateTag.SET_TRIBE_NAMES); return tribeNames; } // ----------------- HELPER METHODS ----------------- // /** * advanceWeek sets the number of weeksPassed to weeksPassed + 1. */ public void advanceWeek() { if (elimExists == false) return; /* Fill weekly NULLs */ for (User u : allUsers) { if (u.getWeeklyPick().isNull() || u.getWeeklyPick() == null) { try { u.setWeeklyPick(randomContestant(true)); } catch (InvalidFieldException e) { } // wont happen } /* Fill ultimate NULLs */ if (u.getUltimatePick().isNull()) { try { u.setUltimatePick(randomContestant(true)); } catch (InvalidFieldException e) { } // wont happen } } checkPicks(); allocatePoints(getElimCont()); Contestant nullC = new Contestant(); nullC.setNull(); /* clear all weekly picks */ for (User u : allUsers) { try { u.setWeeklyPick(nullC); } catch (InvalidFieldException e) { } // wont happen /* clear defunct ult picks */ if (u.getUltimatePick().getID().equals(getElimCont().getID())) { try { u.setUltimatePick(nullC); } catch (InvalidFieldException e) { } // wont happen } } weeksRem -= 1; // reduce num of weeks remaining weeksPassed += 1; // increment number of weeks passed elimExists = false; elimCont = null; if (isFinalWeek()) notifyAdd(UpdateTag.FINAL_WEEK); else if (isSeasonEnded()) notifyAdd(UpdateTag.END_GAME); else notifyAdd(UpdateTag.ADVANCE_WEEK); } /** * Iterates through all users on the list. Allocates points based off of * weekly elimination pick. * * @param c * Contestant that was cast off */ public void allocatePoints(Contestant c) { Iterator<User> itr = allUsers.iterator(); User u; while (itr.hasNext()) { u = itr.next(); if (u.getWeeklyPick().equals(c)) { if (this.isFinalWeek()) // final week u.addPoints(40); else // normal week u.addPoints(20); } // if the end of the game and the person gets the right ultimate pick if (u.getUltimatePick().equals(c) && this.isFinalWeek()){ u.addPoints(u.getUltimatePoints()); } u.addPoints(u.getNumBonusAnswer() * 10); // add week's correct bonus questions u.setNumBonusAnswer(0); // clears the number of questions } notifyAdd(UpdateTag.ALLOCATE_POINTS); } /** * Casts a contestant from the game. * @param castOff */ public void castOff(int week, Contestant castOff) { if (castOff.isCastOff()) // can't recast off.. return; setElimCont(castOff); setElimExists(true); setCastOff(week,castOff); castOff.setCastDate(week); castOff.setToBeCast(true); notifyAdd(UpdateTag.CONTESTANT_CAST_OFF); } /** * Checks who was chosen as a weekly or ultimate pick. Sets the contestant's picked status to * true if selected. */ public void checkPicks(){ List<User> choices = getCurrentGame().getAllUsers(); for(User u : choices){ u.getWeeklyPick().selected(); u.getUltimatePick().selected(); } } /** * Returns the prize pool split. Accounts for one winner, two winners, and three winners. * * @return list of int values to give each user. */ public List<Integer> determinePrizePool(){ List<Integer> tempList = new ArrayList<Integer>(); int i = getAllUsers().size(); if (i <= 0){ // no users return null; } else if (i == 1) { // one user, he gets the whole pool tempList.add(getTotalAmount()); return tempList; } else if (i == 2) { // two users, first user gets 65% of the //winnings, the rest goes to the second tempList.add((int) (getTotalAmount()*0.65)); // first 65 tempList.add(getTotalAmount() - tempList.get(0)); // the rest } else { // three or more users // split is 60/30/10 tempList.add((int) (getTotalAmount()*0.60)); // first 60 // total amount - the first amount, which leaves 40% of the original amount // 30% is now equivalent to 75% of the new amount tempList.add((int) ((getTotalAmount()- tempList.get(0)) * 0.75)); // the total minus the first and second place winnings tempList.add(getTotalAmount() - tempList.get(0) - tempList.get(1)); } return tempList; } /** * Iterates through all players on the list, and determines the top three winners. * @param Player within the game. */ public List<User> determineWinners() { Iterator<User> itr = allUsers.iterator(); User u; User first = new User (); User second = new User (); User third = new User (); first.setPoints(-1); second.setPoints(-1); third.setPoints(-1); while (itr.hasNext()) { u = itr.next(); if (u.getPoints() > first.getPoints()) { third = second; second = first; first = u; } else if (u.getPoints() > second.getPoints()){ third = second; second = u; } else if (u.getPoints() > third.getPoints()){ third = u; } } List<User> tempList = new ArrayList<User>(); if (first.getPoints() != -1) tempList.add(first); if (second.getPoints() != -1) tempList.add(second); if (third.getPoints() != -1) tempList.add(third); return tempList; } /** * Nulls the current game stored, allows a new game to start. */ public void endCurrentGame() { Bonus.deleteAllQuestions(); // removed tag, as there's a different between END_GAME and a reset. JSONUtils.resetSeason(); GameData.currentGame = null; } /** * Helper method to get the index of a contestant ID in the * activeContestants array * * @param searchID * Search Contestant ID * @return Index in activeContestants where ID is stored, else < 0. */ protected int getContestantIndexID(String searchID) { return Utils.BinIDSearchSafe(allContestants, searchID); } /** * Gets a Users index in the stored list by ID. Uses a binary search for * speed. * * @param searchID * @return Index in the list, index <0 if not found. */ protected int getUserIndexID(String searchID) { return Utils.BinIDSearchSafe(allUsers, searchID); } /** * Tells whether a Contestant ID is in use. * * @param id * The Contestant ID is in use. * @return True if in use. */ public boolean isContestantIDInUse(String id) { return (getContestantIndexID(id) >= 0); } /** * Tells whether a User ID is in use. * * @param id * The Contestant ID is in use. * @return True if in use. */ public boolean isUserIDInUse(String id) { return (getUserIndexID(id) >= 0); } /** * Provides a random contestant. * * @param isActive * @return random contestant */ public Contestant randomContestant(boolean isActive) { List<Contestant> list = null; if (isActive) { list = getActiveContestants(true); list.add(getElimCont()); // elim contestant still active } else { list = getAllContestants(); } Random r = new Random(); int index = r.nextInt(list.size()); return list.get(index); } /** * startGame sets gameStarted to true, not allowing the admin to add any * more players/Contestants to the pool/game. */ public void startSeason(int bet) { this.setBetAmount(bet); this.setTotalAmount(bet * allUsers.size()); seasonStarted = true; notifyAdd(UpdateTag.START_SEASON); } /** * Undoes the current contestant that would be cast off. * @param castOff */ public void undoCastOff(int week, Contestant castOff) { castOff.setToBeCast(false); setElimCont(null); setElimExists(false); castOff.setCastDate(-1); notifyAdd(UpdateTag.CONTESTANT_CAST_OFF); } // ----------------- JSON ----------------- // /** * Convert GameData to a JSON object * * @return a JSONObject with all the relevant data * @throws JSONException */ public JSONObject toJSONObject() throws ParseException { JSONObject obj = new JSONObject(); obj.put(KEY_NUM_CONTEST, new Integer(numInitialContestants)); JSONArray cons = new JSONArray(); for (Object o : allContestants) { if (o != null) cons.add(((Contestant) o).toJSONObject()); } JSONArray users = new JSONArray(); for (Object o : allUsers) { if (o != null) users.add(((User) o).toJSONObject()); } JSONArray coffs = new JSONArray(); for(Contestant c : castOffs){ if(c != null) coffs.add(c.toJSONObject()); } JSONArray ts = new JSONArray(); ts.add(tribeNames[0]); ts.add(tribeNames[1]); obj.put(KEY_CONTESTANTS, cons); obj.put(KEY_USERS, users); obj.put(KEY_CAST_OFFS, coffs); obj.put(KEY_TRIBES, ts); obj.put(KEY_WEEKS_REMAIN, weeksRem); obj.put(KEY_WEEKS_PASSED, weeksPassed); obj.put(KEY_SEASON_STARTED, seasonStarted); if(seasonStarted){ obj.put(KEY_BET_AMOUNT, betAmount); obj.put(KEY_POOL_TOTAL, totalAmount); } return obj; } /** * Update GameData with values from JSONObject * * @param obj * a JSONObject that contains all the values * @throws JSONException */ public void fromJSONObject(JSONObject obj) throws ParseException { numInitialContestants = ((Number) obj.get(KEY_NUM_CONTEST)).intValue(); // tribes JSONArray ts = (JSONArray) obj.get(KEY_TRIBES); setTribeNames((String) ts.get(0), (String) ts.get(1)); // week info: weeksRem = Utils.numToInt(obj.get(KEY_WEEKS_REMAIN)); weeksPassed = Utils.numToInt(obj.get(KEY_WEEKS_PASSED)); seasonStarted = (Boolean) obj.get(KEY_SEASON_STARTED); if(seasonStarted){ betAmount = Utils.numToInt(obj.get(KEY_BET_AMOUNT)); totalAmount = Utils.numToInt(obj.get(KEY_POOL_TOTAL)); System.out.println(betAmount + " " + totalAmount); } // Contestants must be loaded before users, but after others! allContestants = new ArrayList<Contestant>(numInitialContestants); // load the contestant array. JSONArray cons = (JSONArray) obj.get(KEY_CONTESTANTS); for (int i = 0; i < cons.size(); i++) { Contestant c = new Contestant(); c.fromJSONObject((JSONObject)cons.get(i)); try { addContestant(c); + if(c.getCastDate() == getCurrentWeek()){ + this.setElimCont(c); + this.setElimExists(true); + } } catch (InvalidFieldException ie) { } } // load the cast offs JSONArray coffs = (JSONArray) obj.get(KEY_CAST_OFFS); if(getCurrentWeek() != 1 && seasonStarted){ for(int i = 0; i < coffs.size(); i++){ Contestant c = new Contestant(); c.fromJSONObject((JSONObject)coffs.get(i)); try{ setCastOffJSON(i,c); }catch(NullPointerException ie){ } } } // users: JSONArray users = (JSONArray) obj.get(KEY_USERS); allUsers = new ArrayList<User>(users.size()); for (int i = 0; i < users.size(); i++) { User u = new User(); u.fromJSONObject((JSONObject)users.get(i)); try { addUser(u); } catch (InvalidFieldException ie) { } if(getCurrentWeek() >= 2); } notifyAdd(); } /** * Write all DATA into file */ public void writeData() { try { JSONUtils.writeJSON(JSONUtils.pathGame, toJSONObject()); } catch (ParseException e) { e.printStackTrace(); } } // ---------------- INITIATION METHODS --------------- // /** * Used by SeasonCreate to create a new season. * * @param num */ public static void initSeason(int num) { currentGame = new GameData(num); } /** * intGameData reads in a data file and builds a GameData object out of it, * returning it to the user. * * @param inputFile * file to be read in * @return GameData object made out of file or null if season not created * */ public static GameData initGameData() { JSONObject json; try { json = JSONUtils.readFile(JSONUtils.pathGame); } catch (FileNotFoundException e) { return currentGame; } currentGame = new GameData( Utils.numToInt(json.get(KEY_NUM_CONTEST))); // TODO: Combine? try { GameData.getCurrentGame().fromJSONObject(json); } catch (ParseException e) { e.printStackTrace(); } return currentGame; } // ---------------- MISC --------------- // /** * toString returns a string of the contestant's information in JSON format. */ public String toString() { return new String("GameData<WR:\"" + weeksRem + "\"" + ", WP:\"" + weeksPassed + "\"" + ", #C:\"" + numInitialContestants + "\"" + ", SS: " + "\"" + seasonStarted + "\"" + ", TN: {" + "\"" + tribeNames[0] + "\", \"" + tribeNames[1] + "\"}>"); } /** * Small class used for removing parallel calls to do the same * notification. The update system accounts for multiple modifications * in one update call, so this means those methods are only called once. * @author Kevin Brightwell */ private class UpdateCall implements Runnable { public EnumSet<UpdateTag> mods = EnumSet.noneOf(UpdateTag.class); public boolean done = false; public void run() { setChanged(); notifyObservers(mods); done = true; } } /** * Adds a set of {@link GameData.UpdateTag}s to the next update call. This * method in conjunction with {@link GameData.UpdateCall} works to remove * excess method executions. * @param tags Tags to add to the next call. */ public void notifyAdd(UpdateTag... tags) { if (updateExec == null || updateExec.done){ updateExec = new UpdateCall(); SwingUtilities.invokeLater(updateExec); } for (UpdateTag ut: tags) { if (!updateExec.mods.contains(ut)) updateExec.mods.add(ut); } } // ----------------- TEST DRIVER ------------------// public static void main(String[] args) { GameData g = new GameData(6); String[] tribes = new String[] { "banana", "apple" }; g.setTribeNames(tribes[0], tribes[1]); Contestant c1 = null, c2 = null; try { c1 = new Contestant("a2", "Al", "Sd", tribes[1]); c2 = new Contestant("as", "John", "Silver", tribes[0]); } catch (InvalidFieldException e) { // wont happen. } try { g.addContestant(c1); g.addContestant(c2); } catch (InvalidFieldException ie) { } g.startSeason(5); User u1; try { u1 = new User("First", "last", "flast"); User u2 = new User("Firsto", "lasto", "flasto"); g.addUser(u1); g.addUser(u2); u1.setPoints(10); u2.setPoints(1); } catch (InvalidFieldException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } try { System.out.println(g.toJSONObject().toString()); } catch (ParseException e1) { e1.printStackTrace(); } } /** * Creates a EnumSet of the tags passed, allowing for flexible notions * of multiple tags sent. * @param tags Sets the flags of the set. * @return EnumSet containing the tags passed. */ /*private EnumSet updateTagSet(UpdateTag... tags) { EnumSet set = new EnumSet(UpdateTag.class); return set.of(tags); }*/ }
true
true
public void fromJSONObject(JSONObject obj) throws ParseException { numInitialContestants = ((Number) obj.get(KEY_NUM_CONTEST)).intValue(); // tribes JSONArray ts = (JSONArray) obj.get(KEY_TRIBES); setTribeNames((String) ts.get(0), (String) ts.get(1)); // week info: weeksRem = Utils.numToInt(obj.get(KEY_WEEKS_REMAIN)); weeksPassed = Utils.numToInt(obj.get(KEY_WEEKS_PASSED)); seasonStarted = (Boolean) obj.get(KEY_SEASON_STARTED); if(seasonStarted){ betAmount = Utils.numToInt(obj.get(KEY_BET_AMOUNT)); totalAmount = Utils.numToInt(obj.get(KEY_POOL_TOTAL)); System.out.println(betAmount + " " + totalAmount); } // Contestants must be loaded before users, but after others! allContestants = new ArrayList<Contestant>(numInitialContestants); // load the contestant array. JSONArray cons = (JSONArray) obj.get(KEY_CONTESTANTS); for (int i = 0; i < cons.size(); i++) { Contestant c = new Contestant(); c.fromJSONObject((JSONObject)cons.get(i)); try { addContestant(c); } catch (InvalidFieldException ie) { } } // load the cast offs JSONArray coffs = (JSONArray) obj.get(KEY_CAST_OFFS); if(getCurrentWeek() != 1 && seasonStarted){ for(int i = 0; i < coffs.size(); i++){ Contestant c = new Contestant(); c.fromJSONObject((JSONObject)coffs.get(i)); try{ setCastOffJSON(i,c); }catch(NullPointerException ie){ } } } // users: JSONArray users = (JSONArray) obj.get(KEY_USERS); allUsers = new ArrayList<User>(users.size()); for (int i = 0; i < users.size(); i++) { User u = new User(); u.fromJSONObject((JSONObject)users.get(i)); try { addUser(u); } catch (InvalidFieldException ie) { } if(getCurrentWeek() >= 2); } notifyAdd(); }
public void fromJSONObject(JSONObject obj) throws ParseException { numInitialContestants = ((Number) obj.get(KEY_NUM_CONTEST)).intValue(); // tribes JSONArray ts = (JSONArray) obj.get(KEY_TRIBES); setTribeNames((String) ts.get(0), (String) ts.get(1)); // week info: weeksRem = Utils.numToInt(obj.get(KEY_WEEKS_REMAIN)); weeksPassed = Utils.numToInt(obj.get(KEY_WEEKS_PASSED)); seasonStarted = (Boolean) obj.get(KEY_SEASON_STARTED); if(seasonStarted){ betAmount = Utils.numToInt(obj.get(KEY_BET_AMOUNT)); totalAmount = Utils.numToInt(obj.get(KEY_POOL_TOTAL)); System.out.println(betAmount + " " + totalAmount); } // Contestants must be loaded before users, but after others! allContestants = new ArrayList<Contestant>(numInitialContestants); // load the contestant array. JSONArray cons = (JSONArray) obj.get(KEY_CONTESTANTS); for (int i = 0; i < cons.size(); i++) { Contestant c = new Contestant(); c.fromJSONObject((JSONObject)cons.get(i)); try { addContestant(c); if(c.getCastDate() == getCurrentWeek()){ this.setElimCont(c); this.setElimExists(true); } } catch (InvalidFieldException ie) { } } // load the cast offs JSONArray coffs = (JSONArray) obj.get(KEY_CAST_OFFS); if(getCurrentWeek() != 1 && seasonStarted){ for(int i = 0; i < coffs.size(); i++){ Contestant c = new Contestant(); c.fromJSONObject((JSONObject)coffs.get(i)); try{ setCastOffJSON(i,c); }catch(NullPointerException ie){ } } } // users: JSONArray users = (JSONArray) obj.get(KEY_USERS); allUsers = new ArrayList<User>(users.size()); for (int i = 0; i < users.size(); i++) { User u = new User(); u.fromJSONObject((JSONObject)users.get(i)); try { addUser(u); } catch (InvalidFieldException ie) { } if(getCurrentWeek() >= 2); } notifyAdd(); }
diff --git a/src/com/vmware/vim25/mo/samples/QueryEvent.java b/src/com/vmware/vim25/mo/samples/QueryEvent.java index 969ae8a..0eb1e41 100644 --- a/src/com/vmware/vim25/mo/samples/QueryEvent.java +++ b/src/com/vmware/vim25/mo/samples/QueryEvent.java @@ -1,106 +1,106 @@ /*================================================================================ Copyright (c) 2008 VMware, Inc. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of VMware, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ================================================================================*/ package com.vmware.vim25.mo.samples; import java.net.URL; import com.vmware.vim25.Event; import com.vmware.vim25.EventFilterSpec; import com.vmware.vim25.mo.EventHistoryCollector; import com.vmware.vim25.mo.EventManager; import com.vmware.vim25.mo.ServiceInstance; import com.vmware.vim25.mo.util.CommandLineParser; import com.vmware.vim25.mo.util.OptionSpec; /** * This sample shows you how to get filtered events from VC * * @author Tom Elliott (twelliott - [email protected]) * */ public class QueryEvent { private static void usage() { System.err.println("Usage: QueryEvent server username password"); } public static void main(String[] args) throws Exception { if (args.length != 3) { usage(); return; } String urlStr = args[0]; String username = args[1]; String password = args[2]; System.out.println("Connecting to " + urlStr + " as " + username); ServiceInstance si = new ServiceInstance(new URL(urlStr), username, password, true); System.out.println("info---" + si.getAboutInfo().getFullName()); // Displays all the Events with Full Formatted message try { EventManager _eventManager = si.getEventManager(); EventFilterSpec eventFilter = new EventFilterSpec(); EventHistoryCollector history = _eventManager .createCollectorForEvents(eventFilter); - Event[] events = history.getLastPage(); + Event[] events = history.getLatestPage(); System.out.println("Events In the latestPage are : "); for (int i = 0; i < events.length; i++) { Event anEvent = events[i]; System.out.println("Event: " + anEvent.getClass().getName() + " FullFormattedMessage: " + anEvent.getFullFormattedMessage()); } } catch (Exception e) { System.out.println("Caught Exception : " + " Name : " + e.getClass().getName() + " Message : " + e.getMessage() + " Trace : "); e.printStackTrace(); } si.getServerConnection().logout(); } }
true
true
public static void main(String[] args) throws Exception { if (args.length != 3) { usage(); return; } String urlStr = args[0]; String username = args[1]; String password = args[2]; System.out.println("Connecting to " + urlStr + " as " + username); ServiceInstance si = new ServiceInstance(new URL(urlStr), username, password, true); System.out.println("info---" + si.getAboutInfo().getFullName()); // Displays all the Events with Full Formatted message try { EventManager _eventManager = si.getEventManager(); EventFilterSpec eventFilter = new EventFilterSpec(); EventHistoryCollector history = _eventManager .createCollectorForEvents(eventFilter); Event[] events = history.getLastPage(); System.out.println("Events In the latestPage are : "); for (int i = 0; i < events.length; i++) { Event anEvent = events[i]; System.out.println("Event: " + anEvent.getClass().getName() + " FullFormattedMessage: " + anEvent.getFullFormattedMessage()); } } catch (Exception e) { System.out.println("Caught Exception : " + " Name : " + e.getClass().getName() + " Message : " + e.getMessage() + " Trace : "); e.printStackTrace(); } si.getServerConnection().logout(); }
public static void main(String[] args) throws Exception { if (args.length != 3) { usage(); return; } String urlStr = args[0]; String username = args[1]; String password = args[2]; System.out.println("Connecting to " + urlStr + " as " + username); ServiceInstance si = new ServiceInstance(new URL(urlStr), username, password, true); System.out.println("info---" + si.getAboutInfo().getFullName()); // Displays all the Events with Full Formatted message try { EventManager _eventManager = si.getEventManager(); EventFilterSpec eventFilter = new EventFilterSpec(); EventHistoryCollector history = _eventManager .createCollectorForEvents(eventFilter); Event[] events = history.getLatestPage(); System.out.println("Events In the latestPage are : "); for (int i = 0; i < events.length; i++) { Event anEvent = events[i]; System.out.println("Event: " + anEvent.getClass().getName() + " FullFormattedMessage: " + anEvent.getFullFormattedMessage()); } } catch (Exception e) { System.out.println("Caught Exception : " + " Name : " + e.getClass().getName() + " Message : " + e.getMessage() + " Trace : "); e.printStackTrace(); } si.getServerConnection().logout(); }
diff --git a/SWADroid/src/es/ugr/swad/swadroid/modules/rollcall/sessions/SessionsList.java b/SWADroid/src/es/ugr/swad/swadroid/modules/rollcall/sessions/SessionsList.java index 88039e40..e8a9064f 100644 --- a/SWADroid/src/es/ugr/swad/swadroid/modules/rollcall/sessions/SessionsList.java +++ b/SWADroid/src/es/ugr/swad/swadroid/modules/rollcall/sessions/SessionsList.java @@ -1,166 +1,166 @@ /* * This file is part of SWADroid. * * Copyright (C) 2010 Juan Miguel Boyero Corral <[email protected]> * * SWADroid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SWADroid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with SWADroid. If not, see <http://www.gnu.org/licenses/>. */ package es.ugr.swad.swadroid.modules.rollcall.sessions; import java.io.IOException; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.ksoap2.SoapFault; import org.xmlpull.v1.XmlPullParserException; import android.app.Dialog; import android.content.DialogInterface; import android.content.DialogInterface.OnKeyListener; import android.content.Intent; import android.os.Bundle; import android.view.KeyEvent; import android.widget.LinearLayout.LayoutParams; import android.widget.ListView; import es.ugr.swad.swadroid.Global; import es.ugr.swad.swadroid.R; import es.ugr.swad.swadroid.model.Group; import es.ugr.swad.swadroid.model.PracticeSession; import es.ugr.swad.swadroid.modules.Module; /** * Sessions list module. * @author Antonio Aguilera Malagon <[email protected]> */ public class SessionsList extends Module { private Dialog sessionsDialog; /** * Sessions List tag name for Logcat */ public static final String TAG = Global.APP_TAG + " SessionsList"; /* (non-Javadoc) * @see es.ugr.swad.swadroid.modules.Module#onCreate(android.os.Bundle) */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } /* (non-Javadoc) * @see es.ugr.swad.swadroid.modules.Module#onStart() */ @Override protected void onStart() { sessionsDialog = new Dialog(this); super.onStart(); sessionsDialog.setTitle(R.string.sessionsTitle); sessionsDialog.setCancelable(true); sessionsDialog.getWindow().setLayout(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); sessionsDialog.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { sessionsDialog.dismiss(); setResult(RESULT_OK); SessionsList.this.finish(); } return false; } }); initialize(); } /* (non-Javadoc) * @see es.ugr.swad.swadroid.modules.Module#onPause() */ @Override protected void onPause() { super.onPause(); sessionsDialog.dismiss(); } private void initialize() { List<SessionItemModel> sessionList = null; long courseCode = Global.getSelectedCourseCode(); Intent intent = getIntent(); long studentId = intent.getLongExtra("studentId", (long) 0); boolean existSessions = false; // Get practice groups of selected course - List<Long> groupIdList = dbHelper.getGroupsCourse(courseCode); + List<Long> groupIdList = dbHelper.getGroupCodesCourse(courseCode); ListView lv = new ListView(this); SeparatedListAdapter adapter = new SeparatedListAdapter(this); // For each practice group, show practice sessions for (Long groupCode: groupIdList) { Group g = dbHelper.getGroup(groupCode); // Get practice sessions List<PracticeSession> ps = dbHelper.getPracticeSessions(courseCode, groupCode); int numSessions = ps.size(); if (numSessions > 0) { existSessions = true; sessionList = new ArrayList<SessionItemModel>(); for (int i=0; i < numSessions; i++) { boolean attended = dbHelper.hasAttendedSession(studentId, ps.get(i).getId()); SessionItemModel sim = new SessionItemModel(ps.get(i).getSessionStart(), attended); sessionList.add(sim); } // Arrange the list alphabetically Collections.sort(sessionList); adapter.addSection(getString(R.string.group) + " " + g.getGroupName(), new SessionsArrayAdapter(this, sessionList)); } } lv.setAdapter(adapter); sessionsDialog.setContentView(lv); if (!existSessions) { setResult(RESULT_CANCELED); finish(); } else sessionsDialog.show(); } @Override protected void requestService() throws NoSuchAlgorithmException, IOException, XmlPullParserException, SoapFault, IllegalAccessException, InstantiationException { } @Override protected void connect() { } @Override protected void postConnect() { } @Override protected void onError() { } }
true
true
private void initialize() { List<SessionItemModel> sessionList = null; long courseCode = Global.getSelectedCourseCode(); Intent intent = getIntent(); long studentId = intent.getLongExtra("studentId", (long) 0); boolean existSessions = false; // Get practice groups of selected course List<Long> groupIdList = dbHelper.getGroupsCourse(courseCode); ListView lv = new ListView(this); SeparatedListAdapter adapter = new SeparatedListAdapter(this); // For each practice group, show practice sessions for (Long groupCode: groupIdList) { Group g = dbHelper.getGroup(groupCode); // Get practice sessions List<PracticeSession> ps = dbHelper.getPracticeSessions(courseCode, groupCode); int numSessions = ps.size(); if (numSessions > 0) { existSessions = true; sessionList = new ArrayList<SessionItemModel>(); for (int i=0; i < numSessions; i++) { boolean attended = dbHelper.hasAttendedSession(studentId, ps.get(i).getId()); SessionItemModel sim = new SessionItemModel(ps.get(i).getSessionStart(), attended); sessionList.add(sim); } // Arrange the list alphabetically Collections.sort(sessionList); adapter.addSection(getString(R.string.group) + " " + g.getGroupName(), new SessionsArrayAdapter(this, sessionList)); } } lv.setAdapter(adapter); sessionsDialog.setContentView(lv); if (!existSessions) { setResult(RESULT_CANCELED); finish(); } else sessionsDialog.show(); }
private void initialize() { List<SessionItemModel> sessionList = null; long courseCode = Global.getSelectedCourseCode(); Intent intent = getIntent(); long studentId = intent.getLongExtra("studentId", (long) 0); boolean existSessions = false; // Get practice groups of selected course List<Long> groupIdList = dbHelper.getGroupCodesCourse(courseCode); ListView lv = new ListView(this); SeparatedListAdapter adapter = new SeparatedListAdapter(this); // For each practice group, show practice sessions for (Long groupCode: groupIdList) { Group g = dbHelper.getGroup(groupCode); // Get practice sessions List<PracticeSession> ps = dbHelper.getPracticeSessions(courseCode, groupCode); int numSessions = ps.size(); if (numSessions > 0) { existSessions = true; sessionList = new ArrayList<SessionItemModel>(); for (int i=0; i < numSessions; i++) { boolean attended = dbHelper.hasAttendedSession(studentId, ps.get(i).getId()); SessionItemModel sim = new SessionItemModel(ps.get(i).getSessionStart(), attended); sessionList.add(sim); } // Arrange the list alphabetically Collections.sort(sessionList); adapter.addSection(getString(R.string.group) + " " + g.getGroupName(), new SessionsArrayAdapter(this, sessionList)); } } lv.setAdapter(adapter); sessionsDialog.setContentView(lv); if (!existSessions) { setResult(RESULT_CANCELED); finish(); } else sessionsDialog.show(); }
diff --git a/net.sourceforge.vrapper.eclipse/src/net/sourceforge/vrapper/eclipse/platform/EclipseCursorAndSelection.java b/net.sourceforge.vrapper.eclipse/src/net/sourceforge/vrapper/eclipse/platform/EclipseCursorAndSelection.java index 94fdec2a..170653a3 100644 --- a/net.sourceforge.vrapper.eclipse/src/net/sourceforge/vrapper/eclipse/platform/EclipseCursorAndSelection.java +++ b/net.sourceforge.vrapper.eclipse/src/net/sourceforge/vrapper/eclipse/platform/EclipseCursorAndSelection.java @@ -1,399 +1,398 @@ package net.sourceforge.vrapper.eclipse.platform; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import net.sourceforge.vrapper.eclipse.ui.CaretUtils; import net.sourceforge.vrapper.log.VrapperLog; import net.sourceforge.vrapper.platform.Configuration; import net.sourceforge.vrapper.platform.CursorService; import net.sourceforge.vrapper.platform.SelectionService; import net.sourceforge.vrapper.utils.CaretType; import net.sourceforge.vrapper.utils.ContentType; import net.sourceforge.vrapper.utils.LineInformation; import net.sourceforge.vrapper.utils.Position; import net.sourceforge.vrapper.utils.Space; import net.sourceforge.vrapper.utils.StartEndTextRange; import net.sourceforge.vrapper.utils.VimUtils; import net.sourceforge.vrapper.vim.commands.BlockWiseSelection; import net.sourceforge.vrapper.vim.commands.BlockWiseSelection.Rect; import net.sourceforge.vrapper.vim.commands.Selection; import net.sourceforge.vrapper.vim.commands.SimpleSelection; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.ITextViewerExtension5; import org.eclipse.swt.custom.CaretEvent; import org.eclipse.swt.custom.CaretListener; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Caret; public class EclipseCursorAndSelection implements CursorService, SelectionService { public static final String POSITION_CATEGORY_NAME = "net.sourceforge.vrapper.position"; private final ITextViewer textViewer; private int stickyColumn; private boolean stickToEOL = false; private final ITextViewerExtension5 converter; private Selection selection; private final SelectionChangeListener selectionChangeListener; private final StickyColumnUpdater caretListener; private final Map<String, org.eclipse.jface.text.Position> marks; private final List<org.eclipse.jface.text.Position> changeList; private int changeListIndex; private final Configuration configuration; private final EclipseTextContent textContent; public EclipseCursorAndSelection(final Configuration configuration, final ITextViewer textViewer, final EclipseTextContent textContent) { this.configuration = configuration; this.textViewer = textViewer; this.textContent = textContent; StyledText tw = textViewer.getTextWidget(); this.stickyColumn = tw.getLeftMargin(); converter = OffsetConverter.create(textViewer); selectionChangeListener = new SelectionChangeListener(); caretListener = new StickyColumnUpdater(); marks = new HashMap<String, org.eclipse.jface.text.Position>(); changeList = new ArrayList<org.eclipse.jface.text.Position>(); textViewer.getTextWidget().addSelectionListener(selectionChangeListener); textViewer.getTextWidget().addCaretListener(caretListener); textViewer.getDocument().addPositionCategory(POSITION_CATEGORY_NAME); } @Override public Position getPosition() { return new TextViewerPosition(textViewer, Space.VIEW, textViewer.getTextWidget().getCaretOffset()); } @Override public void setPosition(final Position position, final boolean updateColumn) { if (!updateColumn) { caretListener.disable(); } int viewOffset = position.getViewOffset(); if (viewOffset < 0) { //Something went screwy, avoid getting into a bad state. //Just put the cursor at offset 0. viewOffset = 0; } textViewer.getTextWidget().setSelection(viewOffset); caretListener.enable(); } @Override public Position stickyColumnAtViewLine(final int lineNo) { // FIXME: do this properly final StyledText tw = textViewer.getTextWidget(); if (!stickToEOL) { try { final int y = tw.getLocationAtOffset(tw.getOffsetAtLine(lineNo)).y; final int offset = tw.getOffsetAtLocation(new Point(stickyColumn - tw.getHorizontalPixel(), y)); return new TextViewerPosition(textViewer, Space.VIEW, offset); } catch (final IllegalArgumentException e) { // fall through silently and return line end } } try { final int line = converter.widgetLine2ModelLine(lineNo); final int lineLen = textViewer.getDocument().getLineLength(line); final String nl = textViewer.getDocument().getLineDelimiter(line); final int nlLen = nl != null ? nl.length() : 0; final int offset = tw.getOffsetAtLine(lineNo) + lineLen - nlLen; return new TextViewerPosition(textViewer, Space.VIEW, offset); } catch (final BadLocationException e) { throw new RuntimeException(e); } } @Override public Position stickyColumnAtModelLine(final int lineNo) { // FIXME: do this properly if (stickToEOL) { try { final int lineLength = textViewer.getDocument().getLineLength(lineNo); //getLineLength includes the line's delimiter //we need to find the last non-delimiter character final int startOffset = textViewer.getDocument().getLineInformation(lineNo).getOffset(); int endOffset = startOffset + lineLength; //don't leave the cursor on a newline if(lineLength > 0) { endOffset--; } //check for multi-byte (windows) line-endings (\r\n) if(endOffset > startOffset && VimUtils.isNewLine(textContent.getModelContent().getText(endOffset, 1))) { endOffset--; } return new TextViewerPosition(textViewer, Space.MODEL, endOffset); } catch (final Exception e) { throw new RuntimeException(e); } } else { try { return stickyColumnAtViewLine(converter.modelLine2WidgetLine(lineNo)); } catch (final RuntimeException e) { try { final int caretOffset = converter.widgetOffset2ModelOffset(textViewer.getTextWidget().getCaretOffset()); final int lineOffset = textViewer.getDocument().getLineInformationOfOffset(caretOffset).getOffset(); final int y = Math.abs(caretOffset - lineOffset); final IRegion line = textViewer.getDocument().getLineInformation(lineNo); final int offset = line.getOffset() + Math.min(y, line.getLength()); return new TextViewerPosition(textViewer, Space.MODEL, offset); } catch (final BadLocationException e1) { throw new RuntimeException(e1); } } } } @Override public Selection getSelection() { if (selection != null) { return selection; } int start, end, pos, len; start = end = textViewer.getSelectedRange().x; len = textViewer.getSelectedRange().y; pos = converter.widgetOffset2ModelOffset(textViewer.getTextWidget().getCaretOffset()); if (start == pos) { start += len+1; } else { end += len; } final Position from = new TextViewerPosition(textViewer, Space.MODEL, start); final Position to = new TextViewerPosition(textViewer, Space.MODEL, end); return new SimpleSelection(new StartEndTextRange(from, to)); } @Override public void setSelection(final Selection newSelection) { if (newSelection == null) { final Point point = textViewer.getSelectedRange(); textViewer.getTextWidget().setBlockSelection(false); textViewer.setSelectedRange(point.x, 0); selection = null; } else { - textViewer.getTextWidget().setCaretOffset(newSelection.getStart().getViewOffset()); final int from = newSelection.getStart().getModelOffset(); int length = !newSelection.isReversed() ? newSelection.getModelLength() : -newSelection.getModelLength(); // linewise selection includes final newline, this means the cursor // is placed in the line below the selection by eclipse. this // corrects that behaviour if (ContentType.LINES.equals(newSelection.getContentType(configuration))) { if (!newSelection.isReversed()) { length -=1; } } selection = newSelection; selectionChangeListener.disable(); if (ContentType.TEXT_RECTANGLE.equals(newSelection.getContentType(configuration))) { // block selection final StyledText styled = textViewer.getTextWidget(); styled.setBlockSelection(true); final Rect rect = BlockWiseSelection.getViewRect(textContent.getViewContent(), newSelection); // convert to units Eclipse wants // final int charWidth = JFaceTextUtil.getAverageCharWidth(styled); final int yPixel = styled.getLinePixel(rect.top); final int hPixel = styled.getLinePixel(rect.bottom + 1) - yPixel; final int start = rect.getULOffset(textContent.getViewContent()); final Rectangle row = styled.getTextBounds(start, start + rect.width()); final int xPixel = row.x; final int wPixel = row.width; // getLinePixel is relative to the top of the viewport, // not the top of the document; however, setBlockSelectionBounds // wants pixels relative to the document. awesome final int scrollOffsetY = styled.getTopPixel() + yPixel; // getTextBounds is apparently also relative to the viewport final int scrollOffsetX = styled.getHorizontalPixel() + xPixel; styled.setBlockSelectionBounds( scrollOffsetX, scrollOffsetY, wPixel, hPixel); } else { textViewer.getTextWidget().setBlockSelection(false); textViewer.setSelectedRange(from, length); } selectionChangeListener.enable(); } } @Override public Position newPositionForModelOffset(final int offset) { return new TextViewerPosition(textViewer, Space.MODEL, offset); } @Override public Position newPositionForViewOffset(final int offset) { return new TextViewerPosition(textViewer, Space.VIEW, offset); } @Override public void setCaret(final CaretType caretType) { final StyledText styledText = textViewer.getTextWidget(); final Caret old = styledText.getCaret(); styledText.setCaret(CaretUtils.createCaret(caretType, styledText)); // old caret is not disposed automatically old.dispose(); } @Override public void stickToEOL() { stickToEOL = true; } private final class SelectionChangeListener implements SelectionListener { boolean enabled = true; @Override public void widgetDefaultSelected(final SelectionEvent arg0) { if (enabled) { selection = null; } } @Override public void widgetSelected(final SelectionEvent arg0) { if (enabled) { selection = null; } } public void enable() { enabled = true; } public void disable() { enabled = false; } } private final class StickyColumnUpdater implements CaretListener { boolean enabled = true; @Override public void caretMoved(final CaretEvent e) { if (enabled) { final int offset = e.caretOffset; StyledText textWidget = textViewer.getTextWidget(); stickyColumn = textWidget.getLocationAtOffset(offset).x + textWidget.getHorizontalPixel(); // if the user clicks to the right of the line end // (i.e. the newline is selected) stick to EOL final LineInformation line = textContent.getViewContent().getLineInformationOfOffset(offset); stickToEOL = offset >= line.getEndOffset(); } } public void enable() { enabled = true; } public void disable() { enabled = false; } } @Override public void setMark(final String id, final Position position) { final org.eclipse.jface.text.Position p = new org.eclipse.jface.text.Position(position.getModelOffset()); try { //add listener so Position automatically updates as the document changes textViewer.getDocument().addPosition(p); } catch (final BadLocationException e) { e.printStackTrace(); return; } if(id == LAST_EDIT_MARK) { changeList.add(p); if(changeList.size() > 100) { //remove (and stop tracking changes for) old positions textViewer.getDocument().removePosition( changeList.remove(0) ); } //new edit, restart index position changeListIndex = changeList.size(); } else if(marks.containsKey(id)) { //we're about to overwrite an old position //no need to track its changes anymore textViewer.getDocument().removePosition( marks.get(id) ); } //update mark position marks.put(id, p); } @Override public Position getMark(String id) { //`` and '' are the same position, so we need to return that position //regardless of which way the user accessed it if(id.equals("`")) { id = LAST_JUMP_MARK; } final org.eclipse.jface.text.Position p = marks.get(id); if (p == null || p.isDeleted) { //leave deleted entries in marks Map //in case an 'undo' brings it back return null; } final int offset = p.getOffset(); return newPositionForModelOffset(offset); } @Override public Position getNextChangeLocation(final int count) { final int index = changeListIndex + count; return getChangeLocation(index); } @Override public Position getPrevChangeLocation(final int count) { final int index = changeListIndex - count; return getChangeLocation(index); } private Position getChangeLocation(int index) { if(changeList.size() == 0) { return null; } if(index < 0) { index = 0; } else if(index >= changeList.size()) { index = changeList.size() -1; } final org.eclipse.jface.text.Position p = changeList.get(index); if(p == null || p.isDeleted) { changeList.remove(index); changeListIndex = changeList.size(); if(p != null) { //deleted textViewer.getDocument().removePosition(p); } return null; } else { changeListIndex = index; //prepare for next invocation return newPositionForModelOffset(p.getOffset()); } } }
true
true
public void setSelection(final Selection newSelection) { if (newSelection == null) { final Point point = textViewer.getSelectedRange(); textViewer.getTextWidget().setBlockSelection(false); textViewer.setSelectedRange(point.x, 0); selection = null; } else { textViewer.getTextWidget().setCaretOffset(newSelection.getStart().getViewOffset()); final int from = newSelection.getStart().getModelOffset(); int length = !newSelection.isReversed() ? newSelection.getModelLength() : -newSelection.getModelLength(); // linewise selection includes final newline, this means the cursor // is placed in the line below the selection by eclipse. this // corrects that behaviour if (ContentType.LINES.equals(newSelection.getContentType(configuration))) { if (!newSelection.isReversed()) { length -=1; } } selection = newSelection; selectionChangeListener.disable(); if (ContentType.TEXT_RECTANGLE.equals(newSelection.getContentType(configuration))) { // block selection final StyledText styled = textViewer.getTextWidget(); styled.setBlockSelection(true); final Rect rect = BlockWiseSelection.getViewRect(textContent.getViewContent(), newSelection); // convert to units Eclipse wants // final int charWidth = JFaceTextUtil.getAverageCharWidth(styled); final int yPixel = styled.getLinePixel(rect.top); final int hPixel = styled.getLinePixel(rect.bottom + 1) - yPixel; final int start = rect.getULOffset(textContent.getViewContent()); final Rectangle row = styled.getTextBounds(start, start + rect.width()); final int xPixel = row.x; final int wPixel = row.width; // getLinePixel is relative to the top of the viewport, // not the top of the document; however, setBlockSelectionBounds // wants pixels relative to the document. awesome final int scrollOffsetY = styled.getTopPixel() + yPixel; // getTextBounds is apparently also relative to the viewport final int scrollOffsetX = styled.getHorizontalPixel() + xPixel; styled.setBlockSelectionBounds( scrollOffsetX, scrollOffsetY, wPixel, hPixel); } else { textViewer.getTextWidget().setBlockSelection(false); textViewer.setSelectedRange(from, length); } selectionChangeListener.enable(); } }
public void setSelection(final Selection newSelection) { if (newSelection == null) { final Point point = textViewer.getSelectedRange(); textViewer.getTextWidget().setBlockSelection(false); textViewer.setSelectedRange(point.x, 0); selection = null; } else { final int from = newSelection.getStart().getModelOffset(); int length = !newSelection.isReversed() ? newSelection.getModelLength() : -newSelection.getModelLength(); // linewise selection includes final newline, this means the cursor // is placed in the line below the selection by eclipse. this // corrects that behaviour if (ContentType.LINES.equals(newSelection.getContentType(configuration))) { if (!newSelection.isReversed()) { length -=1; } } selection = newSelection; selectionChangeListener.disable(); if (ContentType.TEXT_RECTANGLE.equals(newSelection.getContentType(configuration))) { // block selection final StyledText styled = textViewer.getTextWidget(); styled.setBlockSelection(true); final Rect rect = BlockWiseSelection.getViewRect(textContent.getViewContent(), newSelection); // convert to units Eclipse wants // final int charWidth = JFaceTextUtil.getAverageCharWidth(styled); final int yPixel = styled.getLinePixel(rect.top); final int hPixel = styled.getLinePixel(rect.bottom + 1) - yPixel; final int start = rect.getULOffset(textContent.getViewContent()); final Rectangle row = styled.getTextBounds(start, start + rect.width()); final int xPixel = row.x; final int wPixel = row.width; // getLinePixel is relative to the top of the viewport, // not the top of the document; however, setBlockSelectionBounds // wants pixels relative to the document. awesome final int scrollOffsetY = styled.getTopPixel() + yPixel; // getTextBounds is apparently also relative to the viewport final int scrollOffsetX = styled.getHorizontalPixel() + xPixel; styled.setBlockSelectionBounds( scrollOffsetX, scrollOffsetY, wPixel, hPixel); } else { textViewer.getTextWidget().setBlockSelection(false); textViewer.setSelectedRange(from, length); } selectionChangeListener.enable(); } }
diff --git a/src/com/cooliris/media/GridInputProcessor.java b/src/com/cooliris/media/GridInputProcessor.java index fd65f66..2f0c0b4 100644 --- a/src/com/cooliris/media/GridInputProcessor.java +++ b/src/com/cooliris/media/GridInputProcessor.java @@ -1,828 +1,837 @@ package com.cooliris.media; import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.os.SystemClock; import android.view.GestureDetector; import android.view.KeyEvent; import android.view.MotionEvent; import com.cooliris.app.App; public final class GridInputProcessor implements GestureDetector.OnGestureListener, GestureDetector.OnDoubleTapListener, ScaleGestureDetector.OnScaleGestureListener { private int mCurrentFocusSlot; private boolean mCurrentFocusIsPressed; private int mCurrentSelectedSlot; private float mPrevTiltValueLowPass; private float mPrevShakeValueHighPass; private float mShakeValue; private int mTouchPosX; private int mTouchPosY; private int mActionCode; private long mPrevTouchTime; private float mFirstTouchPosX; private float mFirstTouchPosY; private float mPrevTouchPosX; private float mPrevTouchPosY; private float mTouchVelX; private float mTouchVelY; private boolean mProcessTouch; private boolean mTouchMoved; private float mDpadIgnoreTime = 0.0f; private GridCamera mCamera; private GridLayer mLayer; private Context mContext; private Pool<Vector3f> mPool; private DisplayItem[] mDisplayItems; private boolean mPrevHitEdge; private boolean mTouchFeedbackDelivered; private GestureDetector mGestureDetector; private ScaleGestureDetector mScaleGestureDetector; private boolean mZoomGesture; private int mCurrentScaleSlot; private float mScale; public GridInputProcessor(Context context, GridCamera camera, GridLayer layer, RenderView view, Pool<Vector3f> pool, DisplayItem[] displayItems) { mPool = pool; mCamera = camera; mLayer = layer; mCurrentFocusSlot = Shared.INVALID; mCurrentSelectedSlot = Shared.INVALID; mCurrentScaleSlot = Shared.INVALID; mContext = context; mDisplayItems = displayItems; mGestureDetector = new GestureDetector(context, this); mScaleGestureDetector = new ScaleGestureDetector(context, this); mGestureDetector.setIsLongpressEnabled(true); mZoomGesture = false; mScale = 1.0f; } public int getCurrentFocusSlot() { return mCurrentFocusSlot; } public int getCurrentSelectedSlot() { return mCurrentSelectedSlot; } public int getCurrentScaledSlot() { return mCurrentScaleSlot; } public void setCurrentSelectedSlot(int slot) { mCurrentSelectedSlot = slot; GridLayer layer = mLayer; layer.setState(GridLayer.STATE_FULL_SCREEN); mCamera.mConvergenceSpeed = 2.0f; mCamera.mFriction = 0.0f; DisplayItem displayItem = layer.getDisplayItemForSlotId(slot); MediaItem item = null; if (displayItem != null) item = displayItem.mItemRef; layer.getHud().fullscreenSelectionChanged(item, mCurrentSelectedSlot + 1, layer.getCompleteRange().end + 1); } public void onSensorChanged(RenderView view, SensorEvent event, int state) { if (mZoomGesture) return; switch (event.sensor.getType()) { case Sensor.TYPE_ACCELEROMETER: case Sensor.TYPE_ORIENTATION: float[] values = event.values; float valueToUse = (mCamera.mWidth < mCamera.mHeight) ? values[0] : -values[1]; float tiltValue = 0.8f * mPrevTiltValueLowPass + 0.2f * valueToUse; if (Math.abs(tiltValue) < 0.5f) tiltValue = 0.0f; if (state == GridLayer.STATE_FULL_SCREEN) tiltValue = 0.0f; if (tiltValue != 0.0f) view.requestRender(); mCamera.mEyeOffsetX = -3.0f * tiltValue; float shakeValue = values[1] * values[1] + values[2] * values[2]; mShakeValue = shakeValue - mPrevShakeValueHighPass; mPrevShakeValueHighPass = shakeValue; if (mShakeValue < 16.0f) { mShakeValue = 0; } else { mShakeValue = mShakeValue * 4.0f; if (mShakeValue > 200) { mShakeValue = 200; } } break; } } public boolean onTouchEvent(MotionEvent event) { mTouchPosX = (int) (event.getX()); mTouchPosY = (int) (event.getY()); mActionCode = event.getAction(); long timestamp = SystemClock.elapsedRealtime(); long delta = timestamp - mPrevTouchTime; mPrevTouchTime = timestamp; float timeElapsed = (float) delta; timeElapsed = timeElapsed * 0.001f; // division by 1000 for seconds switch (mActionCode) { case MotionEvent.ACTION_UP: touchEnded(mTouchPosX, mTouchPosY, timeElapsed); break; case MotionEvent.ACTION_DOWN: mPrevTouchTime = timestamp; touchBegan(mTouchPosX, mTouchPosY); break; case MotionEvent.ACTION_MOVE: touchMoved(mTouchPosX, mTouchPosY, timeElapsed); break; } if (!mZoomGesture) mGestureDetector.onTouchEvent(event); mScaleGestureDetector.onTouchEvent(event); return true; } public boolean onKeyDown(int keyCode, KeyEvent event, int state) { GridLayer layer = mLayer; if (keyCode == KeyEvent.KEYCODE_BACK) { if (layer.getViewIntent()) return false; if (layer.getHud().getMode() == HudLayer.MODE_SELECT) { layer.deselectAll(); return true; } if (layer.inSlideShowMode()) { layer.endSlideshow(); layer.getHud().setAlpha(1.0f); return true; } float zoomValue = layer.getZoomValue(); if (zoomValue != 1.0f) { layer.setZoomValue(1.0f); layer.centerCameraForSlot(mCurrentSelectedSlot, 1.0f); return true; } layer.goBack(); if (state == GridLayer.STATE_MEDIA_SETS) return false; return true; } if (mDpadIgnoreTime < 0.1f) return true; mDpadIgnoreTime = 0.0f; IndexRange bufferedVisibleRange = layer.getBufferedVisibleRange(); int firstBufferedVisibleSlot = bufferedVisibleRange.begin; int lastBufferedVisibleSlot = bufferedVisibleRange.end; int anchorSlot = layer.getAnchorSlotIndex(GridLayer.ANCHOR_CENTER); if (state == GridLayer.STATE_FULL_SCREEN) { if (keyCode != KeyEvent.KEYCODE_VOLUME_UP && keyCode != KeyEvent.KEYCODE_VOLUME_DOWN && keyCode != KeyEvent.KEYCODE_MUTE && keyCode != KeyEvent.KEYCODE_HEADSETHOOK && keyCode != KeyEvent.KEYCODE_NOTIFICATION) { layer.endSlideshow(); } boolean needsVibrate = false; + boolean directionalKeyPressed = false; if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) { needsVibrate = !layer.changeFocusToNextSlot(1.0f); + directionalKeyPressed = true; } if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) { needsVibrate = !layer.changeFocusToPreviousSlot(1.0f); + directionalKeyPressed = true; + } + if (directionalKeyPressed) { + if (layer.getHud().getMode() == HudLayer.MODE_SELECT) { + layer.deselectAll(); + layer.enterSelectionMode(); + } } if (needsVibrate) { vibrateShort(); } if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER && !mCamera.isAnimating()) { if (layer.getZoomValue() == 1.0f) layer.zoomInToSelectedItem(); else layer.setZoomValue(1.0f); } if (keyCode == KeyEvent.KEYCODE_MENU) { if (mLayer.getFeed() != null && mLayer.getFeed().isSingleImageMode()) { return true; } if (layer.getHud().getMode() == HudLayer.MODE_NORMAL) layer.enterSelectionMode(); else layer.deselectAll(); } } else { mCurrentFocusIsPressed = false; int numRows = ((GridLayoutInterface) layer.getLayoutInterface()).mNumRows; if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER && mCurrentFocusSlot != Shared.INVALID) { if (layer.getHud().getMode() != HudLayer.MODE_SELECT) { boolean centerCamera = layer.tapGesture(mCurrentFocusSlot, false); if (centerCamera) { int slotId = mCurrentFocusSlot; selectSlot(slotId); } mCurrentFocusSlot = Shared.INVALID; return true; } else { layer.addSlotToSelectedItems(mCurrentFocusSlot, true, true); } mCurrentFocusIsPressed = true; } else if (keyCode == KeyEvent.KEYCODE_MENU && mCurrentFocusSlot != Shared.INVALID) { if (layer.getHud().getMode() == HudLayer.MODE_NORMAL) layer.enterSelectionMode(); else layer.deselectAll(); } else if (mCurrentFocusSlot == Shared.INVALID) { mCurrentFocusSlot = anchorSlot; } else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) { mCurrentFocusSlot += numRows; } else if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) { mCurrentFocusSlot -= numRows; } else if (keyCode == KeyEvent.KEYCODE_DPAD_UP) { --mCurrentFocusSlot; } else if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) { ++mCurrentFocusSlot; } if (mCurrentFocusSlot > lastBufferedVisibleSlot) { mCurrentFocusSlot = lastBufferedVisibleSlot; } if (mCurrentFocusSlot < firstBufferedVisibleSlot) mCurrentFocusSlot = firstBufferedVisibleSlot; if (mCurrentFocusSlot != Shared.INVALID) { layer.centerCameraForSlot(mCurrentFocusSlot, 1.0f); } } return false; } private void touchBegan(int posX, int posY) { mPrevTouchPosX = posX; mPrevTouchPosY = posY; mFirstTouchPosX = posX; mFirstTouchPosY = posY; mTouchVelX = 0; mTouchVelY = 0; mProcessTouch = true; mZoomGesture = false; mTouchMoved = false; mCamera.stopMovementInX(); GridLayer layer = mLayer; mCurrentFocusSlot = layer.getSlotIndexForScreenPosition(posX, posY); mCurrentFocusIsPressed = true; mTouchFeedbackDelivered = false; HudLayer hud = layer.getHud(); if (hud.getMode() == HudLayer.MODE_SELECT) hud.closeSelectionMenu(); if (layer.getState() == GridLayer.STATE_FULL_SCREEN && hud.getMode() == HudLayer.MODE_SELECT) { layer.deselectAll(); hud.setAlpha(1.0f); } int slotId = layer.getSlotIndexForScreenPosition(posX, posY); if (slotId != Shared.INVALID && layer.getState() != GridLayer.STATE_FULL_SCREEN) { vibrateShort(); } } private void touchMoved(int posX, int posY, float timeElapsedx) { if (mProcessTouch && !mZoomGesture) { GridLayer layer = mLayer; GridCamera camera = mCamera; float deltaX = -(posX - mPrevTouchPosX); // negation since the wall // moves in a direction // opposite to that of // the touch float deltaY = -(posY - mPrevTouchPosY); if (Math.abs(deltaX) >= 10.0f || Math.abs(deltaY) >= 10.0f) { mTouchMoved = true; } Pool<Vector3f> pool = mPool; Vector3f firstPosition = pool.create(); Vector3f lastPosition = pool.create(); Vector3f deltaAnchorPosition = pool.create(); Vector3f worldPosDelta = pool.create(); try { deltaAnchorPosition.set(layer.getDeltaAnchorPosition()); LayoutInterface layout = layer.getLayoutInterface(); GridCameraManager.getSlotPositionForSlotIndex(0, camera, layout, deltaAnchorPosition, firstPosition); int lastSlotIndex = 0; IndexRange completeRange = layer.getCompleteRange(); synchronized (completeRange) { lastSlotIndex = completeRange.end; } GridCameraManager.getSlotPositionForSlotIndex(lastSlotIndex, camera, layout, deltaAnchorPosition, lastPosition); camera.convertToRelativeCameraSpace(deltaX, deltaY, 0, worldPosDelta); deltaX = worldPosDelta.x; deltaY = worldPosDelta.y; camera.moveBy(deltaX, (layer.getZoomValue() == 1.0f) ? 0 : deltaY, 0); deltaX *= camera.mScale; deltaY *= camera.mScale; } finally { pool.delete(firstPosition); pool.delete(lastPosition); pool.delete(deltaAnchorPosition); pool.delete(worldPosDelta); } if (layer.getZoomValue() == 1.0f) { if (camera .computeConstraints(false, (layer.getState() != GridLayer.STATE_FULL_SCREEN), firstPosition, lastPosition)) { deltaX = 0.0f; // vibrate if (!mTouchFeedbackDelivered) { mTouchFeedbackDelivered = true; vibrateLong(); } } } mTouchVelX = deltaX * timeElapsedx; mTouchVelY = deltaY * timeElapsedx; float maxVelXx = (mCamera.mWidth * 0.5f); float maxVelYx = (mCamera.mHeight); mTouchVelX = FloatUtils.clamp(mTouchVelX, -maxVelXx, maxVelXx); mTouchVelY = FloatUtils.clamp(mTouchVelY, -maxVelYx, maxVelYx); mPrevTouchPosX = posX; mPrevTouchPosY = posY; // you want the movement to track the finger immediately if (mTouchMoved == false) mCurrentFocusSlot = layer.getSlotIndexForScreenPosition(posX, posY); else mCurrentFocusSlot = Shared.INVALID; if (!mCamera.isZAnimating()) { mCamera.commitMoveInX(); mCamera.commitMoveInY(); } int anchorSlotIndex = layer.getAnchorSlotIndex(GridLayer.ANCHOR_LEFT); DisplayItem[] displayItems = mDisplayItems; IndexRange bufferedVisibleRange = layer.getBufferedVisibleRange(); int firstBufferedVisibleSlot = bufferedVisibleRange.begin; int lastBufferedVisibleSlot = bufferedVisibleRange.end; synchronized (displayItems) { if (anchorSlotIndex >= firstBufferedVisibleSlot && anchorSlotIndex <= lastBufferedVisibleSlot) { DisplayItem item = displayItems[(anchorSlotIndex - firstBufferedVisibleSlot) * GridLayer.MAX_ITEMS_PER_SLOT]; if (item != null) { layer.getHud().setTimeBarTime(item.mItemRef.mDateTakenInMs); } } } } } private void touchEnded(int posX, int posY, float timeElapsedx) { if (mProcessTouch == false || mZoomGesture) { return; } int maxPixelsBeforeSwitch = mCamera.mWidth / 8; mCamera.mConvergenceSpeed = 2.0f; GridLayer layer = mLayer; if (layer.getExpandedSlot() == Shared.INVALID && !layer.feedAboutToChange() && !mZoomGesture) { if (mCurrentSelectedSlot != Shared.INVALID) { if (layer.getState() == GridLayer.STATE_FULL_SCREEN) { if (!mTouchMoved) { // tap gesture for fullscreen if (layer.getZoomValue() == 1.0f) layer.changeFocusToSlot(mCurrentSelectedSlot, 1.0f); } else if (layer.getZoomValue() == 1.0f) { // we want to snap to a new slotIndex based on where the // current position is if (layer.inSlideShowMode()) { layer.endSlideshow(); } float deltaX = posX - mFirstTouchPosX; float deltaY = posY - mFirstTouchPosY; if (deltaY != 0) { // it has moved vertically } layer.changeFocusToSlot(mCurrentSelectedSlot, 1.0f); HudLayer hud = layer.getHud(); if (deltaX > maxPixelsBeforeSwitch && hud.getMode() != HudLayer.MODE_SELECT) { layer.changeFocusToPreviousSlot(1.0f); } else if (deltaX < -maxPixelsBeforeSwitch && hud.getMode() != HudLayer.MODE_SELECT) { layer.changeFocusToNextSlot(1.0f); } } else { // in zoomed state // we do nothing for now, but we should clamp to the // image bounds boolean hitEdge = layer.constrainCameraForSlot(mCurrentSelectedSlot); // mPrevHitEdge = false; if (hitEdge && mPrevHitEdge) { float deltaX = posX - mFirstTouchPosX; float deltaY = posY - mFirstTouchPosY; maxPixelsBeforeSwitch *= 4; if (deltaY != 0) { // it has moved vertically } mPrevHitEdge = false; HudLayer hud = layer.getHud(); if (deltaX > maxPixelsBeforeSwitch && hud.getMode() != HudLayer.MODE_SELECT) { layer.changeFocusToPreviousSlot(1.0f); } else if (deltaX < -maxPixelsBeforeSwitch && hud.getMode() != HudLayer.MODE_SELECT) { layer.changeFocusToNextSlot(1.0f); } else { mPrevHitEdge = hitEdge; } } else { mPrevHitEdge = hitEdge; } } } } else { if (!layer.feedAboutToChange() && layer.getZoomValue() == 1.0f && mTouchMoved) { constrainCamera(true); } } } mCurrentFocusSlot = Shared.INVALID; mCurrentFocusIsPressed = false; mPrevTouchPosX = posX; mPrevTouchPosY = posY; mProcessTouch = false; } private void constrainCamera(boolean b) { Pool<Vector3f> pool = mPool; GridLayer layer = mLayer; Vector3f firstPosition = pool.create(); Vector3f lastPosition = pool.create(); Vector3f deltaAnchorPosition = pool.create(); try { deltaAnchorPosition.set(layer.getDeltaAnchorPosition()); GridCamera camera = mCamera; LayoutInterface layout = layer.getLayoutInterface(); GridCameraManager.getSlotPositionForSlotIndex(0, camera, layout, deltaAnchorPosition, firstPosition); int lastSlotIndex = 0; IndexRange completeRange = layer.getCompleteRange(); synchronized (completeRange) { lastSlotIndex = completeRange.end; } GridCameraManager.getSlotPositionForSlotIndex(lastSlotIndex, camera, layout, deltaAnchorPosition, lastPosition); camera.computeConstraints(true, (layer.getState() != GridLayer.STATE_FULL_SCREEN), firstPosition, lastPosition); } finally { pool.delete(firstPosition); pool.delete(lastPosition); pool.delete(deltaAnchorPosition); } } public void clearSelection() { mCurrentSelectedSlot = Shared.INVALID; } public void clearFocus() { mCurrentFocusSlot = Shared.INVALID; } public boolean isFocusItemPressed() { return mCurrentFocusIsPressed; } public void update(float timeElapsed) { mDpadIgnoreTime += timeElapsed; if (mCamera.mFriction != 0.0f) { constrainCamera(true); } } public void setCurrentFocusSlot(int slotId) { mCurrentSelectedSlot = slotId; } public boolean onDown(MotionEvent e) { // TODO Auto-generated method stub return true; } public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { if (mCurrentSelectedSlot == Shared.INVALID) { mCamera.moveYTo(0); mCamera.moveZTo(0); mCamera.mConvergenceSpeed = 1.0f; mCamera.mFriction = 0.0f; float normalizedVelocity = velocityX * mCamera.mOneByScale; // mCamera.moveBy(-velocityX * mCamera.mOneByScale * 0.25f, 0, 0); // constrainCamera(true); IndexRange visibleRange = mLayer.getVisibleRange(); int numVisibleSlots = visibleRange.end - visibleRange.begin; if (numVisibleSlots > 0) { float fastFlingVelocity = 10.0f; int slotsToSkip = (int) (numVisibleSlots * (-normalizedVelocity / fastFlingVelocity)); int maxSlots = numVisibleSlots; if (slotsToSkip > maxSlots) slotsToSkip = maxSlots; if (slotsToSkip < -maxSlots) slotsToSkip = -maxSlots; if (Math.abs(slotsToSkip) <= 1) { if (velocityX > 0) slotsToSkip = -2; else if (velocityX < 0) slotsToSkip = 2; } int slotToGetTo = mLayer.getAnchorSlotIndex(GridLayer.ANCHOR_CENTER) + slotsToSkip; if (slotToGetTo < 0) slotToGetTo = 0; int lastSlot = mLayer.getCompleteRange().end; if (slotToGetTo > lastSlot) slotToGetTo = lastSlot; mLayer.centerCameraForSlot(slotToGetTo, 1.0f); } constrainCamera(true); return true; } else { return false; } } public void onLongPress(MotionEvent e) { if (mZoomGesture) return; if (mLayer.getFeed() != null && mLayer.getFeed().isSingleImageMode()) { HudLayer hud = mLayer.getHud(); hud.getPathBar().setHidden(true); hud.getMenuBar().setHidden(true); if (hud.getMode() != HudLayer.MODE_NORMAL) hud.setMode(HudLayer.MODE_NORMAL); } if (mCurrentFocusSlot != Shared.INVALID) { vibrateLong(); GridLayer layer = mLayer; if (layer.getState() == GridLayer.STATE_FULL_SCREEN) { layer.deselectAll(); } HudLayer hud = layer.getHud(); hud.enterSelectionMode(); layer.addSlotToSelectedItems(mCurrentFocusSlot, true, true); } } public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { // TODO Auto-generated method stub return false; } public void onShowPress(MotionEvent e) { // TODO Auto-generated method stub } public boolean onSingleTapUp(MotionEvent e) { GridLayer layer = mLayer; int posX = (int) e.getX(); int posY = (int) e.getY(); if (mCurrentSelectedSlot != Shared.INVALID) { // Fullscreen mode. mCamera.mConvergenceSpeed = 2.0f; mCamera.mFriction = 0.0f; int slotId = mCurrentSelectedSlot; if (layer.getZoomValue() == 1.0f) { layer.centerCameraForSlot(slotId, 1.0f); } else { layer.constrainCameraForSlot(slotId); } DisplayItem displayItem = layer.getDisplayItemForSlotId(slotId); if (displayItem != null) { final MediaItem item = displayItem.mItemRef; int heightBy2 = mCamera.mHeight / 2; boolean posYInBounds = (Math.abs(posY - heightBy2) < 64); if (posX < 32 && posYInBounds) { layer.changeFocusToPreviousSlot(1.0f); } else if (posX > mCamera.mWidth - 32 && posYInBounds) { layer.changeFocusToNextSlot(1.0f); } else if (item.getMediaType() == MediaItem.MEDIA_TYPE_VIDEO) { Utils.playVideo(mContext, item); } else { // We stop any slideshow. HudLayer hud = layer.getHud(); if (layer.inSlideShowMode()) { layer.endSlideshow(); } else { hud.setAlpha(1.0f - hud.getAlpha()); } if (hud.getMode() == HudLayer.MODE_SELECT) { hud.setAlpha(1.0f); } } } } else { int slotId = layer.getSlotIndexForScreenPosition(posX, posY); if (slotId != Shared.INVALID) { HudLayer hud = layer.getHud(); if (hud.getMode() == HudLayer.MODE_SELECT) { layer.addSlotToSelectedItems(slotId, true, true); } else { boolean centerCamera = (mCurrentSelectedSlot == Shared.INVALID) ? layer.tapGesture(slotId, false) : true; if (centerCamera) { // We check if this item is a video or not. selectSlot(slotId); } } } else { int state = layer.getState(); if (state != GridLayer.STATE_FULL_SCREEN && state != GridLayer.STATE_GRID_VIEW && layer.getHud().getMode() != HudLayer.MODE_SELECT) { slotId = layer.getMetadataSlotIndexForScreenPosition(posX, posY); if (slotId != Shared.INVALID) { layer.tapGesture(slotId, true); } } } } return true; } private void selectSlot(int slotId) { GridLayer layer = mLayer; if (layer.getState() == GridLayer.STATE_GRID_VIEW) { DisplayItem displayItem = layer.getDisplayItemForSlotId(slotId); if (displayItem != null) { final MediaItem item = displayItem.mItemRef; if (layer.getPickIntent()) { // we need to return this item App.get(mContext).getHandler().post(new Runnable() { public void run() { CropImage.launchCropperOrFinish(mContext, item); } }); return; } if (item.getMediaType() == MediaItem.MEDIA_TYPE_VIDEO) { Utils.playVideo(mContext, item); } else { mCurrentSelectedSlot = slotId; layer.endSlideshow(); layer.setState(GridLayer.STATE_FULL_SCREEN); mCamera.mConvergenceSpeed = 2.0f; mCamera.mFriction = 0.0f; layer.getHud().fullscreenSelectionChanged(item, mCurrentSelectedSlot + 1, layer.getCompleteRange().end + 1); } } } constrainCamera(true); } public boolean onDoubleTap(MotionEvent e) { final GridLayer layer = mLayer; if (layer.getState() == GridLayer.STATE_FULL_SCREEN && !mCamera.isZAnimating()) { float posX = e.getX(); float posY = e.getY(); final Vector3f retVal = new Vector3f(); posX -= (mCamera.mWidth / 2); posY -= (mCamera.mHeight / 2); mCamera.convertToRelativeCameraSpace(posX, posY, 0, retVal); if (layer.getZoomValue() == 1.0f) { layer.setZoomValue(3f); mCamera.update(0.001f); mCamera.moveBy(retVal.x, retVal.y, 0); layer.constrainCameraForSlot(mCurrentSelectedSlot); } else { layer.setZoomValue(1.0f); } mCamera.mConvergenceSpeed = 2.0f; mCamera.mFriction = 0.0f; } else { return onSingleTapConfirmed(e); } return true; } public boolean onDoubleTapEvent(MotionEvent e) { return false; } public boolean onSingleTapConfirmed(MotionEvent e) { return false; } public boolean touchPressed() { return mProcessTouch; } private void vibrateShort() { // As per request by Google, this line disables vibration. // mView.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); } private void vibrateLong() { // mView.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY); } public boolean onScale(ScaleGestureDetector detector) { final GridLayer layer = mLayer; float scale = detector.getScaleFactor(); if (Float.isInfinite(scale) || Float.isNaN(scale)) return true; mScale = scale * mScale; boolean performTranslation = Math.abs(scale - 1.0f) < 0.001f ? false : true; if (layer.getState() == GridLayer.STATE_FULL_SCREEN) { float currentScale = layer.getZoomValue(); if (currentScale <= 1.0f) performTranslation = false; final Vector3f retVal = new Vector3f(); if (performTranslation) { float posX = detector.getFocusX(); float posY = detector.getFocusY(); posX -= (mCamera.mWidth / 2); posY -= (mCamera.mHeight / 2); mCamera.convertToRelativeCameraSpace(posX, posY, 0, retVal); } if (currentScale < 0.7f && scale < 1.0f) { scale = 1.0f; } if (currentScale > 8.0f && scale > 1.0f) { scale = 1.0f; } layer.setZoomValue(currentScale * scale); if (performTranslation) { mCamera.update(0.001f); mCamera.moveBy(retVal.x, retVal.y, 0); layer.constrainCameraForSlot(mCurrentSelectedSlot); } } if (mLayer.getState() == GridLayer.STATE_GRID_VIEW) { mCurrentScaleSlot = Shared.INVALID; mCurrentFocusSlot = Shared.INVALID; } return true; } public boolean onScaleBegin(ScaleGestureDetector detector) { mZoomGesture = true; mScale = 1.0f; mLayer.getHud().hideZoomButtons(true); int posX = (int) detector.getFocusX(); int posY = (int) detector.getFocusY(); int slotId = mLayer.getSlotIndexForScreenPosition(posX, posY); if (slotId == Shared.INVALID) { slotId = mLayer.getAnchorSlotIndex(GridLayer.ANCHOR_CENTER); } if (slotId != Shared.INVALID) { mCurrentScaleSlot = slotId; mCurrentFocusSlot = slotId; } if (mLayer.getState() == GridLayer.STATE_GRID_VIEW) { mCurrentScaleSlot = Shared.INVALID; mCurrentFocusSlot = Shared.INVALID; } constrainCamera(true); return true; } public void onScaleEnd(ScaleGestureDetector detector, boolean cancel) { if (!cancel) { final GridLayer layer = mLayer; if (layer.getState() == GridLayer.STATE_FULL_SCREEN) { float currentScale = layer.getZoomValue(); if (currentScale < 1.0f) { currentScale = 1.0f; } else if (currentScale > 6.0f) { currentScale = 6.0f; } if (currentScale != layer.getZoomValue()) { layer.setZoomValue(currentScale); } layer.constrainCameraForSlot(mCurrentSelectedSlot); mLayer.getHud().hideZoomButtons(false); if (mScale < 0.7f && false) { layer.goBack(); } } else { if (mScale > 3.0f && false) { HudLayer hud = layer.getHud(); if (hud.getMode() == HudLayer.MODE_SELECT) { layer.addSlotToSelectedItems(mCurrentScaleSlot, true, true); } else { boolean centerCamera = (mCurrentSelectedSlot == Shared.INVALID) ? layer .tapGesture(mCurrentScaleSlot, false) : true; if (centerCamera) { // We check if this item is a video or not. selectSlot(mCurrentScaleSlot); } } } else { if (layer.getState() == GridLayer.STATE_GRID_VIEW) { if (mScale < 0.7f && false) { layer.goBack(); } } } } } else { // The gesture was cancelled. final GridLayer layer = mLayer; if (layer.getState() == GridLayer.STATE_FULL_SCREEN) { layer.setZoomValue(1.0f); mLayer.getHud().hideZoomButtons(false); } } resetScale(); } public float getScale() { return mScale; } public void resetScale() { mScale = 1.0f; mCurrentScaleSlot = Shared.INVALID; } public ScaleGestureDetector getScaleGestureDetector() { return mScaleGestureDetector; } }
false
true
public boolean onKeyDown(int keyCode, KeyEvent event, int state) { GridLayer layer = mLayer; if (keyCode == KeyEvent.KEYCODE_BACK) { if (layer.getViewIntent()) return false; if (layer.getHud().getMode() == HudLayer.MODE_SELECT) { layer.deselectAll(); return true; } if (layer.inSlideShowMode()) { layer.endSlideshow(); layer.getHud().setAlpha(1.0f); return true; } float zoomValue = layer.getZoomValue(); if (zoomValue != 1.0f) { layer.setZoomValue(1.0f); layer.centerCameraForSlot(mCurrentSelectedSlot, 1.0f); return true; } layer.goBack(); if (state == GridLayer.STATE_MEDIA_SETS) return false; return true; } if (mDpadIgnoreTime < 0.1f) return true; mDpadIgnoreTime = 0.0f; IndexRange bufferedVisibleRange = layer.getBufferedVisibleRange(); int firstBufferedVisibleSlot = bufferedVisibleRange.begin; int lastBufferedVisibleSlot = bufferedVisibleRange.end; int anchorSlot = layer.getAnchorSlotIndex(GridLayer.ANCHOR_CENTER); if (state == GridLayer.STATE_FULL_SCREEN) { if (keyCode != KeyEvent.KEYCODE_VOLUME_UP && keyCode != KeyEvent.KEYCODE_VOLUME_DOWN && keyCode != KeyEvent.KEYCODE_MUTE && keyCode != KeyEvent.KEYCODE_HEADSETHOOK && keyCode != KeyEvent.KEYCODE_NOTIFICATION) { layer.endSlideshow(); } boolean needsVibrate = false; if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) { needsVibrate = !layer.changeFocusToNextSlot(1.0f); } if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) { needsVibrate = !layer.changeFocusToPreviousSlot(1.0f); } if (needsVibrate) { vibrateShort(); } if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER && !mCamera.isAnimating()) { if (layer.getZoomValue() == 1.0f) layer.zoomInToSelectedItem(); else layer.setZoomValue(1.0f); } if (keyCode == KeyEvent.KEYCODE_MENU) { if (mLayer.getFeed() != null && mLayer.getFeed().isSingleImageMode()) { return true; } if (layer.getHud().getMode() == HudLayer.MODE_NORMAL) layer.enterSelectionMode(); else layer.deselectAll(); } } else { mCurrentFocusIsPressed = false; int numRows = ((GridLayoutInterface) layer.getLayoutInterface()).mNumRows; if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER && mCurrentFocusSlot != Shared.INVALID) { if (layer.getHud().getMode() != HudLayer.MODE_SELECT) { boolean centerCamera = layer.tapGesture(mCurrentFocusSlot, false); if (centerCamera) { int slotId = mCurrentFocusSlot; selectSlot(slotId); } mCurrentFocusSlot = Shared.INVALID; return true; } else { layer.addSlotToSelectedItems(mCurrentFocusSlot, true, true); } mCurrentFocusIsPressed = true; } else if (keyCode == KeyEvent.KEYCODE_MENU && mCurrentFocusSlot != Shared.INVALID) { if (layer.getHud().getMode() == HudLayer.MODE_NORMAL) layer.enterSelectionMode(); else layer.deselectAll(); } else if (mCurrentFocusSlot == Shared.INVALID) { mCurrentFocusSlot = anchorSlot; } else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) { mCurrentFocusSlot += numRows; } else if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) { mCurrentFocusSlot -= numRows; } else if (keyCode == KeyEvent.KEYCODE_DPAD_UP) { --mCurrentFocusSlot; } else if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) { ++mCurrentFocusSlot; } if (mCurrentFocusSlot > lastBufferedVisibleSlot) { mCurrentFocusSlot = lastBufferedVisibleSlot; } if (mCurrentFocusSlot < firstBufferedVisibleSlot) mCurrentFocusSlot = firstBufferedVisibleSlot; if (mCurrentFocusSlot != Shared.INVALID) { layer.centerCameraForSlot(mCurrentFocusSlot, 1.0f); } } return false; }
public boolean onKeyDown(int keyCode, KeyEvent event, int state) { GridLayer layer = mLayer; if (keyCode == KeyEvent.KEYCODE_BACK) { if (layer.getViewIntent()) return false; if (layer.getHud().getMode() == HudLayer.MODE_SELECT) { layer.deselectAll(); return true; } if (layer.inSlideShowMode()) { layer.endSlideshow(); layer.getHud().setAlpha(1.0f); return true; } float zoomValue = layer.getZoomValue(); if (zoomValue != 1.0f) { layer.setZoomValue(1.0f); layer.centerCameraForSlot(mCurrentSelectedSlot, 1.0f); return true; } layer.goBack(); if (state == GridLayer.STATE_MEDIA_SETS) return false; return true; } if (mDpadIgnoreTime < 0.1f) return true; mDpadIgnoreTime = 0.0f; IndexRange bufferedVisibleRange = layer.getBufferedVisibleRange(); int firstBufferedVisibleSlot = bufferedVisibleRange.begin; int lastBufferedVisibleSlot = bufferedVisibleRange.end; int anchorSlot = layer.getAnchorSlotIndex(GridLayer.ANCHOR_CENTER); if (state == GridLayer.STATE_FULL_SCREEN) { if (keyCode != KeyEvent.KEYCODE_VOLUME_UP && keyCode != KeyEvent.KEYCODE_VOLUME_DOWN && keyCode != KeyEvent.KEYCODE_MUTE && keyCode != KeyEvent.KEYCODE_HEADSETHOOK && keyCode != KeyEvent.KEYCODE_NOTIFICATION) { layer.endSlideshow(); } boolean needsVibrate = false; boolean directionalKeyPressed = false; if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) { needsVibrate = !layer.changeFocusToNextSlot(1.0f); directionalKeyPressed = true; } if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) { needsVibrate = !layer.changeFocusToPreviousSlot(1.0f); directionalKeyPressed = true; } if (directionalKeyPressed) { if (layer.getHud().getMode() == HudLayer.MODE_SELECT) { layer.deselectAll(); layer.enterSelectionMode(); } } if (needsVibrate) { vibrateShort(); } if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER && !mCamera.isAnimating()) { if (layer.getZoomValue() == 1.0f) layer.zoomInToSelectedItem(); else layer.setZoomValue(1.0f); } if (keyCode == KeyEvent.KEYCODE_MENU) { if (mLayer.getFeed() != null && mLayer.getFeed().isSingleImageMode()) { return true; } if (layer.getHud().getMode() == HudLayer.MODE_NORMAL) layer.enterSelectionMode(); else layer.deselectAll(); } } else { mCurrentFocusIsPressed = false; int numRows = ((GridLayoutInterface) layer.getLayoutInterface()).mNumRows; if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER && mCurrentFocusSlot != Shared.INVALID) { if (layer.getHud().getMode() != HudLayer.MODE_SELECT) { boolean centerCamera = layer.tapGesture(mCurrentFocusSlot, false); if (centerCamera) { int slotId = mCurrentFocusSlot; selectSlot(slotId); } mCurrentFocusSlot = Shared.INVALID; return true; } else { layer.addSlotToSelectedItems(mCurrentFocusSlot, true, true); } mCurrentFocusIsPressed = true; } else if (keyCode == KeyEvent.KEYCODE_MENU && mCurrentFocusSlot != Shared.INVALID) { if (layer.getHud().getMode() == HudLayer.MODE_NORMAL) layer.enterSelectionMode(); else layer.deselectAll(); } else if (mCurrentFocusSlot == Shared.INVALID) { mCurrentFocusSlot = anchorSlot; } else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) { mCurrentFocusSlot += numRows; } else if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) { mCurrentFocusSlot -= numRows; } else if (keyCode == KeyEvent.KEYCODE_DPAD_UP) { --mCurrentFocusSlot; } else if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) { ++mCurrentFocusSlot; } if (mCurrentFocusSlot > lastBufferedVisibleSlot) { mCurrentFocusSlot = lastBufferedVisibleSlot; } if (mCurrentFocusSlot < firstBufferedVisibleSlot) mCurrentFocusSlot = firstBufferedVisibleSlot; if (mCurrentFocusSlot != Shared.INVALID) { layer.centerCameraForSlot(mCurrentFocusSlot, 1.0f); } } return false; }
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/wizards/NewAttachmentWizard.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/wizards/NewAttachmentWizard.java index d108bb05f..26be4eff7 100644 --- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/wizards/NewAttachmentWizard.java +++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/wizards/NewAttachmentWizard.java @@ -1,256 +1,256 @@ /******************************************************************************* * Copyright (c) 2004 - 2006 University Of British Columbia and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * University Of British Columbia - initial API and implementation *******************************************************************************/ package org.eclipse.mylar.internal.tasks.ui.wizards; import java.io.File; import java.io.FileWriter; import java.io.IOException; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.IJobChangeEvent; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.core.runtime.jobs.JobChangeAdapter; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.wizard.IWizardPage; import org.eclipse.jface.wizard.Wizard; import org.eclipse.mylar.context.core.ContextCorePlugin; import org.eclipse.mylar.internal.tasks.ui.ITasksUiConstants; import org.eclipse.mylar.internal.tasks.ui.TaskListImages; import org.eclipse.mylar.internal.tasks.ui.util.WebBrowserDialog; import org.eclipse.mylar.tasks.core.AbstractRepositoryConnector; import org.eclipse.mylar.tasks.core.AbstractRepositoryTask; import org.eclipse.mylar.tasks.core.IAttachmentHandler; import org.eclipse.mylar.tasks.core.LocalAttachment; import org.eclipse.mylar.tasks.core.TaskRepository; import org.eclipse.mylar.tasks.core.AbstractRepositoryTask.RepositoryTaskSyncState; import org.eclipse.mylar.tasks.ui.TasksUiPlugin; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.PlatformUI; /** * A wizard to add a new attachment to a task report. * * @author Jeff Pound */ public class NewAttachmentWizard extends Wizard { private static final String DIALOG_SETTINGS_KEY = "AttachmentWizard"; private LocalAttachment attachment; private InputAttachmentSourcePage inputPage; private NewAttachmentPage attachPage; private NewAttachmentWizardDialog dialog; private boolean hasNewDialogSettings; private TaskRepository repository; private AbstractRepositoryTask task; public NewAttachmentWizard(TaskRepository repository, AbstractRepositoryTask task) { super(); this.task = task; this.repository = repository; setNeedsProgressMonitor(true); setWindowTitle("Add Attachment"); setDefaultPageImageDescriptor(TaskListImages.BANNER_REPOSITORY); attachment = new LocalAttachment(); attachment.setFilePath(""); inputPage = new InputAttachmentSourcePage(this); IDialogSettings workbenchSettings = TasksUiPlugin.getDefault().getDialogSettings(); IDialogSettings section = workbenchSettings.getSection(DIALOG_SETTINGS_KEY); if (section == null) { hasNewDialogSettings = true; } else { hasNewDialogSettings = false; setDialogSettings(section); } } public NewAttachmentWizard(TaskRepository repository, AbstractRepositoryTask task, File attachFile) { this(repository, task); attachment.setFilePath(attachFile.getAbsolutePath()); } public NewAttachmentWizard(TaskRepository repository, AbstractRepositoryTask task, String attachContents) { this(repository, task); inputPage.setUseClipboard(true); inputPage.setClipboardContents(attachContents); attachment.setFilePath(InputAttachmentSourcePage.CLIPBOARD_LABEL); } @Override public boolean performFinish() { /* TODO jpound - support non-text in clipboard */ attachPage.populateAttachment(); String path = inputPage.getAbsoluteAttachmentPath(); if (InputAttachmentSourcePage.CLIPBOARD_LABEL.equals(path)) { // write temporary file String contents = inputPage.getClipboardContents(); if (contents == null) { // TODO Handle error } - File file = new File(TasksUiPlugin.getDefault().getDefaultDataDirectory() + File file = new File(TasksUiPlugin.getDefault().getDataDirectory() + System.getProperty("file.separator").charAt(0) + "Clipboard-attachment"); try { FileWriter writer = new FileWriter(file); writer.write(contents); writer.flush(); writer.close(); } catch (IOException e) { // TODO Handle error } path = file.getAbsolutePath(); attachment.setDeleteAfterUpload(true); } attachment.setFilePath(path); // Save the dialog settings if (hasNewDialogSettings) { IDialogSettings workbenchSettings = TasksUiPlugin.getDefault().getDialogSettings(); IDialogSettings section = workbenchSettings.getSection(DIALOG_SETTINGS_KEY); section = workbenchSettings.addNewSection(DIALOG_SETTINGS_KEY); setDialogSettings(section); } // upload the attachment AbstractRepositoryConnector connector = TasksUiPlugin.getRepositoryManager().getRepositoryConnector( repository.getKind()); final IAttachmentHandler attachmentHandler = connector.getAttachmentHandler(); if (attachmentHandler == null) { return false; } final boolean attachContext = attachPage.getAttachContext(); Job submitJob = new Job("Submitting attachment") { @Override protected IStatus run(IProgressMonitor monitor) { AbstractRepositoryConnector connector = TasksUiPlugin.getRepositoryManager() .getRepositoryConnector(repository.getKind()); try { attachmentHandler.uploadAttachment(repository, task, attachment.getComment(), attachment .getDescription(), new File(attachment.getFilePath()), attachment.getContentType(), attachment.isPatch()); if (attachment.getDeleteAfterUpload()) { File file = new File(attachment.getFilePath()); if (!file.delete()) { // TODO: Handle bad clean up } } if (attachContext) { connector.attachContext(repository, task, ""); // attachContext sets outgoing state but we want to recieve incoming // on synchronization. This could result in lost edits so need to // review the whole attachment interaction. task.setSyncState(RepositoryTaskSyncState.SYNCHRONIZED); } } catch (final CoreException e) { if (e.getStatus().getCode() == Status.INFO) { PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { WebBrowserDialog.openAcceptAgreement(null, "Upload Error", e.getStatus().getMessage(), e.getStatus().getException().getMessage()); } }); } else if (e.getStatus().getCode() == Status.ERROR) { PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { MessageDialog.openError(null, "Upload Error", e.getStatus().getMessage()); } }); } } TasksUiPlugin.getSynchronizationManager().synchronize(connector, task, false, new JobChangeAdapter() { @Override public void done(final IJobChangeEvent event) { if (event.getResult().getException() != null) { PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { MessageDialog.openError(Display.getDefault().getActiveShell(), ITasksUiConstants.TITLE_DIALOG, event.getResult().getMessage()); } }); } } }); return Status.OK_STATUS; } }; submitJob.schedule(); return true; } protected boolean hasContext() { return ContextCorePlugin.getContextManager().hasContext(task.getHandleIdentifier()); } @Override public boolean canFinish() { return attachPage.isPageComplete(); } @Override public void addPages() { super.addPages(); if ("".equals(attachment.getFilePath())) { addPage(inputPage); } addPage((attachPage = new NewAttachmentPage(attachment))); } public LocalAttachment getAttachment() { return attachment; } protected String getFilePath() { return inputPage.getAttachmentName(); } @Override public IWizardPage getNextPage(IWizardPage page) { if (page == inputPage) { attachPage.setFilePath(inputPage.getAttachmentName()); } return super.getNextPage(page); } public void showPage(IWizardPage page) { dialog.showPage(page); } public void setDialog(NewAttachmentWizardDialog dialog) { this.dialog = dialog; } public String getClipboardContents() { return inputPage.getClipboardContents(); } @Override public boolean needsPreviousAndNextButtons() { return true; } }
true
true
public boolean performFinish() { /* TODO jpound - support non-text in clipboard */ attachPage.populateAttachment(); String path = inputPage.getAbsoluteAttachmentPath(); if (InputAttachmentSourcePage.CLIPBOARD_LABEL.equals(path)) { // write temporary file String contents = inputPage.getClipboardContents(); if (contents == null) { // TODO Handle error } File file = new File(TasksUiPlugin.getDefault().getDefaultDataDirectory() + System.getProperty("file.separator").charAt(0) + "Clipboard-attachment"); try { FileWriter writer = new FileWriter(file); writer.write(contents); writer.flush(); writer.close(); } catch (IOException e) { // TODO Handle error } path = file.getAbsolutePath(); attachment.setDeleteAfterUpload(true); } attachment.setFilePath(path); // Save the dialog settings if (hasNewDialogSettings) { IDialogSettings workbenchSettings = TasksUiPlugin.getDefault().getDialogSettings(); IDialogSettings section = workbenchSettings.getSection(DIALOG_SETTINGS_KEY); section = workbenchSettings.addNewSection(DIALOG_SETTINGS_KEY); setDialogSettings(section); } // upload the attachment AbstractRepositoryConnector connector = TasksUiPlugin.getRepositoryManager().getRepositoryConnector( repository.getKind()); final IAttachmentHandler attachmentHandler = connector.getAttachmentHandler(); if (attachmentHandler == null) { return false; } final boolean attachContext = attachPage.getAttachContext(); Job submitJob = new Job("Submitting attachment") { @Override protected IStatus run(IProgressMonitor monitor) { AbstractRepositoryConnector connector = TasksUiPlugin.getRepositoryManager() .getRepositoryConnector(repository.getKind()); try { attachmentHandler.uploadAttachment(repository, task, attachment.getComment(), attachment .getDescription(), new File(attachment.getFilePath()), attachment.getContentType(), attachment.isPatch()); if (attachment.getDeleteAfterUpload()) { File file = new File(attachment.getFilePath()); if (!file.delete()) { // TODO: Handle bad clean up } } if (attachContext) { connector.attachContext(repository, task, ""); // attachContext sets outgoing state but we want to recieve incoming // on synchronization. This could result in lost edits so need to // review the whole attachment interaction. task.setSyncState(RepositoryTaskSyncState.SYNCHRONIZED); } } catch (final CoreException e) { if (e.getStatus().getCode() == Status.INFO) { PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { WebBrowserDialog.openAcceptAgreement(null, "Upload Error", e.getStatus().getMessage(), e.getStatus().getException().getMessage()); } }); } else if (e.getStatus().getCode() == Status.ERROR) { PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { MessageDialog.openError(null, "Upload Error", e.getStatus().getMessage()); } }); } } TasksUiPlugin.getSynchronizationManager().synchronize(connector, task, false, new JobChangeAdapter() { @Override public void done(final IJobChangeEvent event) { if (event.getResult().getException() != null) { PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { MessageDialog.openError(Display.getDefault().getActiveShell(), ITasksUiConstants.TITLE_DIALOG, event.getResult().getMessage()); } }); } } }); return Status.OK_STATUS; } }; submitJob.schedule(); return true; }
public boolean performFinish() { /* TODO jpound - support non-text in clipboard */ attachPage.populateAttachment(); String path = inputPage.getAbsoluteAttachmentPath(); if (InputAttachmentSourcePage.CLIPBOARD_LABEL.equals(path)) { // write temporary file String contents = inputPage.getClipboardContents(); if (contents == null) { // TODO Handle error } File file = new File(TasksUiPlugin.getDefault().getDataDirectory() + System.getProperty("file.separator").charAt(0) + "Clipboard-attachment"); try { FileWriter writer = new FileWriter(file); writer.write(contents); writer.flush(); writer.close(); } catch (IOException e) { // TODO Handle error } path = file.getAbsolutePath(); attachment.setDeleteAfterUpload(true); } attachment.setFilePath(path); // Save the dialog settings if (hasNewDialogSettings) { IDialogSettings workbenchSettings = TasksUiPlugin.getDefault().getDialogSettings(); IDialogSettings section = workbenchSettings.getSection(DIALOG_SETTINGS_KEY); section = workbenchSettings.addNewSection(DIALOG_SETTINGS_KEY); setDialogSettings(section); } // upload the attachment AbstractRepositoryConnector connector = TasksUiPlugin.getRepositoryManager().getRepositoryConnector( repository.getKind()); final IAttachmentHandler attachmentHandler = connector.getAttachmentHandler(); if (attachmentHandler == null) { return false; } final boolean attachContext = attachPage.getAttachContext(); Job submitJob = new Job("Submitting attachment") { @Override protected IStatus run(IProgressMonitor monitor) { AbstractRepositoryConnector connector = TasksUiPlugin.getRepositoryManager() .getRepositoryConnector(repository.getKind()); try { attachmentHandler.uploadAttachment(repository, task, attachment.getComment(), attachment .getDescription(), new File(attachment.getFilePath()), attachment.getContentType(), attachment.isPatch()); if (attachment.getDeleteAfterUpload()) { File file = new File(attachment.getFilePath()); if (!file.delete()) { // TODO: Handle bad clean up } } if (attachContext) { connector.attachContext(repository, task, ""); // attachContext sets outgoing state but we want to recieve incoming // on synchronization. This could result in lost edits so need to // review the whole attachment interaction. task.setSyncState(RepositoryTaskSyncState.SYNCHRONIZED); } } catch (final CoreException e) { if (e.getStatus().getCode() == Status.INFO) { PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { WebBrowserDialog.openAcceptAgreement(null, "Upload Error", e.getStatus().getMessage(), e.getStatus().getException().getMessage()); } }); } else if (e.getStatus().getCode() == Status.ERROR) { PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { MessageDialog.openError(null, "Upload Error", e.getStatus().getMessage()); } }); } } TasksUiPlugin.getSynchronizationManager().synchronize(connector, task, false, new JobChangeAdapter() { @Override public void done(final IJobChangeEvent event) { if (event.getResult().getException() != null) { PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { MessageDialog.openError(Display.getDefault().getActiveShell(), ITasksUiConstants.TITLE_DIALOG, event.getResult().getMessage()); } }); } } }); return Status.OK_STATUS; } }; submitJob.schedule(); return true; }
diff --git a/src/com/android/launcher2/FirstFrameAnimatorHelper.java b/src/com/android/launcher2/FirstFrameAnimatorHelper.java index f42a741c..2351dd07 100644 --- a/src/com/android/launcher2/FirstFrameAnimatorHelper.java +++ b/src/com/android/launcher2/FirstFrameAnimatorHelper.java @@ -1,105 +1,109 @@ /* * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.launcher2; import android.animation.ValueAnimator; import android.animation.Animator.AnimatorListener; import android.util.Log; import android.view.ViewTreeObserver; import android.view.View; /* * This is a helper class that listens to updates from the corresponding animation. * For the first two frames, it adjusts the current play time of the animation to * prevent jank at the beginning of the animation */ public class FirstFrameAnimatorHelper implements ValueAnimator.AnimatorUpdateListener { private static final boolean DEBUG = false; private static final int MAX_FIRST_FRAME_DELAY = 200; private static final int IDEAL_FRAME_DURATION = 16; private View mTarget; private long mStartFrame; private long mStartTime = -1; private boolean mHandlingOnAnimationUpdate; private boolean mAdjustedSecondFrameTime; private static ViewTreeObserver.OnDrawListener sGlobalDrawListener; private static long sGlobalFrameCounter; public FirstFrameAnimatorHelper(ValueAnimator animator, View target) { mTarget = target; animator.addUpdateListener(this); } public static void initializeDrawListener(View view) { sGlobalDrawListener = new ViewTreeObserver.OnDrawListener() { private long mTime = System.currentTimeMillis(); public void onDraw() { sGlobalFrameCounter++; long newTime = System.currentTimeMillis(); if (DEBUG) { Log.d("FirstFrameAnimatorHelper", "TICK " + (newTime - mTime)); } mTime = newTime; } }; view.getViewTreeObserver().addOnDrawListener(sGlobalDrawListener); } - public void onAnimationUpdate(ValueAnimator animation) { + public void onAnimationUpdate(final ValueAnimator animation) { if (mStartTime == -1) { mStartFrame = sGlobalFrameCounter; mStartTime = System.currentTimeMillis(); } if (!mHandlingOnAnimationUpdate) { mHandlingOnAnimationUpdate = true; long frameNum = sGlobalFrameCounter - mStartFrame; // If we haven't drawn our first frame, reset the time to t = 0 // (give up after 200ms of waiting though - might happen, for example, if we are no // longer in the foreground and no frames are being rendered ever) if (frameNum == 0 && System.currentTimeMillis() < mStartTime + MAX_FIRST_FRAME_DELAY) { mTarget.getRootView().invalidate(); // make sure we'll do a draw animation.setCurrentPlayTime(0); // For the second frame, if the first frame took more than 16ms, // adjust the start time and pretend it took only 16ms anyway. This // prevents a large jump in the animation due to an expensive first frame } else if (frameNum == 1 && !mAdjustedSecondFrameTime && System.currentTimeMillis() > mStartTime + 16) { animation.setCurrentPlayTime(IDEAL_FRAME_DURATION); mAdjustedSecondFrameTime = true; } else { if (frameNum > 1) { - animation.removeUpdateListener(this); + mTarget.post(new Runnable() { + public void run() { + animation.removeUpdateListener(FirstFrameAnimatorHelper.this); + } + }); } if (DEBUG) print(animation); } mHandlingOnAnimationUpdate = false; } else { if (DEBUG) print(animation); } } public void print(ValueAnimator animation) { float flatFraction = animation.getCurrentPlayTime() / (float) animation.getDuration(); Log.d("FirstFrameAnimatorHelper", sGlobalFrameCounter + "(" + (sGlobalFrameCounter - mStartFrame) + ") " + mTarget + " dirty? " + mTarget.isDirty() + " " + flatFraction + " " + this + " " + animation); } }
false
true
public void onAnimationUpdate(ValueAnimator animation) { if (mStartTime == -1) { mStartFrame = sGlobalFrameCounter; mStartTime = System.currentTimeMillis(); } if (!mHandlingOnAnimationUpdate) { mHandlingOnAnimationUpdate = true; long frameNum = sGlobalFrameCounter - mStartFrame; // If we haven't drawn our first frame, reset the time to t = 0 // (give up after 200ms of waiting though - might happen, for example, if we are no // longer in the foreground and no frames are being rendered ever) if (frameNum == 0 && System.currentTimeMillis() < mStartTime + MAX_FIRST_FRAME_DELAY) { mTarget.getRootView().invalidate(); // make sure we'll do a draw animation.setCurrentPlayTime(0); // For the second frame, if the first frame took more than 16ms, // adjust the start time and pretend it took only 16ms anyway. This // prevents a large jump in the animation due to an expensive first frame } else if (frameNum == 1 && !mAdjustedSecondFrameTime && System.currentTimeMillis() > mStartTime + 16) { animation.setCurrentPlayTime(IDEAL_FRAME_DURATION); mAdjustedSecondFrameTime = true; } else { if (frameNum > 1) { animation.removeUpdateListener(this); } if (DEBUG) print(animation); } mHandlingOnAnimationUpdate = false; } else { if (DEBUG) print(animation); } }
public void onAnimationUpdate(final ValueAnimator animation) { if (mStartTime == -1) { mStartFrame = sGlobalFrameCounter; mStartTime = System.currentTimeMillis(); } if (!mHandlingOnAnimationUpdate) { mHandlingOnAnimationUpdate = true; long frameNum = sGlobalFrameCounter - mStartFrame; // If we haven't drawn our first frame, reset the time to t = 0 // (give up after 200ms of waiting though - might happen, for example, if we are no // longer in the foreground and no frames are being rendered ever) if (frameNum == 0 && System.currentTimeMillis() < mStartTime + MAX_FIRST_FRAME_DELAY) { mTarget.getRootView().invalidate(); // make sure we'll do a draw animation.setCurrentPlayTime(0); // For the second frame, if the first frame took more than 16ms, // adjust the start time and pretend it took only 16ms anyway. This // prevents a large jump in the animation due to an expensive first frame } else if (frameNum == 1 && !mAdjustedSecondFrameTime && System.currentTimeMillis() > mStartTime + 16) { animation.setCurrentPlayTime(IDEAL_FRAME_DURATION); mAdjustedSecondFrameTime = true; } else { if (frameNum > 1) { mTarget.post(new Runnable() { public void run() { animation.removeUpdateListener(FirstFrameAnimatorHelper.this); } }); } if (DEBUG) print(animation); } mHandlingOnAnimationUpdate = false; } else { if (DEBUG) print(animation); } }
diff --git a/jetty-continuation/src/main/java/org/eclipse/jetty/continuation/Servlet3Continuation.java b/jetty-continuation/src/main/java/org/eclipse/jetty/continuation/Servlet3Continuation.java index 3d15be2d0..e4bca0be2 100644 --- a/jetty-continuation/src/main/java/org/eclipse/jetty/continuation/Servlet3Continuation.java +++ b/jetty-continuation/src/main/java/org/eclipse/jetty/continuation/Servlet3Continuation.java @@ -1,239 +1,239 @@ package org.eclipse.jetty.continuation; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.AsyncContext; import javax.servlet.AsyncEvent; import javax.servlet.AsyncListener; import javax.servlet.DispatcherType; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.ServletResponseWrapper; /* ------------------------------------------------------------ */ /** * This implementation of Continuation is used by {@link ContinuationSupport} * when it detects that the application has been deployed in a non-jetty Servlet 3 * server. */ public class Servlet3Continuation implements Continuation { // Exception reused for all continuations // Turn on debug in ContinuationFilter to see real stack trace. private final static ContinuationThrowable __exception = new ContinuationThrowable(); private final ServletRequest _request; private ServletResponse _response; private AsyncContext _context; private List<AsyncListener> _listeners=new ArrayList<AsyncListener>(); private volatile boolean _initial=true; private volatile boolean _resumed=false; private volatile boolean _expired=false; private volatile boolean _responseWrapped=false; private long _timeoutMs=-1; /* ------------------------------------------------------------ */ public Servlet3Continuation(ServletRequest request) { _request=request; _listeners.add(new AsyncListener() { public void onComplete(AsyncEvent event) throws IOException { } public void onError(AsyncEvent event) throws IOException { } public void onStartAsync(AsyncEvent event) throws IOException { event.getAsyncContext().addListener(this); } public void onTimeout(AsyncEvent event) throws IOException { _initial=false; event.getAsyncContext().dispatch(); } }); } /* ------------------------------------------------------------ */ public void addContinuationListener(final ContinuationListener listener) { AsyncListener wrapped = new AsyncListener() { public void onComplete(final AsyncEvent event) throws IOException { listener.onComplete(Servlet3Continuation.this); } public void onError(AsyncEvent event) throws IOException { listener.onComplete(Servlet3Continuation.this); } public void onStartAsync(AsyncEvent event) throws IOException { event.getAsyncContext().addListener(this); } public void onTimeout(AsyncEvent event) throws IOException { _expired=true; listener.onTimeout(Servlet3Continuation.this); } }; - if (_context==null) + if (_context!=null) _context.addListener(wrapped); else _listeners.add(wrapped); } /* ------------------------------------------------------------ */ public void complete() { AsyncContext context=_context; if (context==null) throw new IllegalStateException(); _context.complete(); } /* ------------------------------------------------------------ */ public ServletResponse getServletResponse() { return _response; } /* ------------------------------------------------------------ */ public boolean isExpired() { return _expired; } /* ------------------------------------------------------------ */ public boolean isInitial() { // TODO - this is not perfect if non continuation API is used directly return _initial&&_request.getDispatcherType()!=DispatcherType.ASYNC; } /* ------------------------------------------------------------ */ public boolean isResumed() { return _resumed; } /* ------------------------------------------------------------ */ public boolean isSuspended() { return _request.isAsyncStarted(); } /* ------------------------------------------------------------ */ public void keepWrappers() { _responseWrapped=true; } /* ------------------------------------------------------------ */ public void resume() { AsyncContext context=_context; if (context==null) throw new IllegalStateException(); _resumed=true; _context.dispatch(); } /* ------------------------------------------------------------ */ public void setTimeout(long timeoutMs) { _timeoutMs=timeoutMs; if (_context!=null) _context.setTimeout(timeoutMs); } /* ------------------------------------------------------------ */ public void suspend(ServletResponse response) { _response=response; _responseWrapped=response instanceof ServletResponseWrapper; _resumed=false; _expired=false; _context=_request.startAsync(); _context.setTimeout(_timeoutMs); for (AsyncListener listener:_listeners) _context.addListener(listener); _listeners.clear(); } /* ------------------------------------------------------------ */ public void suspend() { _resumed=false; _expired=false; _context=_request.startAsync(); _context.setTimeout(_timeoutMs); for (AsyncListener listener:_listeners) _context.addListener(listener); _listeners.clear(); } /* ------------------------------------------------------------ */ public boolean isResponseWrapped() { return _responseWrapped; } /* ------------------------------------------------------------ */ /** * @see org.eclipse.jetty.continuation.Continuation#getAttribute(java.lang.String) */ public Object getAttribute(String name) { return _request.getAttribute(name); } /* ------------------------------------------------------------ */ /** * @see org.eclipse.jetty.continuation.Continuation#removeAttribute(java.lang.String) */ public void removeAttribute(String name) { _request.removeAttribute(name); } /* ------------------------------------------------------------ */ /** * @see org.eclipse.jetty.continuation.Continuation#setAttribute(java.lang.String, java.lang.Object) */ public void setAttribute(String name, Object attribute) { _request.setAttribute(name,attribute); } /* ------------------------------------------------------------ */ /** * @see org.eclipse.jetty.continuation.Continuation#undispatch() */ public void undispatch() { if (isSuspended()) { if (ContinuationFilter.__debug) throw new ContinuationThrowable(); throw __exception; } throw new IllegalStateException("!suspended"); } }
true
true
public void addContinuationListener(final ContinuationListener listener) { AsyncListener wrapped = new AsyncListener() { public void onComplete(final AsyncEvent event) throws IOException { listener.onComplete(Servlet3Continuation.this); } public void onError(AsyncEvent event) throws IOException { listener.onComplete(Servlet3Continuation.this); } public void onStartAsync(AsyncEvent event) throws IOException { event.getAsyncContext().addListener(this); } public void onTimeout(AsyncEvent event) throws IOException { _expired=true; listener.onTimeout(Servlet3Continuation.this); } }; if (_context==null) _context.addListener(wrapped); else _listeners.add(wrapped); }
public void addContinuationListener(final ContinuationListener listener) { AsyncListener wrapped = new AsyncListener() { public void onComplete(final AsyncEvent event) throws IOException { listener.onComplete(Servlet3Continuation.this); } public void onError(AsyncEvent event) throws IOException { listener.onComplete(Servlet3Continuation.this); } public void onStartAsync(AsyncEvent event) throws IOException { event.getAsyncContext().addListener(this); } public void onTimeout(AsyncEvent event) throws IOException { _expired=true; listener.onTimeout(Servlet3Continuation.this); } }; if (_context!=null) _context.addListener(wrapped); else _listeners.add(wrapped); }
diff --git a/gsf-wra/src/main/java/com/fatwire/gst/foundation/httpstatus/StatusFilterHttpResponseWrapper.java b/gsf-wra/src/main/java/com/fatwire/gst/foundation/httpstatus/StatusFilterHttpResponseWrapper.java index 1f1d8cfb..291e0240 100644 --- a/gsf-wra/src/main/java/com/fatwire/gst/foundation/httpstatus/StatusFilterHttpResponseWrapper.java +++ b/gsf-wra/src/main/java/com/fatwire/gst/foundation/httpstatus/StatusFilterHttpResponseWrapper.java @@ -1,136 +1,135 @@ /* * Copyright 2010 FatWire Corporation. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.fatwire.gst.foundation.httpstatus; import static com.fatwire.gst.foundation.httpstatus.HttpStatusStrings.X_FATWIRE_HEADER; import static com.fatwire.gst.foundation.httpstatus.HttpStatusStrings.X_FATWIRE_STATUS; import java.io.IOException; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponseWrapper; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * <p> * A filter that transforms 2 special headers into a response status or response * header. In a ContentServer XML element you can call * ics.StreamHeader("X-Fatwire-Status","404") to set the response status for * Satellite Server to 404. * </p> * * * @version 15 June 2009 * @author Dolf Dijkstra * */ public class StatusFilterHttpResponseWrapper extends HttpServletResponseWrapper { private static Log log = LogFactory.getLog(StatusFilterHttpResponseWrapper.class.getPackage().getName()); private int status = -1; /** * Class constructor instatiating the response object */ public StatusFilterHttpResponseWrapper(HttpServletResponse origResponse) { super(origResponse); } /** * This method sets the response header value and names. It just proxies the * custom response header information if the environment is CS * (ContentServer). If the environment is SS (Satellite Server) then the * custom header information supplied as "X-FatWire-Header" and * "X-FatWire-Status" is parsed and set in the response header accordingly * * @param hdrName Response header name * @param hdrValue Response header value */ public void setHeader(String hdrName, String hdrValue) { if (log.isDebugEnabled()) { log.debug("original setHeader " + hdrName + ": " + hdrValue); } if (X_FATWIRE_STATUS.equalsIgnoreCase(hdrName)) { try { status = Integer.parseInt(hdrValue); } catch (Throwable t) { log.warn("Exception parsing the " + hdrName + " header. " + t.getMessage()); } if (status > 300) { // TODO low priority: is sendError needed for codes > 400? // TODO low priority: is sendRedirectNeeded for 302 or 301? if (log.isDebugEnabled()) { log.debug("setStatus to " + status + " from " + hdrName); } if (this.isCommitted()) { log.debug("wanted to setStatus to " + status + " from " + hdrName + " but the response is already committed"); } if (status >= 400) { try { super.sendError(status); } catch (IOException e) { log.warn("Could not send error " + status + ".", e); - super.setStatus(status); } } else { super.setStatus(status); } // ignore the header all together after the setStatus, so // we are not leaking to the public } else if (status != -1) { log.debug("ignoring status header with value " + status + " from " + hdrName); } } else if (X_FATWIRE_HEADER.equalsIgnoreCase(hdrName)) { // splitting header name/value based on passed in header value, // pipe seperated; String[] headers = hdrValue.split("\\|"); if (headers.length == 2 && headers[0] != null && headers[1] != null) { super.setHeader(headers[0], headers[1]); } else { log.debug(hdrName + " could not be split into something useful. " + hdrValue); } } else { super.setHeader(hdrName, hdrValue); } } @Override public void setStatus(int sc) { if (status == -1) { // only set it if we have not overridden it super.setStatus(sc); } else { if (log.isTraceEnabled()) { log.trace("setStatus " + sc + " is being ignored because " + X_FATWIRE_STATUS + " header set it to " + status); } } } }// end of BufferedHttpResponseWrapper
true
true
public void setHeader(String hdrName, String hdrValue) { if (log.isDebugEnabled()) { log.debug("original setHeader " + hdrName + ": " + hdrValue); } if (X_FATWIRE_STATUS.equalsIgnoreCase(hdrName)) { try { status = Integer.parseInt(hdrValue); } catch (Throwable t) { log.warn("Exception parsing the " + hdrName + " header. " + t.getMessage()); } if (status > 300) { // TODO low priority: is sendError needed for codes > 400? // TODO low priority: is sendRedirectNeeded for 302 or 301? if (log.isDebugEnabled()) { log.debug("setStatus to " + status + " from " + hdrName); } if (this.isCommitted()) { log.debug("wanted to setStatus to " + status + " from " + hdrName + " but the response is already committed"); } if (status >= 400) { try { super.sendError(status); } catch (IOException e) { log.warn("Could not send error " + status + ".", e); super.setStatus(status); } } else { super.setStatus(status); } // ignore the header all together after the setStatus, so // we are not leaking to the public } else if (status != -1) { log.debug("ignoring status header with value " + status + " from " + hdrName); } } else if (X_FATWIRE_HEADER.equalsIgnoreCase(hdrName)) { // splitting header name/value based on passed in header value, // pipe seperated; String[] headers = hdrValue.split("\\|"); if (headers.length == 2 && headers[0] != null && headers[1] != null) { super.setHeader(headers[0], headers[1]); } else { log.debug(hdrName + " could not be split into something useful. " + hdrValue); } } else { super.setHeader(hdrName, hdrValue); } }
public void setHeader(String hdrName, String hdrValue) { if (log.isDebugEnabled()) { log.debug("original setHeader " + hdrName + ": " + hdrValue); } if (X_FATWIRE_STATUS.equalsIgnoreCase(hdrName)) { try { status = Integer.parseInt(hdrValue); } catch (Throwable t) { log.warn("Exception parsing the " + hdrName + " header. " + t.getMessage()); } if (status > 300) { // TODO low priority: is sendError needed for codes > 400? // TODO low priority: is sendRedirectNeeded for 302 or 301? if (log.isDebugEnabled()) { log.debug("setStatus to " + status + " from " + hdrName); } if (this.isCommitted()) { log.debug("wanted to setStatus to " + status + " from " + hdrName + " but the response is already committed"); } if (status >= 400) { try { super.sendError(status); } catch (IOException e) { log.warn("Could not send error " + status + ".", e); } } else { super.setStatus(status); } // ignore the header all together after the setStatus, so // we are not leaking to the public } else if (status != -1) { log.debug("ignoring status header with value " + status + " from " + hdrName); } } else if (X_FATWIRE_HEADER.equalsIgnoreCase(hdrName)) { // splitting header name/value based on passed in header value, // pipe seperated; String[] headers = hdrValue.split("\\|"); if (headers.length == 2 && headers[0] != null && headers[1] != null) { super.setHeader(headers[0], headers[1]); } else { log.debug(hdrName + " could not be split into something useful. " + hdrValue); } } else { super.setHeader(hdrName, hdrValue); } }
diff --git a/src/ch/epfl/flamemaker/InterpolatedPalette.java b/src/ch/epfl/flamemaker/InterpolatedPalette.java index 39fbd1c..f6c249d 100644 --- a/src/ch/epfl/flamemaker/InterpolatedPalette.java +++ b/src/ch/epfl/flamemaker/InterpolatedPalette.java @@ -1,33 +1,37 @@ package ch.epfl.flamemaker; import java.util.List; import ch.epfl.flamemaker.color.Color; public class InterpolatedPalette implements Palette { List<Color> m_colors; public InterpolatedPalette(List<Color> colors) { if(colors.size() < 2) { throw new IllegalArgumentException("An interpolated palette must contain at least 2 colors"); } m_colors = colors; } @Override public Color colorForIndex(double index) { if(index < 0 || index > 1) { throw new IllegalArgumentException("index must be between 0 and 1"); } int nbColors = m_colors.size()-1; double lowColor = Math.floor(nbColors * index); double highColorWeight = index * nbColors - lowColor; double highColor = lowColor+1; + //Cas particulier quand index = 1.0 + if(highColor == m_colors.size() || lowColor == m_colors.size()){ + return m_colors.get(m_colors.size()-1); + } return m_colors.get((int) highColor).mixWith(m_colors.get((int) lowColor), highColorWeight); } }
true
true
public Color colorForIndex(double index) { if(index < 0 || index > 1) { throw new IllegalArgumentException("index must be between 0 and 1"); } int nbColors = m_colors.size()-1; double lowColor = Math.floor(nbColors * index); double highColorWeight = index * nbColors - lowColor; double highColor = lowColor+1; return m_colors.get((int) highColor).mixWith(m_colors.get((int) lowColor), highColorWeight); }
public Color colorForIndex(double index) { if(index < 0 || index > 1) { throw new IllegalArgumentException("index must be between 0 and 1"); } int nbColors = m_colors.size()-1; double lowColor = Math.floor(nbColors * index); double highColorWeight = index * nbColors - lowColor; double highColor = lowColor+1; //Cas particulier quand index = 1.0 if(highColor == m_colors.size() || lowColor == m_colors.size()){ return m_colors.get(m_colors.size()-1); } return m_colors.get((int) highColor).mixWith(m_colors.get((int) lowColor), highColorWeight); }
diff --git a/org.eclipse.mylyn.reviews.r4e.ui/src/org/eclipse/mylyn/reviews/r4e/ui/internal/properties/tabbed/AnomalyTabPropertySection.java b/org.eclipse.mylyn.reviews.r4e.ui/src/org/eclipse/mylyn/reviews/r4e/ui/internal/properties/tabbed/AnomalyTabPropertySection.java index 902fcaa..7502558 100644 --- a/org.eclipse.mylyn.reviews.r4e.ui/src/org/eclipse/mylyn/reviews/r4e/ui/internal/properties/tabbed/AnomalyTabPropertySection.java +++ b/org.eclipse.mylyn.reviews.r4e.ui/src/org/eclipse/mylyn/reviews/r4e/ui/internal/properties/tabbed/AnomalyTabPropertySection.java @@ -1,1081 +1,1082 @@ // $codepro.audit.disable com.instantiations.assist.eclipse.analysis.audit.rule.effectivejava.alwaysOverridetoString.alwaysOverrideToString, staticFieldSecurity, com.instantiations.assist.eclipse.analysis.deserializeabilitySecurity, com.instantiations.assist.eclipse.analysis.enforceCloneableUsageSecurity, com.instantiations.assist.eclipse.analysis.instanceFieldSecurity /******************************************************************************* * Copyright (c) 2010, 2012 Ericsson AB and others. * * All rights reserved. This program and the accompanying materials are * made available under the terms of the Eclipse Public License v1.0 which * accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Description: * * This class implements the tabbed property section for the Anomaly model element * * Contributors: * Sebastien Dubois - Created for Mylyn Review R4E project * ******************************************************************************/ package org.eclipse.mylyn.reviews.r4e.ui.internal.properties.tabbed; import java.text.SimpleDateFormat; import java.util.List; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.window.Window; import org.eclipse.mylyn.reviews.r4e.core.model.R4EAnomaly; import org.eclipse.mylyn.reviews.r4e.core.model.R4EAnomalyState; import org.eclipse.mylyn.reviews.r4e.core.model.R4ECommentType; import org.eclipse.mylyn.reviews.r4e.core.model.R4EReviewPhase; import org.eclipse.mylyn.reviews.r4e.core.model.R4EReviewState; import org.eclipse.mylyn.reviews.r4e.core.model.RModelFactory; import org.eclipse.mylyn.reviews.r4e.core.model.drules.R4EDesignRule; import org.eclipse.mylyn.reviews.r4e.core.model.drules.R4EDesignRuleClass; import org.eclipse.mylyn.reviews.r4e.core.model.drules.R4EDesignRuleRank; import org.eclipse.mylyn.reviews.r4e.core.model.serial.Persistence.RModelFactoryExt; import org.eclipse.mylyn.reviews.r4e.core.model.serial.impl.OutOfSyncException; import org.eclipse.mylyn.reviews.r4e.core.model.serial.impl.ResourceHandlingException; import org.eclipse.mylyn.reviews.r4e.ui.R4EUIPlugin; import org.eclipse.mylyn.reviews.r4e.ui.internal.dialogs.IAnomalyInputDialog; import org.eclipse.mylyn.reviews.r4e.ui.internal.dialogs.ICalendarDialog; import org.eclipse.mylyn.reviews.r4e.ui.internal.dialogs.R4EUIDialogFactory; import org.eclipse.mylyn.reviews.r4e.ui.internal.model.IR4EUIModelElement; import org.eclipse.mylyn.reviews.r4e.ui.internal.model.IR4EUIPosition; import org.eclipse.mylyn.reviews.r4e.ui.internal.model.R4EUIAnomalyBasic; import org.eclipse.mylyn.reviews.r4e.ui.internal.model.R4EUIAnomalyExtended; import org.eclipse.mylyn.reviews.r4e.ui.internal.model.R4EUIFileContext; import org.eclipse.mylyn.reviews.r4e.ui.internal.model.R4EUIModelController; import org.eclipse.mylyn.reviews.r4e.ui.internal.model.R4EUIPostponedAnomaly; import org.eclipse.mylyn.reviews.r4e.ui.internal.model.R4EUIReviewBasic; import org.eclipse.mylyn.reviews.r4e.ui.internal.utils.R4EUIConstants; import org.eclipse.mylyn.reviews.r4e.ui.internal.utils.UIUtils; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CCombo; import org.eclipse.swt.custom.CLabel; import org.eclipse.swt.custom.ScrolledComposite; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.forms.events.ExpansionAdapter; import org.eclipse.ui.forms.events.ExpansionEvent; import org.eclipse.ui.forms.widgets.ExpandableComposite; import org.eclipse.ui.views.properties.tabbed.ITabbedPropertyConstants; import org.eclipse.ui.views.properties.tabbed.TabbedPropertySheetPage; import org.eclipse.ui.views.properties.tabbed.TabbedPropertySheetWidgetFactory; /** * @author Sebastien Dubois * @version $Revision: 1.0 $ */ public class AnomalyTabPropertySection extends ModelElementTabPropertySection { // ------------------------------------------------------------------------ // Constants // ------------------------------------------------------------------------ /** * Field ANOMALY_DETAILS_SECTION_LABEL. (value is ""Anomaly Details"") */ private static final String ANOMALY_DETAILS_SECTION_LABEL = "Anomaly Details"; /** * Field PARTICIPANT_DETAILS_SECTION_LABEL. (value is ""Participants Details"") */ private static final String PARTICIPANT_DETAILS_SECTION_LABEL = "Participants Details"; // ------------------------------------------------------------------------ // Member variables // ------------------------------------------------------------------------ /** * Field fPosition. */ private IR4EUIPosition fPosition; /** * Field fTitleText. */ protected Text fTitleText = null; /** * Field fAuthorText. */ protected Text fAuthorText = null; /** * Field fCreationDateText. */ protected Text fCreationDateText = null; /** * Field fPositionText. */ protected Text fPositionText = null; /** * Field fDescriptionText. */ protected Text fDescriptionText = null; /** * Field fStateLabel. */ private CLabel fStateLabel = null; /** * Field fStateCombo. */ protected CCombo fStateCombo = null; /** * Field fClassCombo. */ protected CCombo fClassCombo = null; /** * Field fRankCombo. */ protected CCombo fRankCombo = null; /** * Field fRuleId. */ protected Text fRuleId = null; /** * Field fRuleButton. */ protected Button fRuleButton = null; /** * Field fDateText. */ protected Text fDateText = null; /** * Field fCalendarButton. */ protected Button fCalendarButton = null; /** * Field fDecidedByLabel. */ private CLabel fDecidedByLabel = null; /** * Field fDecidedByCombo. */ protected CCombo fDecidedByCombo = null; /** * Field fFixedByLabel. */ private CLabel fFixedByLabel = null; /** * Field fFixedByCombo. */ protected CCombo fFixedByCombo = null; /** * Field fFollowUpByLabel. */ private CLabel fFollowUpByLabel = null; /** * Field fFollowUpByCombo. */ protected CCombo fFollowUpByCombo = null; /** * Field fAssignedToCombo. */ private CCombo fAssignedToCombo; // ------------------------------------------------------------------------ // Methods // ------------------------------------------------------------------------ /** * Method shouldUseExtraSpace. * * @return boolean * @see org.eclipse.ui.views.properties.tabbed.ISection#shouldUseExtraSpace() */ @Override public boolean shouldUseExtraSpace() { return true; } /** * Method createControls. * * @param parent * Composite * @param aTabbedPropertySheetPage * TabbedPropertySheetPage * @see org.eclipse.ui.views.properties.tabbed.ISection#createControls(Composite, TabbedPropertySheetPage) */ @Override public void createControls(Composite parent, TabbedPropertySheetPage aTabbedPropertySheetPage) { super.createControls(parent, aTabbedPropertySheetPage); //Tell element to build its own detailed tab layout final TabbedPropertySheetWidgetFactory widgetFactory = aTabbedPropertySheetPage.getWidgetFactory(); final Composite composite = widgetFactory.createFlatFormComposite(parent); FormData data = null; //Anomaly title widgetFactory.setBorderStyle(SWT.BORDER); fTitleText = widgetFactory.createText(composite, "", SWT.MULTI); data = new FormData(); data.left = new FormAttachment(0, R4EUIConstants.TABBED_PROPERTY_LABEL_WIDTH); data.right = new FormAttachment(100, 0); // $codepro.audit.disable numericLiterals data.top = new FormAttachment(0, ITabbedPropertyConstants.VSPACE); fTitleText.setToolTipText(R4EUIConstants.ANOMALY_TITLE_TOOLTIP); fTitleText.setLayoutData(data); fTitleText.addListener(SWT.FocusOut, new Listener() { public void handleEvent(Event event) { if (!fRefreshInProgress) { try { //Set new model data final String currentUser = R4EUIModelController.getReviewer(); final R4EAnomaly modelAnomaly = ((R4EUIAnomalyBasic) fProperties.getElement()).getAnomaly(); String newValue = fTitleText.getText().trim(); if (!newValue.equals(modelAnomaly.getTitle())) { final Long bookNum = R4EUIModelController.FResourceUpdater.checkOut(modelAnomaly, currentUser); modelAnomaly.setTitle(newValue); R4EUIModelController.FResourceUpdater.checkIn(bookNum); //Set new UI display if (fProperties.getElement() instanceof R4EUIAnomalyExtended) { fProperties.getElement().setName( R4EUIAnomalyExtended.buildAnomalyExtName(modelAnomaly, ((R4EUIAnomalyExtended) fProperties.getElement()).getPosition())); } else { fProperties.getElement().setName( R4EUIAnomalyBasic.buildAnomalyName(modelAnomaly, ((R4EUIAnomalyBasic) fProperties.getElement()).getPosition())); } } fTitleText.setText(newValue); } catch (ResourceHandlingException e1) { UIUtils.displayResourceErrorDialog(e1); } catch (OutOfSyncException e1) { UIUtils.displaySyncErrorDialog(e1); } } R4EUIModelController.getNavigatorView().getTreeViewer().refresh(); refresh(); } }); UIUtils.addTabbedPropertiesTextResizeListener(fTitleText); final CLabel titleLabel = widgetFactory.createCLabel(composite, R4EUIConstants.TITLE_LABEL); data = new FormData(); data.left = new FormAttachment(0, 0); data.right = new FormAttachment(fTitleText, -ITabbedPropertyConstants.HSPACE); data.top = new FormAttachment(fTitleText, 0, SWT.CENTER); titleLabel.setToolTipText(R4EUIConstants.ANOMALY_TITLE_TOOLTIP); titleLabel.setLayoutData(data); //Anomaly Description (Read-Only) widgetFactory.setBorderStyle(SWT.NULL); fDescriptionText = widgetFactory.createText(composite, "", SWT.MULTI); data = new FormData(); data.left = new FormAttachment(0, R4EUIConstants.TABBED_PROPERTY_LABEL_WIDTH); data.right = new FormAttachment(100, 0); // $codepro.audit.disable numericLiterals data.top = new FormAttachment(fTitleText, ITabbedPropertyConstants.VSPACE); fDescriptionText.setEditable(false); fDescriptionText.setLayoutData(data); fDescriptionText.setToolTipText(R4EUIConstants.ANOMALY_DESCRIPTION_TOOLTIP); final CLabel descriptionLabel = widgetFactory.createCLabel(composite, R4EUIConstants.DESCRIPTION_LABEL); data = new FormData(); data.left = new FormAttachment(0, 0); data.right = new FormAttachment(fDescriptionText, -ITabbedPropertyConstants.HSPACE); data.top = new FormAttachment(fDescriptionText, 0, SWT.CENTER); descriptionLabel.setToolTipText(R4EUIConstants.ANOMALY_DESCRIPTION_TOOLTIP); descriptionLabel.setLayoutData(data); //State widgetFactory.setBorderStyle(SWT.BORDER); fStateCombo = widgetFactory.createCCombo(composite, SWT.READ_ONLY); data = new FormData(); data.left = new FormAttachment(0, R4EUIConstants.TABBED_PROPERTY_LABEL_WIDTH); data.right = new FormAttachment(100, 0); // $codepro.audit.disable numericLiterals data.top = new FormAttachment(fDescriptionText, ITabbedPropertyConstants.VSPACE); fStateCombo.setToolTipText(R4EUIConstants.ANOMALY_STATE_TOOLTIP); fStateCombo.setVisibleItemCount(6); fStateCombo.setLayoutData(data); fStateCombo.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { if (!fRefreshInProgress) { final R4EAnomalyState newState = R4EUIAnomalyExtended.getStateFromString(fStateCombo.getText()); final R4EAnomalyState oldState = ((R4EUIAnomalyBasic) fProperties.getElement()).getAnomaly() .getState(); if (!newState.equals(oldState)) { if (newState.equals(R4EAnomalyState.R4E_ANOMALY_STATE_REJECTED) && !oldState.equals(R4EAnomalyState.R4E_ANOMALY_STATE_REJECTED)) { final boolean commentResult = ((R4EUIAnomalyBasic) fProperties.getElement()).createComment(true); if (commentResult) { UIUtils.changeAnomalyState(fProperties.getElement(), newState); return; } else { final ErrorDialog dialog = new ErrorDialog(null, R4EUIConstants.DIALOG_TITLE_ERROR, "Cannot change Anomaly State", new Status(IStatus.ERROR, R4EUIPlugin.PLUGIN_ID, 0, "Please enter a reason for rejecting this anomaly", null), IStatus.ERROR); Display.getDefault().syncExec(new Runnable() { public void run() { dialog.open(); } }); refresh(); return; } } UIUtils.changeAnomalyState(fProperties.getElement(), newState); } } refresh(); R4EUIModelController.getNavigatorView().getTreeViewer().refresh(); } }); addScrollListener(fStateCombo); fStateLabel = widgetFactory.createCLabel(composite, R4EUIConstants.STATE_LABEL); data = new FormData(); data.left = new FormAttachment(0, 0); data.right = new FormAttachment(fStateCombo, -ITabbedPropertyConstants.HSPACE); data.top = new FormAttachment(fStateCombo, 0, SWT.CENTER); fStateLabel.setToolTipText(R4EUIConstants.ANOMALY_STATE_TOOLTIP); fStateLabel.setLayoutData(data); //Assigned To fAssignedToCombo = widgetFactory.createCCombo(composite, SWT.READ_ONLY); data = new FormData(); data.left = new FormAttachment(0, R4EUIConstants.TABBED_PROPERTY_LABEL_WIDTH); data.right = new FormAttachment(100, 0); // $codepro.audit.disable numericLiterals data.top = new FormAttachment(fStateCombo, ITabbedPropertyConstants.VSPACE); fAssignedToCombo.setToolTipText(R4EUIConstants.ASSIGNED_TO_TOOLTIP); fAssignedToCombo.setLayoutData(data); fAssignedToCombo.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { if (!fRefreshInProgress) { try { final String currentUser = R4EUIModelController.getReviewer(); final R4EAnomaly modelAnomaly = ((R4EUIAnomalyBasic) fProperties.getElement()).getAnomaly(); if (!modelAnomaly.getAssignedTo().contains(fAssignedToCombo.getText())) { final Long bookNum = R4EUIModelController.FResourceUpdater.checkOut(modelAnomaly, currentUser); modelAnomaly.getAssignedTo().clear(); modelAnomaly.getAssignedTo().add(fAssignedToCombo.getText()); R4EUIModelController.FResourceUpdater.checkIn(bookNum); } } catch (ResourceHandlingException e1) { UIUtils.displayResourceErrorDialog(e1); } catch (OutOfSyncException e1) { UIUtils.displaySyncErrorDialog(e1); } } R4EUIModelController.getNavigatorView().getTreeViewer().refresh(); refresh(); } }); addScrollListener(fAssignedToCombo); final CLabel assignedToLabel = widgetFactory.createCLabel(composite, R4EUIConstants.ASSIGNED_TO_LABEL); data = new FormData(); data.left = new FormAttachment(0, 0); data.right = new FormAttachment(fAssignedToCombo, -ITabbedPropertyConstants.HSPACE); data.top = new FormAttachment(fAssignedToCombo, 0, SWT.CENTER); assignedToLabel.setToolTipText(R4EUIConstants.ASSIGNED_TO_TOOLTIP); assignedToLabel.setLayoutData(data); createParticipantDetailsSection(widgetFactory, composite, createAnomalyDetailsSection(widgetFactory, composite)); } /** * Method createAnomalyDetailsSection. * * @param aWidgetFactory * TabbedPropertySheetWidgetFactory * @param aComposite * Composite * @return Composite */ private Composite createAnomalyDetailsSection(TabbedPropertySheetWidgetFactory aWidgetFactory, final Composite aComposite) { //Anomaly Details section final ExpandableComposite anomalyDetailsSection = aWidgetFactory.createExpandableComposite(aComposite, ExpandableComposite.TWISTIE); final FormData data = new FormData(); data.left = new FormAttachment(0, 0); data.right = new FormAttachment(100, 0); // $codepro.audit.disable numericLiterals data.top = new FormAttachment(fAssignedToCombo, ITabbedPropertyConstants.VSPACE); anomalyDetailsSection.setLayoutData(data); anomalyDetailsSection.setText(ANOMALY_DETAILS_SECTION_LABEL); anomalyDetailsSection.addExpansionListener(new ExpansionAdapter() { @Override public void expansionStateChanged(ExpansionEvent e) { final ScrolledComposite scrolledParent = (ScrolledComposite) aComposite.getParent() .getParent() .getParent() .getParent() .getParent(); scrolledParent.setMinSize(aComposite.computeSize(SWT.DEFAULT, SWT.DEFAULT)); scrolledParent.layout(true, true); } }); anomalyDetailsSection.setLayout(new GridLayout(1, false)); final Composite anomalyDetailsSectionClient = aWidgetFactory.createComposite(anomalyDetailsSection); anomalyDetailsSectionClient.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); anomalyDetailsSectionClient.setLayout(new GridLayout(4, false)); anomalyDetailsSection.setClient(anomalyDetailsSectionClient); //Anomaly Creation Date (read-only) final CLabel creationDateLabel = aWidgetFactory.createCLabel(anomalyDetailsSectionClient, R4EUIConstants.CREATION_DATE_LABEL); GridData gridData = new GridData(SWT.FILL, SWT.CENTER, false, false); gridData.horizontalSpan = 1; creationDateLabel.setToolTipText(R4EUIConstants.ANOMALY_CREATION_DATE_TOOLTIP); creationDateLabel.setLayoutData(gridData); aWidgetFactory.setBorderStyle(SWT.NULL); fCreationDateText = aWidgetFactory.createText(anomalyDetailsSectionClient, "", SWT.NULL); gridData = new GridData(SWT.FILL, SWT.CENTER, true, false); gridData.horizontalSpan = 3; fCreationDateText.setEditable(false); fCreationDateText.setToolTipText(R4EUIConstants.ANOMALY_CREATION_DATE_TOOLTIP); fCreationDateText.setLayoutData(gridData); //Anomaly position (read-only) final CLabel positionLabel = aWidgetFactory.createCLabel(anomalyDetailsSectionClient, R4EUIConstants.POSITION_LABEL); gridData = new GridData(SWT.FILL, SWT.CENTER, false, false); gridData.horizontalSpan = 1; positionLabel.setToolTipText(R4EUIConstants.ANOMALY_POSITION_TOOLTIP); positionLabel.setLayoutData(gridData); fPositionText = aWidgetFactory.createText(anomalyDetailsSectionClient, "", SWT.NULL); gridData = new GridData(SWT.FILL, SWT.CENTER, true, false); gridData.horizontalSpan = 3; fPositionText.setEditable(false); fPositionText.setToolTipText(R4EUIConstants.ANOMALY_POSITION_TOOLTIP); fPositionText.setLayoutData(gridData); //Class final CLabel classLabel = aWidgetFactory.createCLabel(anomalyDetailsSectionClient, R4EUIConstants.CLASS_LABEL); gridData = new GridData(SWT.FILL, SWT.CENTER, false, false); gridData.horizontalSpan = 1; classLabel.setToolTipText(R4EUIConstants.ANOMALY_CLASS_TOOLTIP); classLabel.setLayoutData(gridData); aWidgetFactory.setBorderStyle(SWT.BORDER); fClassCombo = aWidgetFactory.createCCombo(anomalyDetailsSectionClient, SWT.READ_ONLY); int size = UIUtils.getClasses().length; fClassCombo.setVisibleItemCount(size); gridData = new GridData(SWT.FILL, SWT.CENTER, true, false); gridData.horizontalSpan = 3; fClassCombo.setToolTipText(R4EUIConstants.ANOMALY_CLASS_TOOLTIP); fClassCombo.setLayoutData(gridData); fClassCombo.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { if (!fRefreshInProgress) { try { final String currentUser = R4EUIModelController.getReviewer(); final R4EAnomaly modelAnomaly = ((R4EUIAnomalyBasic) fProperties.getElement()).getAnomaly(); R4EDesignRuleClass newClass = UIUtils.getClassFromString(fClassCombo.getText()); R4EDesignRuleClass oldClass = null; if (null != modelAnomaly.getType()) { oldClass = ((R4ECommentType) modelAnomaly.getType()).getType(); } if (!newClass.equals(oldClass)) { final Long bookNum = R4EUIModelController.FResourceUpdater.checkOut(modelAnomaly, currentUser); final R4ECommentType type = RModelFactoryExt.eINSTANCE.createR4ECommentType(); type.setType(newClass); modelAnomaly.setType(type); R4EUIModelController.FResourceUpdater.checkIn(bookNum); } } catch (ResourceHandlingException e1) { UIUtils.displayResourceErrorDialog(e1); } catch (OutOfSyncException e1) { UIUtils.displaySyncErrorDialog(e1); } refresh(); } } }); addScrollListener(fClassCombo); //Rank final CLabel rankLabel = aWidgetFactory.createCLabel(anomalyDetailsSectionClient, R4EUIConstants.RANK_LABEL); gridData = new GridData(SWT.FILL, SWT.CENTER, false, false); gridData.horizontalSpan = 1; rankLabel.setToolTipText(R4EUIConstants.ANOMALY_RANK_TOOLTIP); rankLabel.setLayoutData(gridData); fRankCombo = aWidgetFactory.createCCombo(anomalyDetailsSectionClient, SWT.READ_ONLY); fRankCombo.setToolTipText(R4EUIConstants.ANOMALY_RANK_TOOLTIP); gridData = new GridData(SWT.FILL, SWT.CENTER, true, false); gridData.horizontalSpan = 3; fRankCombo.setLayoutData(gridData); fRankCombo.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { if (!fRefreshInProgress) { try { final String currentUser = R4EUIModelController.getReviewer(); final R4EAnomaly modelAnomaly = ((R4EUIAnomalyBasic) fProperties.getElement()).getAnomaly(); R4EDesignRuleRank newRank = UIUtils.getRankFromString(fRankCombo.getText()); R4EDesignRuleRank oldRank = modelAnomaly.getRank(); if (!newRank.equals(oldRank)) { final Long bookNum = R4EUIModelController.FResourceUpdater.checkOut(modelAnomaly, currentUser); modelAnomaly.setRank(newRank); R4EUIModelController.FResourceUpdater.checkIn(bookNum); } } catch (ResourceHandlingException e1) { UIUtils.displayResourceErrorDialog(e1); } catch (OutOfSyncException e1) { UIUtils.displaySyncErrorDialog(e1); } } refresh(); } }); addScrollListener(fRankCombo); //RuleId final CLabel ruleIdLabel = aWidgetFactory.createCLabel(anomalyDetailsSectionClient, R4EUIConstants.RULE_ID_LABEL); gridData = new GridData(SWT.FILL, SWT.CENTER, false, false); gridData.horizontalSpan = 1; ruleIdLabel.setToolTipText(R4EUIConstants.ANOMALY_RULE_ID_TOOLTIP); ruleIdLabel.setLayoutData(gridData); final Composite ruleComposite = aWidgetFactory.createComposite(anomalyDetailsSectionClient); gridData = new GridData(SWT.FILL, SWT.FILL, true, false); gridData.horizontalSpan = 3; ruleComposite.setToolTipText(R4EUIConstants.ANOMALY_RULE_ID_TOOLTIP); ruleComposite.setLayoutData(gridData); ruleComposite.setLayout(new GridLayout(2, false)); fRuleId = aWidgetFactory.createText(ruleComposite, "", SWT.NULL); fRuleId.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); fRuleId.setEditable(false); fRuleButton = aWidgetFactory.createButton(ruleComposite, R4EUIConstants.UPDATE_LABEL, SWT.NONE); fRuleButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); fRuleButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { //Modify anomaly R4EUIModelController.setJobInProgress(true); final R4EAnomaly modelAnomaly = ((R4EUIAnomalyBasic) fProperties.getElement()).getAnomaly(); final IAnomalyInputDialog dialog = R4EUIDialogFactory.getInstance().getNewAnomalyInputDialog(); dialog.create(); dialog.setTitle(modelAnomaly.getTitle()); dialog.setDescription(modelAnomaly.getDescription()); dialog.setDueDate(modelAnomaly.getDueDate()); if (modelAnomaly.getAssignedTo().size() > 0) { dialog.setAssigned(modelAnomaly.getAssignedTo().get(0)); } if (null != modelAnomaly.getType()) { dialog.setClass_(((R4ECommentType) modelAnomaly.getType()).getType()); } dialog.setRank(modelAnomaly.getRank()); dialog.setRuleID(modelAnomaly.getRuleID()); final int result = dialog.open(); if (result == Window.OK) { if (!fRefreshInProgress) { try { //Set new model data final String currentUser = R4EUIModelController.getReviewer(); final Long bookNum = R4EUIModelController.FResourceUpdater.checkOut(modelAnomaly, currentUser); modelAnomaly.setTitle(dialog.getAnomalyTitleValue()); modelAnomaly.setDescription(dialog.getAnomalyDescriptionValue()); modelAnomaly.setDueDate(dialog.getDueDate()); modelAnomaly.getAssignedTo().clear(); modelAnomaly.getAssignedTo().add(dialog.getAssigned()); if (null != dialog.getRuleReferenceValue()) { final R4EDesignRule rule = dialog.getRuleReferenceValue(); final R4ECommentType commentType = RModelFactory.eINSTANCE.createR4ECommentType(); commentType.setType(rule.getClass_()); modelAnomaly.setType(commentType); modelAnomaly.setRank(rule.getRank()); modelAnomaly.setRuleID(rule.getId()); } else { final R4ECommentType commentType = RModelFactory.eINSTANCE.createR4ECommentType(); commentType.setType(dialog.getClass_()); modelAnomaly.setType(commentType); modelAnomaly.setRank(dialog.getRank()); modelAnomaly.setRuleID(""); } R4EUIModelController.FResourceUpdater.checkIn(bookNum); //Set new UI display if (fProperties.getElement() instanceof R4EUIAnomalyExtended) { fProperties.getElement().setName( R4EUIAnomalyExtended.buildAnomalyExtName(modelAnomaly, ((R4EUIAnomalyBasic) fProperties.getElement()).getPosition())); } else { fProperties.getElement().setName( R4EUIAnomalyBasic.buildAnomalyName(modelAnomaly, ((R4EUIAnomalyBasic) fProperties.getElement()).getPosition())); } } catch (ResourceHandlingException e1) { UIUtils.displayResourceErrorDialog(e1); } catch (OutOfSyncException e1) { UIUtils.displaySyncErrorDialog(e1); } } } R4EUIModelController.setJobInProgress(false); //Enable view + R4EUIModelController.getNavigatorView().getTreeViewer().refresh(); refresh(); } }); //Due Date final CLabel dateLabel = aWidgetFactory.createCLabel(anomalyDetailsSectionClient, R4EUIConstants.DUE_DATE_LABEL); gridData = new GridData(SWT.FILL, SWT.CENTER, false, false); gridData.horizontalSpan = 1; dateLabel.setLayoutData(gridData); final Composite dateComposite = aWidgetFactory.createComposite(anomalyDetailsSectionClient); gridData = new GridData(SWT.FILL, SWT.FILL, true, true); gridData.horizontalSpan = 3; dateComposite.setToolTipText(R4EUIConstants.ANOMALY_DUE_DATE_TOOLTIP); dateComposite.setLayoutData(gridData); dateComposite.setLayout(new GridLayout(2, false)); fDateText = aWidgetFactory.createText(dateComposite, "", SWT.NULL); fDateText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); fDateText.setEditable(false); fCalendarButton = aWidgetFactory.createButton(dateComposite, "...", SWT.NONE); fCalendarButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); fCalendarButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { final ICalendarDialog dialog = R4EUIDialogFactory.getInstance().getCalendarDialog(); final int result = dialog.open(); if (result == Window.OK) { final SimpleDateFormat dateFormat = new SimpleDateFormat(R4EUIConstants.SIMPLE_DATE_FORMAT); fDateText.setText(dateFormat.format(dialog.getDate())); if (!fRefreshInProgress) { try { final String currentUser = R4EUIModelController.getReviewer(); final R4EAnomaly modelAnomaly = ((R4EUIAnomalyBasic) fProperties.getElement()).getAnomaly(); final Long bookNum = R4EUIModelController.FResourceUpdater.checkOut(modelAnomaly, currentUser); modelAnomaly.setDueDate(dialog.getDate()); R4EUIModelController.FResourceUpdater.checkIn(bookNum); } catch (ResourceHandlingException e1) { UIUtils.displayResourceErrorDialog(e1); } catch (OutOfSyncException e1) { UIUtils.displaySyncErrorDialog(e1); } } refresh(); } } }); return anomalyDetailsSection; } /** * Method createParticipantDetailsSection. * * @param aWidgetFactory * TabbedPropertySheetWidgetFactory * @param aComposite * Composite * @param aTopComposite * Composite */ private void createParticipantDetailsSection(TabbedPropertySheetWidgetFactory aWidgetFactory, final Composite aComposite, final Composite aTopComposite) { //Participants Details section final ExpandableComposite participantDetailsSection = aWidgetFactory.createExpandableComposite(aComposite, ExpandableComposite.TWISTIE); final FormData data = new FormData(); data.left = new FormAttachment(0, 0); data.right = new FormAttachment(100, 0); // $codepro.audit.disable numericLiterals data.top = new FormAttachment(aTopComposite, ITabbedPropertyConstants.VSPACE); participantDetailsSection.setLayoutData(data); participantDetailsSection.setText(PARTICIPANT_DETAILS_SECTION_LABEL); participantDetailsSection.addExpansionListener(new ExpansionAdapter() { @Override public void expansionStateChanged(ExpansionEvent e) { final ScrolledComposite scrolledParent = (ScrolledComposite) aComposite.getParent() .getParent() .getParent() .getParent() .getParent(); scrolledParent.setMinSize(aComposite.computeSize(SWT.DEFAULT, SWT.DEFAULT)); scrolledParent.layout(true, true); } }); participantDetailsSection.setLayout(new GridLayout(1, false)); final Composite participantDetailsSectionClient = aWidgetFactory.createComposite(participantDetailsSection); participantDetailsSectionClient.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); participantDetailsSectionClient.setLayout(new GridLayout(4, false)); participantDetailsSection.setClient(participantDetailsSectionClient); //Anomaly Author (read-only) final CLabel authorLabel = aWidgetFactory.createCLabel(participantDetailsSectionClient, R4EUIConstants.AUTHOR_LABEL); GridData gridData = new GridData(SWT.FILL, SWT.CENTER, false, false); gridData.horizontalSpan = 1; authorLabel.setToolTipText(R4EUIConstants.ANOMALY_AUTHOR_TOOLTIP); authorLabel.setLayoutData(gridData); aWidgetFactory.setBorderStyle(SWT.NULL); fAuthorText = aWidgetFactory.createText(participantDetailsSectionClient, "", SWT.NULL); gridData = new GridData(SWT.FILL, SWT.CENTER, true, false); gridData.horizontalSpan = 3; fAuthorText.setEditable(false); fAuthorText.setToolTipText(R4EUIConstants.ANOMALY_AUTHOR_TOOLTIP); fAuthorText.setLayoutData(gridData); //Decided by aWidgetFactory.setBorderStyle(SWT.BORDER); fDecidedByLabel = aWidgetFactory.createCLabel(participantDetailsSectionClient, R4EUIConstants.DECIDED_BY_LABEL); gridData = new GridData(SWT.FILL, SWT.CENTER, false, false); gridData.horizontalSpan = 1; fDecidedByLabel.setToolTipText(R4EUIConstants.ANOMALY_DECIDED_BY_TOOLTIP); fDecidedByLabel.setLayoutData(gridData); fDecidedByCombo = aWidgetFactory.createCCombo(participantDetailsSectionClient, SWT.READ_ONLY); gridData = new GridData(SWT.FILL, SWT.CENTER, true, false); gridData.horizontalSpan = 3; fDecidedByCombo.setToolTipText(R4EUIConstants.ANOMALY_DECIDED_BY_TOOLTIP); fDecidedByCombo.setLayoutData(gridData); fDecidedByCombo.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { if (!fRefreshInProgress) { try { final String currentUser = R4EUIModelController.getReviewer(); final R4EAnomaly modelAnomaly = ((R4EUIAnomalyExtended) fProperties.getElement()).getAnomaly(); if (!fDecidedByCombo.getText().equals(modelAnomaly.getDecidedByID())) { final Long bookNum = R4EUIModelController.FResourceUpdater.checkOut(modelAnomaly, currentUser); modelAnomaly.setDecidedByID(fDecidedByCombo.getText()); R4EUIModelController.FResourceUpdater.checkIn(bookNum); } } catch (ResourceHandlingException e1) { UIUtils.displayResourceErrorDialog(e1); } catch (OutOfSyncException e1) { UIUtils.displaySyncErrorDialog(e1); } } refresh(); } }); addScrollListener(fDecidedByCombo); //Fixed by fFixedByLabel = aWidgetFactory.createCLabel(participantDetailsSectionClient, R4EUIConstants.FIXED_BY_LABEL); gridData = new GridData(SWT.FILL, SWT.CENTER, false, false); gridData.horizontalSpan = 1; fFixedByLabel.setToolTipText(R4EUIConstants.ANOMALY_FIXED_BY_TOOLTIP); fFixedByLabel.setLayoutData(gridData); fFixedByCombo = aWidgetFactory.createCCombo(participantDetailsSectionClient, SWT.READ_ONLY); gridData = new GridData(SWT.FILL, SWT.CENTER, true, false); gridData.horizontalSpan = 3; fFixedByCombo.setToolTipText(R4EUIConstants.ANOMALY_FIXED_BY_TOOLTIP); fFixedByCombo.setLayoutData(gridData); fFixedByCombo.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { if (!fRefreshInProgress) { try { final String currentUser = R4EUIModelController.getReviewer(); final R4EAnomaly modelAnomaly = ((R4EUIAnomalyExtended) fProperties.getElement()).getAnomaly(); if (!fFixedByCombo.getText().equals(modelAnomaly.getFixedByID())) { final Long bookNum = R4EUIModelController.FResourceUpdater.checkOut(modelAnomaly, currentUser); modelAnomaly.setFixedByID(fFixedByCombo.getText()); R4EUIModelController.FResourceUpdater.checkIn(bookNum); } } catch (ResourceHandlingException e1) { UIUtils.displayResourceErrorDialog(e1); } catch (OutOfSyncException e1) { UIUtils.displaySyncErrorDialog(e1); } } refresh(); } }); addScrollListener(fFixedByCombo); //Follow-up by fFollowUpByLabel = aWidgetFactory.createCLabel(participantDetailsSectionClient, R4EUIConstants.FOLLOWUP_BY_LABEL); gridData = new GridData(SWT.FILL, SWT.CENTER, false, false); gridData.horizontalSpan = 1; fFollowUpByLabel.setToolTipText(R4EUIConstants.ANOMALY_FOLLOWUP_BY_TOOLTIP); fFollowUpByLabel.setLayoutData(gridData); fFollowUpByCombo = aWidgetFactory.createCCombo(participantDetailsSectionClient, SWT.READ_ONLY); gridData = new GridData(SWT.FILL, SWT.CENTER, true, false); gridData.horizontalSpan = 3; fFollowUpByCombo.setToolTipText(R4EUIConstants.ANOMALY_FOLLOWUP_BY_TOOLTIP); fFollowUpByCombo.setLayoutData(gridData); fFollowUpByCombo.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { if (!fRefreshInProgress) { try { final String currentUser = R4EUIModelController.getReviewer(); final R4EAnomaly modelAnomaly = ((R4EUIAnomalyExtended) fProperties.getElement()).getAnomaly(); if (!fFollowUpByCombo.getText().equals(modelAnomaly.getFollowUpByID())) { final Long bookNum = R4EUIModelController.FResourceUpdater.checkOut(modelAnomaly, currentUser); modelAnomaly.setFollowUpByID(fFollowUpByCombo.getText()); R4EUIModelController.FResourceUpdater.checkIn(bookNum); } } catch (ResourceHandlingException e1) { UIUtils.displayResourceErrorDialog(e1); } catch (OutOfSyncException e1) { UIUtils.displaySyncErrorDialog(e1); } } refresh(); } }); addScrollListener(fFollowUpByCombo); } /** * Method refresh. * * @see org.eclipse.ui.views.properties.tabbed.ISection#refresh() */ @Override public void refresh() { fRefreshInProgress = true; final R4EUIAnomalyBasic uiModelAnomaly = (R4EUIAnomalyBasic) fProperties.getElement(); final R4EAnomaly modelAnomaly = uiModelAnomaly.getAnomaly(); fTitleText.setText(modelAnomaly.getTitle()); fAuthorText.setText(modelAnomaly.getUser().getId()); fCreationDateText.setText(modelAnomaly.getCreatedOn().toString()); fPosition = ((R4EUIAnomalyBasic) fProperties.getElement()).getPosition(); if (null == fPosition) { fPositionText.setText(R4EUIConstants.GLOBAL_ANOMALY_PROPERTY_VALUE); } else { fPositionText.setText(fPosition.toString()); } fDescriptionText.setText(modelAnomaly.getDescription()); //Here we need to get a handle to the parent review to get the list of participants String[] participants = { "" }; IR4EUIModelElement element = uiModelAnomaly.getParent().getParent(); if (element instanceof R4EUIReviewBasic) { //Global anomaly List<String> participantsStr = ((R4EUIReviewBasic) element).getParticipantIDs(); participants = participantsStr.toArray(new String[participantsStr.size()]); } else if (element instanceof R4EUIFileContext) { //Local anomaly List<String> participantsStr = ((R4EUIReviewBasic) element.getParent().getParent()).getParticipantIDs(); participants = participantsStr.toArray(new String[participantsStr.size()]); } //Reset assignment combo values to current participants fAssignedToCombo.removeAll(); fAssignedToCombo.add(""); for (String participant : participants) { fAssignedToCombo.add(participant); } if (modelAnomaly.getAssignedTo().size() > 0 && null != modelAnomaly.getAssignedTo().get(0)) { fAssignedToCombo.setText(modelAnomaly.getAssignedTo().get(0)); } else { fAssignedToCombo.setText(""); } fClassCombo.setItems(UIUtils.getClasses()); if (null != modelAnomaly.getType() && null != ((R4ECommentType) modelAnomaly.getType()).getType()) { fClassCombo.select(((R4ECommentType) modelAnomaly.getType()).getType().getValue()); } else { fClassCombo.setText(""); } fRankCombo.setItems(UIUtils.getRanks()); //Bug 368865: Mapping needed for DEPRECATED value to MINOR final int rankValue = modelAnomaly.getRank().getValue(); fRankCombo.select(rankValue == R4EDesignRuleRank.R4E_RANK_DEPRECATED_VALUE ? R4EDesignRuleRank.R4E_RANK_MINOR_VALUE : rankValue); if (null != modelAnomaly.getRuleID()) { fRuleId.setText(modelAnomaly.getRuleID()); } if (null != modelAnomaly.getDueDate()) { final SimpleDateFormat dateFormat = new SimpleDateFormat(R4EUIConstants.SIMPLE_DATE_FORMAT); fDateText.setText(dateFormat.format(modelAnomaly.getDueDate())); } else { fDateText.setText(""); } if (fProperties.getElement() instanceof R4EUIAnomalyExtended) { fStateCombo.setItems(((R4EUIAnomalyExtended) uiModelAnomaly).getAvailableStates()); fStateCombo.select(((R4EUIAnomalyExtended) uiModelAnomaly).mapStateToIndex(modelAnomaly.getState())); if (null != R4EUIModelController.getActiveReview()) { fDecidedByCombo.setItems(participants); fDecidedByCombo.select(UIUtils.mapParticipantToIndex(modelAnomaly.getDecidedByID())); fFixedByCombo.setItems(participants); fFixedByCombo.select(UIUtils.mapParticipantToIndex(modelAnomaly.getFixedByID())); fFollowUpByCombo.setItems(participants); fFollowUpByCombo.select(UIUtils.mapParticipantToIndex(modelAnomaly.getFollowUpByID())); } } setEnabledFields(); fRefreshInProgress = false; } /** * Method setEditableFields. */ @Override protected void setEnabledFields() { //Since it is a subclass of this class we need this here. This should be improved later //Do not show Anomaly elements for the Postponed Anomaly. if (fProperties.getElement() instanceof R4EUIPostponedAnomaly) { fTitleText.getParent().getParent().setVisible(false); return; } if (R4EUIModelController.isJobInProgress() || fProperties.getElement().isReadOnly() || null == R4EUIModelController.getActiveReview() || ((R4EReviewState) R4EUIModelController.getActiveReview().getReview().getState()).getState().equals( R4EReviewPhase.R4E_REVIEW_PHASE_COMPLETED) || !fProperties.getElement().isEnabled()) { fTitleText.setForeground(UIUtils.DISABLED_FONT_COLOR); fTitleText.setEditable(false); fAuthorText.setForeground(UIUtils.DISABLED_FONT_COLOR); fCreationDateText.setForeground(UIUtils.DISABLED_FONT_COLOR); fPositionText.setForeground(UIUtils.DISABLED_FONT_COLOR); fDescriptionText.setForeground(UIUtils.DISABLED_FONT_COLOR); fStateCombo.setEnabled(false); fClassCombo.setEnabled(false); fRankCombo.setEnabled(false); fDateText.setForeground(UIUtils.DISABLED_FONT_COLOR); fCalendarButton.setEnabled(false); fDecidedByCombo.setEnabled(false); fFixedByCombo.setEnabled(false); fFollowUpByCombo.setEnabled(false); fRuleButton.setEnabled(false); fRuleId.setForeground(UIUtils.DISABLED_FONT_COLOR); fAssignedToCombo.setEnabled(false); if (fProperties.getElement() instanceof R4EUIAnomalyExtended) { fStateLabel.setVisible(true); fStateCombo.setVisible(true); fDecidedByLabel.setVisible(true); fDecidedByCombo.setVisible(true); fFixedByLabel.setVisible(true); fFixedByCombo.setVisible(true); fFollowUpByLabel.setVisible(true); fFollowUpByCombo.setVisible(true); } else { fStateLabel.setVisible(false); fStateCombo.setVisible(false); fDecidedByLabel.setVisible(false); fDecidedByCombo.setVisible(false); fFixedByLabel.setVisible(false); fFixedByCombo.setVisible(false); fFollowUpByLabel.setVisible(false); fFollowUpByCombo.setVisible(false); } } else { fAuthorText.setForeground(UIUtils.ENABLED_FONT_COLOR); fCreationDateText.setForeground(UIUtils.ENABLED_FONT_COLOR); fPositionText.setForeground(UIUtils.ENABLED_FONT_COLOR); fDescriptionText.setForeground(UIUtils.ENABLED_FONT_COLOR); fRuleButton.setEnabled(true); fRuleId.setForeground(UIUtils.ENABLED_FONT_COLOR); fAssignedToCombo.setEnabled(true); final R4EUIAnomalyBasic uiAnomaly = (R4EUIAnomalyBasic) fProperties.getElement(); if (uiAnomaly.isTitleEnabled()) { fTitleText.setForeground(UIUtils.ENABLED_FONT_COLOR); fTitleText.setEditable(true); } else { fTitleText.setForeground(UIUtils.DISABLED_FONT_COLOR); fTitleText.setEditable(false); } if (uiAnomaly.isDueDateEnabled()) { fDateText.setForeground(UIUtils.ENABLED_FONT_COLOR); fCalendarButton.setEnabled(true); } else { fDateText.setForeground(UIUtils.DISABLED_FONT_COLOR); fCalendarButton.setEnabled(false); } if (uiAnomaly.isClassEnabled()) { fClassCombo.setEnabled(true); } else { fClassCombo.setEnabled(false); } if (uiAnomaly.isRankEnabled()) { fRankCombo.setEnabled(true); } else { fRankCombo.setEnabled(false); } if (fProperties.getElement() instanceof R4EUIAnomalyExtended) { fStateLabel.setVisible(true); fStateCombo.setVisible(true); fStateCombo.setEnabled(true); fDecidedByLabel.setVisible(true); fDecidedByCombo.setVisible(true); if (((R4EUIAnomalyExtended) uiAnomaly).isDecidedByEnabled()) { fDecidedByCombo.setEnabled(true); } else { fDecidedByCombo.setEnabled(false); } fFixedByLabel.setVisible(true); fFixedByCombo.setVisible(true); if (((R4EUIAnomalyExtended) uiAnomaly).isFixedByEnabled()) { fFixedByCombo.setEnabled(true); } else { fFixedByCombo.setEnabled(false); } fFollowUpByLabel.setVisible(true); fFollowUpByCombo.setVisible(true); if (((R4EUIAnomalyExtended) uiAnomaly).isFollowUpByEnabled()) { fFollowUpByCombo.setEnabled(true); } else { fFollowUpByCombo.setEnabled(false); } } else { fStateLabel.setVisible(false); fStateCombo.setVisible(false); fDecidedByCombo.setEnabled(false); fFixedByCombo.setEnabled(false); fFollowUpByCombo.setEnabled(false); fDecidedByLabel.setVisible(false); fDecidedByCombo.setVisible(false); fFixedByLabel.setVisible(false); fFixedByCombo.setVisible(false); fFollowUpByLabel.setVisible(false); fFollowUpByCombo.setVisible(false); } } } }
true
true
private Composite createAnomalyDetailsSection(TabbedPropertySheetWidgetFactory aWidgetFactory, final Composite aComposite) { //Anomaly Details section final ExpandableComposite anomalyDetailsSection = aWidgetFactory.createExpandableComposite(aComposite, ExpandableComposite.TWISTIE); final FormData data = new FormData(); data.left = new FormAttachment(0, 0); data.right = new FormAttachment(100, 0); // $codepro.audit.disable numericLiterals data.top = new FormAttachment(fAssignedToCombo, ITabbedPropertyConstants.VSPACE); anomalyDetailsSection.setLayoutData(data); anomalyDetailsSection.setText(ANOMALY_DETAILS_SECTION_LABEL); anomalyDetailsSection.addExpansionListener(new ExpansionAdapter() { @Override public void expansionStateChanged(ExpansionEvent e) { final ScrolledComposite scrolledParent = (ScrolledComposite) aComposite.getParent() .getParent() .getParent() .getParent() .getParent(); scrolledParent.setMinSize(aComposite.computeSize(SWT.DEFAULT, SWT.DEFAULT)); scrolledParent.layout(true, true); } }); anomalyDetailsSection.setLayout(new GridLayout(1, false)); final Composite anomalyDetailsSectionClient = aWidgetFactory.createComposite(anomalyDetailsSection); anomalyDetailsSectionClient.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); anomalyDetailsSectionClient.setLayout(new GridLayout(4, false)); anomalyDetailsSection.setClient(anomalyDetailsSectionClient); //Anomaly Creation Date (read-only) final CLabel creationDateLabel = aWidgetFactory.createCLabel(anomalyDetailsSectionClient, R4EUIConstants.CREATION_DATE_LABEL); GridData gridData = new GridData(SWT.FILL, SWT.CENTER, false, false); gridData.horizontalSpan = 1; creationDateLabel.setToolTipText(R4EUIConstants.ANOMALY_CREATION_DATE_TOOLTIP); creationDateLabel.setLayoutData(gridData); aWidgetFactory.setBorderStyle(SWT.NULL); fCreationDateText = aWidgetFactory.createText(anomalyDetailsSectionClient, "", SWT.NULL); gridData = new GridData(SWT.FILL, SWT.CENTER, true, false); gridData.horizontalSpan = 3; fCreationDateText.setEditable(false); fCreationDateText.setToolTipText(R4EUIConstants.ANOMALY_CREATION_DATE_TOOLTIP); fCreationDateText.setLayoutData(gridData); //Anomaly position (read-only) final CLabel positionLabel = aWidgetFactory.createCLabel(anomalyDetailsSectionClient, R4EUIConstants.POSITION_LABEL); gridData = new GridData(SWT.FILL, SWT.CENTER, false, false); gridData.horizontalSpan = 1; positionLabel.setToolTipText(R4EUIConstants.ANOMALY_POSITION_TOOLTIP); positionLabel.setLayoutData(gridData); fPositionText = aWidgetFactory.createText(anomalyDetailsSectionClient, "", SWT.NULL); gridData = new GridData(SWT.FILL, SWT.CENTER, true, false); gridData.horizontalSpan = 3; fPositionText.setEditable(false); fPositionText.setToolTipText(R4EUIConstants.ANOMALY_POSITION_TOOLTIP); fPositionText.setLayoutData(gridData); //Class final CLabel classLabel = aWidgetFactory.createCLabel(anomalyDetailsSectionClient, R4EUIConstants.CLASS_LABEL); gridData = new GridData(SWT.FILL, SWT.CENTER, false, false); gridData.horizontalSpan = 1; classLabel.setToolTipText(R4EUIConstants.ANOMALY_CLASS_TOOLTIP); classLabel.setLayoutData(gridData); aWidgetFactory.setBorderStyle(SWT.BORDER); fClassCombo = aWidgetFactory.createCCombo(anomalyDetailsSectionClient, SWT.READ_ONLY); int size = UIUtils.getClasses().length; fClassCombo.setVisibleItemCount(size); gridData = new GridData(SWT.FILL, SWT.CENTER, true, false); gridData.horizontalSpan = 3; fClassCombo.setToolTipText(R4EUIConstants.ANOMALY_CLASS_TOOLTIP); fClassCombo.setLayoutData(gridData); fClassCombo.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { if (!fRefreshInProgress) { try { final String currentUser = R4EUIModelController.getReviewer(); final R4EAnomaly modelAnomaly = ((R4EUIAnomalyBasic) fProperties.getElement()).getAnomaly(); R4EDesignRuleClass newClass = UIUtils.getClassFromString(fClassCombo.getText()); R4EDesignRuleClass oldClass = null; if (null != modelAnomaly.getType()) { oldClass = ((R4ECommentType) modelAnomaly.getType()).getType(); } if (!newClass.equals(oldClass)) { final Long bookNum = R4EUIModelController.FResourceUpdater.checkOut(modelAnomaly, currentUser); final R4ECommentType type = RModelFactoryExt.eINSTANCE.createR4ECommentType(); type.setType(newClass); modelAnomaly.setType(type); R4EUIModelController.FResourceUpdater.checkIn(bookNum); } } catch (ResourceHandlingException e1) { UIUtils.displayResourceErrorDialog(e1); } catch (OutOfSyncException e1) { UIUtils.displaySyncErrorDialog(e1); } refresh(); } } }); addScrollListener(fClassCombo); //Rank final CLabel rankLabel = aWidgetFactory.createCLabel(anomalyDetailsSectionClient, R4EUIConstants.RANK_LABEL); gridData = new GridData(SWT.FILL, SWT.CENTER, false, false); gridData.horizontalSpan = 1; rankLabel.setToolTipText(R4EUIConstants.ANOMALY_RANK_TOOLTIP); rankLabel.setLayoutData(gridData); fRankCombo = aWidgetFactory.createCCombo(anomalyDetailsSectionClient, SWT.READ_ONLY); fRankCombo.setToolTipText(R4EUIConstants.ANOMALY_RANK_TOOLTIP); gridData = new GridData(SWT.FILL, SWT.CENTER, true, false); gridData.horizontalSpan = 3; fRankCombo.setLayoutData(gridData); fRankCombo.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { if (!fRefreshInProgress) { try { final String currentUser = R4EUIModelController.getReviewer(); final R4EAnomaly modelAnomaly = ((R4EUIAnomalyBasic) fProperties.getElement()).getAnomaly(); R4EDesignRuleRank newRank = UIUtils.getRankFromString(fRankCombo.getText()); R4EDesignRuleRank oldRank = modelAnomaly.getRank(); if (!newRank.equals(oldRank)) { final Long bookNum = R4EUIModelController.FResourceUpdater.checkOut(modelAnomaly, currentUser); modelAnomaly.setRank(newRank); R4EUIModelController.FResourceUpdater.checkIn(bookNum); } } catch (ResourceHandlingException e1) { UIUtils.displayResourceErrorDialog(e1); } catch (OutOfSyncException e1) { UIUtils.displaySyncErrorDialog(e1); } } refresh(); } }); addScrollListener(fRankCombo); //RuleId final CLabel ruleIdLabel = aWidgetFactory.createCLabel(anomalyDetailsSectionClient, R4EUIConstants.RULE_ID_LABEL); gridData = new GridData(SWT.FILL, SWT.CENTER, false, false); gridData.horizontalSpan = 1; ruleIdLabel.setToolTipText(R4EUIConstants.ANOMALY_RULE_ID_TOOLTIP); ruleIdLabel.setLayoutData(gridData); final Composite ruleComposite = aWidgetFactory.createComposite(anomalyDetailsSectionClient); gridData = new GridData(SWT.FILL, SWT.FILL, true, false); gridData.horizontalSpan = 3; ruleComposite.setToolTipText(R4EUIConstants.ANOMALY_RULE_ID_TOOLTIP); ruleComposite.setLayoutData(gridData); ruleComposite.setLayout(new GridLayout(2, false)); fRuleId = aWidgetFactory.createText(ruleComposite, "", SWT.NULL); fRuleId.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); fRuleId.setEditable(false); fRuleButton = aWidgetFactory.createButton(ruleComposite, R4EUIConstants.UPDATE_LABEL, SWT.NONE); fRuleButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); fRuleButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { //Modify anomaly R4EUIModelController.setJobInProgress(true); final R4EAnomaly modelAnomaly = ((R4EUIAnomalyBasic) fProperties.getElement()).getAnomaly(); final IAnomalyInputDialog dialog = R4EUIDialogFactory.getInstance().getNewAnomalyInputDialog(); dialog.create(); dialog.setTitle(modelAnomaly.getTitle()); dialog.setDescription(modelAnomaly.getDescription()); dialog.setDueDate(modelAnomaly.getDueDate()); if (modelAnomaly.getAssignedTo().size() > 0) { dialog.setAssigned(modelAnomaly.getAssignedTo().get(0)); } if (null != modelAnomaly.getType()) { dialog.setClass_(((R4ECommentType) modelAnomaly.getType()).getType()); } dialog.setRank(modelAnomaly.getRank()); dialog.setRuleID(modelAnomaly.getRuleID()); final int result = dialog.open(); if (result == Window.OK) { if (!fRefreshInProgress) { try { //Set new model data final String currentUser = R4EUIModelController.getReviewer(); final Long bookNum = R4EUIModelController.FResourceUpdater.checkOut(modelAnomaly, currentUser); modelAnomaly.setTitle(dialog.getAnomalyTitleValue()); modelAnomaly.setDescription(dialog.getAnomalyDescriptionValue()); modelAnomaly.setDueDate(dialog.getDueDate()); modelAnomaly.getAssignedTo().clear(); modelAnomaly.getAssignedTo().add(dialog.getAssigned()); if (null != dialog.getRuleReferenceValue()) { final R4EDesignRule rule = dialog.getRuleReferenceValue(); final R4ECommentType commentType = RModelFactory.eINSTANCE.createR4ECommentType(); commentType.setType(rule.getClass_()); modelAnomaly.setType(commentType); modelAnomaly.setRank(rule.getRank()); modelAnomaly.setRuleID(rule.getId()); } else { final R4ECommentType commentType = RModelFactory.eINSTANCE.createR4ECommentType(); commentType.setType(dialog.getClass_()); modelAnomaly.setType(commentType); modelAnomaly.setRank(dialog.getRank()); modelAnomaly.setRuleID(""); } R4EUIModelController.FResourceUpdater.checkIn(bookNum); //Set new UI display if (fProperties.getElement() instanceof R4EUIAnomalyExtended) { fProperties.getElement().setName( R4EUIAnomalyExtended.buildAnomalyExtName(modelAnomaly, ((R4EUIAnomalyBasic) fProperties.getElement()).getPosition())); } else { fProperties.getElement().setName( R4EUIAnomalyBasic.buildAnomalyName(modelAnomaly, ((R4EUIAnomalyBasic) fProperties.getElement()).getPosition())); } } catch (ResourceHandlingException e1) { UIUtils.displayResourceErrorDialog(e1); } catch (OutOfSyncException e1) { UIUtils.displaySyncErrorDialog(e1); } } } R4EUIModelController.setJobInProgress(false); //Enable view refresh(); } }); //Due Date final CLabel dateLabel = aWidgetFactory.createCLabel(anomalyDetailsSectionClient, R4EUIConstants.DUE_DATE_LABEL); gridData = new GridData(SWT.FILL, SWT.CENTER, false, false); gridData.horizontalSpan = 1; dateLabel.setLayoutData(gridData); final Composite dateComposite = aWidgetFactory.createComposite(anomalyDetailsSectionClient); gridData = new GridData(SWT.FILL, SWT.FILL, true, true); gridData.horizontalSpan = 3; dateComposite.setToolTipText(R4EUIConstants.ANOMALY_DUE_DATE_TOOLTIP); dateComposite.setLayoutData(gridData); dateComposite.setLayout(new GridLayout(2, false)); fDateText = aWidgetFactory.createText(dateComposite, "", SWT.NULL); fDateText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); fDateText.setEditable(false); fCalendarButton = aWidgetFactory.createButton(dateComposite, "...", SWT.NONE); fCalendarButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); fCalendarButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { final ICalendarDialog dialog = R4EUIDialogFactory.getInstance().getCalendarDialog(); final int result = dialog.open(); if (result == Window.OK) { final SimpleDateFormat dateFormat = new SimpleDateFormat(R4EUIConstants.SIMPLE_DATE_FORMAT); fDateText.setText(dateFormat.format(dialog.getDate())); if (!fRefreshInProgress) { try { final String currentUser = R4EUIModelController.getReviewer(); final R4EAnomaly modelAnomaly = ((R4EUIAnomalyBasic) fProperties.getElement()).getAnomaly(); final Long bookNum = R4EUIModelController.FResourceUpdater.checkOut(modelAnomaly, currentUser); modelAnomaly.setDueDate(dialog.getDate()); R4EUIModelController.FResourceUpdater.checkIn(bookNum); } catch (ResourceHandlingException e1) { UIUtils.displayResourceErrorDialog(e1); } catch (OutOfSyncException e1) { UIUtils.displaySyncErrorDialog(e1); } } refresh(); } } }); return anomalyDetailsSection; }
private Composite createAnomalyDetailsSection(TabbedPropertySheetWidgetFactory aWidgetFactory, final Composite aComposite) { //Anomaly Details section final ExpandableComposite anomalyDetailsSection = aWidgetFactory.createExpandableComposite(aComposite, ExpandableComposite.TWISTIE); final FormData data = new FormData(); data.left = new FormAttachment(0, 0); data.right = new FormAttachment(100, 0); // $codepro.audit.disable numericLiterals data.top = new FormAttachment(fAssignedToCombo, ITabbedPropertyConstants.VSPACE); anomalyDetailsSection.setLayoutData(data); anomalyDetailsSection.setText(ANOMALY_DETAILS_SECTION_LABEL); anomalyDetailsSection.addExpansionListener(new ExpansionAdapter() { @Override public void expansionStateChanged(ExpansionEvent e) { final ScrolledComposite scrolledParent = (ScrolledComposite) aComposite.getParent() .getParent() .getParent() .getParent() .getParent(); scrolledParent.setMinSize(aComposite.computeSize(SWT.DEFAULT, SWT.DEFAULT)); scrolledParent.layout(true, true); } }); anomalyDetailsSection.setLayout(new GridLayout(1, false)); final Composite anomalyDetailsSectionClient = aWidgetFactory.createComposite(anomalyDetailsSection); anomalyDetailsSectionClient.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); anomalyDetailsSectionClient.setLayout(new GridLayout(4, false)); anomalyDetailsSection.setClient(anomalyDetailsSectionClient); //Anomaly Creation Date (read-only) final CLabel creationDateLabel = aWidgetFactory.createCLabel(anomalyDetailsSectionClient, R4EUIConstants.CREATION_DATE_LABEL); GridData gridData = new GridData(SWT.FILL, SWT.CENTER, false, false); gridData.horizontalSpan = 1; creationDateLabel.setToolTipText(R4EUIConstants.ANOMALY_CREATION_DATE_TOOLTIP); creationDateLabel.setLayoutData(gridData); aWidgetFactory.setBorderStyle(SWT.NULL); fCreationDateText = aWidgetFactory.createText(anomalyDetailsSectionClient, "", SWT.NULL); gridData = new GridData(SWT.FILL, SWT.CENTER, true, false); gridData.horizontalSpan = 3; fCreationDateText.setEditable(false); fCreationDateText.setToolTipText(R4EUIConstants.ANOMALY_CREATION_DATE_TOOLTIP); fCreationDateText.setLayoutData(gridData); //Anomaly position (read-only) final CLabel positionLabel = aWidgetFactory.createCLabel(anomalyDetailsSectionClient, R4EUIConstants.POSITION_LABEL); gridData = new GridData(SWT.FILL, SWT.CENTER, false, false); gridData.horizontalSpan = 1; positionLabel.setToolTipText(R4EUIConstants.ANOMALY_POSITION_TOOLTIP); positionLabel.setLayoutData(gridData); fPositionText = aWidgetFactory.createText(anomalyDetailsSectionClient, "", SWT.NULL); gridData = new GridData(SWT.FILL, SWT.CENTER, true, false); gridData.horizontalSpan = 3; fPositionText.setEditable(false); fPositionText.setToolTipText(R4EUIConstants.ANOMALY_POSITION_TOOLTIP); fPositionText.setLayoutData(gridData); //Class final CLabel classLabel = aWidgetFactory.createCLabel(anomalyDetailsSectionClient, R4EUIConstants.CLASS_LABEL); gridData = new GridData(SWT.FILL, SWT.CENTER, false, false); gridData.horizontalSpan = 1; classLabel.setToolTipText(R4EUIConstants.ANOMALY_CLASS_TOOLTIP); classLabel.setLayoutData(gridData); aWidgetFactory.setBorderStyle(SWT.BORDER); fClassCombo = aWidgetFactory.createCCombo(anomalyDetailsSectionClient, SWT.READ_ONLY); int size = UIUtils.getClasses().length; fClassCombo.setVisibleItemCount(size); gridData = new GridData(SWT.FILL, SWT.CENTER, true, false); gridData.horizontalSpan = 3; fClassCombo.setToolTipText(R4EUIConstants.ANOMALY_CLASS_TOOLTIP); fClassCombo.setLayoutData(gridData); fClassCombo.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { if (!fRefreshInProgress) { try { final String currentUser = R4EUIModelController.getReviewer(); final R4EAnomaly modelAnomaly = ((R4EUIAnomalyBasic) fProperties.getElement()).getAnomaly(); R4EDesignRuleClass newClass = UIUtils.getClassFromString(fClassCombo.getText()); R4EDesignRuleClass oldClass = null; if (null != modelAnomaly.getType()) { oldClass = ((R4ECommentType) modelAnomaly.getType()).getType(); } if (!newClass.equals(oldClass)) { final Long bookNum = R4EUIModelController.FResourceUpdater.checkOut(modelAnomaly, currentUser); final R4ECommentType type = RModelFactoryExt.eINSTANCE.createR4ECommentType(); type.setType(newClass); modelAnomaly.setType(type); R4EUIModelController.FResourceUpdater.checkIn(bookNum); } } catch (ResourceHandlingException e1) { UIUtils.displayResourceErrorDialog(e1); } catch (OutOfSyncException e1) { UIUtils.displaySyncErrorDialog(e1); } refresh(); } } }); addScrollListener(fClassCombo); //Rank final CLabel rankLabel = aWidgetFactory.createCLabel(anomalyDetailsSectionClient, R4EUIConstants.RANK_LABEL); gridData = new GridData(SWT.FILL, SWT.CENTER, false, false); gridData.horizontalSpan = 1; rankLabel.setToolTipText(R4EUIConstants.ANOMALY_RANK_TOOLTIP); rankLabel.setLayoutData(gridData); fRankCombo = aWidgetFactory.createCCombo(anomalyDetailsSectionClient, SWT.READ_ONLY); fRankCombo.setToolTipText(R4EUIConstants.ANOMALY_RANK_TOOLTIP); gridData = new GridData(SWT.FILL, SWT.CENTER, true, false); gridData.horizontalSpan = 3; fRankCombo.setLayoutData(gridData); fRankCombo.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { if (!fRefreshInProgress) { try { final String currentUser = R4EUIModelController.getReviewer(); final R4EAnomaly modelAnomaly = ((R4EUIAnomalyBasic) fProperties.getElement()).getAnomaly(); R4EDesignRuleRank newRank = UIUtils.getRankFromString(fRankCombo.getText()); R4EDesignRuleRank oldRank = modelAnomaly.getRank(); if (!newRank.equals(oldRank)) { final Long bookNum = R4EUIModelController.FResourceUpdater.checkOut(modelAnomaly, currentUser); modelAnomaly.setRank(newRank); R4EUIModelController.FResourceUpdater.checkIn(bookNum); } } catch (ResourceHandlingException e1) { UIUtils.displayResourceErrorDialog(e1); } catch (OutOfSyncException e1) { UIUtils.displaySyncErrorDialog(e1); } } refresh(); } }); addScrollListener(fRankCombo); //RuleId final CLabel ruleIdLabel = aWidgetFactory.createCLabel(anomalyDetailsSectionClient, R4EUIConstants.RULE_ID_LABEL); gridData = new GridData(SWT.FILL, SWT.CENTER, false, false); gridData.horizontalSpan = 1; ruleIdLabel.setToolTipText(R4EUIConstants.ANOMALY_RULE_ID_TOOLTIP); ruleIdLabel.setLayoutData(gridData); final Composite ruleComposite = aWidgetFactory.createComposite(anomalyDetailsSectionClient); gridData = new GridData(SWT.FILL, SWT.FILL, true, false); gridData.horizontalSpan = 3; ruleComposite.setToolTipText(R4EUIConstants.ANOMALY_RULE_ID_TOOLTIP); ruleComposite.setLayoutData(gridData); ruleComposite.setLayout(new GridLayout(2, false)); fRuleId = aWidgetFactory.createText(ruleComposite, "", SWT.NULL); fRuleId.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); fRuleId.setEditable(false); fRuleButton = aWidgetFactory.createButton(ruleComposite, R4EUIConstants.UPDATE_LABEL, SWT.NONE); fRuleButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); fRuleButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { //Modify anomaly R4EUIModelController.setJobInProgress(true); final R4EAnomaly modelAnomaly = ((R4EUIAnomalyBasic) fProperties.getElement()).getAnomaly(); final IAnomalyInputDialog dialog = R4EUIDialogFactory.getInstance().getNewAnomalyInputDialog(); dialog.create(); dialog.setTitle(modelAnomaly.getTitle()); dialog.setDescription(modelAnomaly.getDescription()); dialog.setDueDate(modelAnomaly.getDueDate()); if (modelAnomaly.getAssignedTo().size() > 0) { dialog.setAssigned(modelAnomaly.getAssignedTo().get(0)); } if (null != modelAnomaly.getType()) { dialog.setClass_(((R4ECommentType) modelAnomaly.getType()).getType()); } dialog.setRank(modelAnomaly.getRank()); dialog.setRuleID(modelAnomaly.getRuleID()); final int result = dialog.open(); if (result == Window.OK) { if (!fRefreshInProgress) { try { //Set new model data final String currentUser = R4EUIModelController.getReviewer(); final Long bookNum = R4EUIModelController.FResourceUpdater.checkOut(modelAnomaly, currentUser); modelAnomaly.setTitle(dialog.getAnomalyTitleValue()); modelAnomaly.setDescription(dialog.getAnomalyDescriptionValue()); modelAnomaly.setDueDate(dialog.getDueDate()); modelAnomaly.getAssignedTo().clear(); modelAnomaly.getAssignedTo().add(dialog.getAssigned()); if (null != dialog.getRuleReferenceValue()) { final R4EDesignRule rule = dialog.getRuleReferenceValue(); final R4ECommentType commentType = RModelFactory.eINSTANCE.createR4ECommentType(); commentType.setType(rule.getClass_()); modelAnomaly.setType(commentType); modelAnomaly.setRank(rule.getRank()); modelAnomaly.setRuleID(rule.getId()); } else { final R4ECommentType commentType = RModelFactory.eINSTANCE.createR4ECommentType(); commentType.setType(dialog.getClass_()); modelAnomaly.setType(commentType); modelAnomaly.setRank(dialog.getRank()); modelAnomaly.setRuleID(""); } R4EUIModelController.FResourceUpdater.checkIn(bookNum); //Set new UI display if (fProperties.getElement() instanceof R4EUIAnomalyExtended) { fProperties.getElement().setName( R4EUIAnomalyExtended.buildAnomalyExtName(modelAnomaly, ((R4EUIAnomalyBasic) fProperties.getElement()).getPosition())); } else { fProperties.getElement().setName( R4EUIAnomalyBasic.buildAnomalyName(modelAnomaly, ((R4EUIAnomalyBasic) fProperties.getElement()).getPosition())); } } catch (ResourceHandlingException e1) { UIUtils.displayResourceErrorDialog(e1); } catch (OutOfSyncException e1) { UIUtils.displaySyncErrorDialog(e1); } } } R4EUIModelController.setJobInProgress(false); //Enable view R4EUIModelController.getNavigatorView().getTreeViewer().refresh(); refresh(); } }); //Due Date final CLabel dateLabel = aWidgetFactory.createCLabel(anomalyDetailsSectionClient, R4EUIConstants.DUE_DATE_LABEL); gridData = new GridData(SWT.FILL, SWT.CENTER, false, false); gridData.horizontalSpan = 1; dateLabel.setLayoutData(gridData); final Composite dateComposite = aWidgetFactory.createComposite(anomalyDetailsSectionClient); gridData = new GridData(SWT.FILL, SWT.FILL, true, true); gridData.horizontalSpan = 3; dateComposite.setToolTipText(R4EUIConstants.ANOMALY_DUE_DATE_TOOLTIP); dateComposite.setLayoutData(gridData); dateComposite.setLayout(new GridLayout(2, false)); fDateText = aWidgetFactory.createText(dateComposite, "", SWT.NULL); fDateText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); fDateText.setEditable(false); fCalendarButton = aWidgetFactory.createButton(dateComposite, "...", SWT.NONE); fCalendarButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); fCalendarButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { final ICalendarDialog dialog = R4EUIDialogFactory.getInstance().getCalendarDialog(); final int result = dialog.open(); if (result == Window.OK) { final SimpleDateFormat dateFormat = new SimpleDateFormat(R4EUIConstants.SIMPLE_DATE_FORMAT); fDateText.setText(dateFormat.format(dialog.getDate())); if (!fRefreshInProgress) { try { final String currentUser = R4EUIModelController.getReviewer(); final R4EAnomaly modelAnomaly = ((R4EUIAnomalyBasic) fProperties.getElement()).getAnomaly(); final Long bookNum = R4EUIModelController.FResourceUpdater.checkOut(modelAnomaly, currentUser); modelAnomaly.setDueDate(dialog.getDate()); R4EUIModelController.FResourceUpdater.checkIn(bookNum); } catch (ResourceHandlingException e1) { UIUtils.displayResourceErrorDialog(e1); } catch (OutOfSyncException e1) { UIUtils.displaySyncErrorDialog(e1); } } refresh(); } } }); return anomalyDetailsSection; }
diff --git a/src/org/opensolaris/opengrok/search/context/Context.java b/src/org/opensolaris/opengrok/search/context/Context.java index 3507afd..446c20d 100644 --- a/src/org/opensolaris/opengrok/search/context/Context.java +++ b/src/org/opensolaris/opengrok/search/context/Context.java @@ -1,278 +1,276 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * See LICENSE.txt included in this distribution for the specific * language governing permissions and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved. */ /** * This is supposed to get the matching lines from sourcefile. * since lucene does not easily give the match context. */ package org.opensolaris.opengrok.search.context; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.logging.Level; import org.apache.lucene.search.Query; import org.opensolaris.opengrok.OpenGrokLogger; import org.opensolaris.opengrok.analysis.Definitions; import org.opensolaris.opengrok.configuration.RuntimeEnvironment; import org.opensolaris.opengrok.search.Hit; import org.opensolaris.opengrok.web.Util; public class Context { private final LineMatcher[] m; static final int MAXFILEREAD = 1024 * 1024; private char[] buffer; PlainLineTokenizer tokens; String queryAsURI; /** * Map whose keys tell which fields to look for in the source file, and * whose values tell if the field is case insensitive (true for * insensitivity, false for sensitivity). */ private static final Map<String, Boolean> tokenFields = new HashMap<String, Boolean>(); static { tokenFields.put("full", true); tokenFields.put("refs", false); tokenFields.put("defs", false); } /** * Constructs a context generator * @param query the query to generate the result for * @param queryStrings map from field names to queries against the fields */ public Context(Query query, Map<String, String> queryStrings) { QueryMatchers qm = new QueryMatchers(); m = qm.getMatchers(query, tokenFields); if (m != null) { buildQueryAsURI(queryStrings); //System.err.println("Found Matchers = "+ m.length + " for " + query); buffer = new char[MAXFILEREAD]; tokens = new PlainLineTokenizer((Reader) null); } } public boolean isEmpty() { return m == null; } /** * Build the {@code queryAsURI} string that holds the query in a form * that's suitable for sending it as part of a URI. * * @param subqueries a map containing the query text for each field */ private void buildQueryAsURI(Map<String, String> subqueries) { boolean first = true; StringBuilder sb = new StringBuilder(); for (Map.Entry<String, String> entry : subqueries.entrySet()) { String field = entry.getKey(); String queryText = entry.getValue(); if (!first) { sb.append('&'); } sb.append(field).append("=").append(Util.URIEncode(queryText)); first = false; } queryAsURI = sb.toString(); } private boolean alt = true; /** * * @param in File to be matched * @param out to write the context * @param morePrefix to link to more... page * @param path path of the file * @param tags format to highlight defs. * @param limit should the number of matching lines be limited? * @return Did it get any matching context? */ public boolean getContext(Reader in, Writer out, String urlPrefix, String morePrefix, String path, Definitions tags, boolean limit, List<Hit> hits) { alt = !alt; if (m == null) { return false; } boolean anything = false; TreeMap<Integer, String[]> matchingTags = null; if (tags != null) { matchingTags = new TreeMap<Integer, String[]>(); try { for (Definitions.Tag tag : tags.getTags()) { for (int i = 0; i < m.length; i++) { - //TODO symbol.toLowerCase makes below check work for all searches and shows the proper tag, hence QueryMatchers or someone from the matchers incorrectly lowercases search for index which IS case sensitive !!! - // please fix bug 17582 if (m[i].match(tag.symbol) == LineMatcher.MATCHED) { /* * desc[1] is line number * desc[2] is type * desc[3] is matching line; */ String[] desc = { tag.symbol, Integer.toString(tag.line), tag.type, tag.text,}; if (in == null) { if (out == null) { Hit hit = new Hit(path, Util.htmlize(desc[3]).replaceAll( desc[0], "<b>" + desc[0] + "</b>"), desc[1], false, alt); hits.add(hit); anything = true; } else { out.write("<a class=\"s\" href=\""); out.write(Util.URIEncodePath(urlPrefix)); out.write(Util.URIEncodePath(path)); out.write("#"); out.write(desc[1]); out.write("\"><span class=\"l\">"); out.write(desc[1]); out.write("</span> "); out.write(Util.htmlize(desc[3]).replaceAll( desc[0], "<b>" + desc[0] + "</b>")); out.write("</a> <i> "); out.write(desc[2]); out.write(" </i><br/>"); anything = true; } } else { matchingTags.put(tag.line, desc); } break; } } } } catch (IOException e) { if (hits != null) { // @todo verify why we ignore all exceptions? OpenGrokLogger.getLogger().log(Level.WARNING, "Could not get context for " + path, e); } } } /** * Just to get the matching tag send a null in */ if (in == null) { return anything; } int charsRead = 0; boolean truncated = false; boolean lim = limit; if (!RuntimeEnvironment.getInstance().isQuickContextScan()) { lim = false; } if (lim) { try { charsRead = in.read(buffer); if (charsRead == MAXFILEREAD) { // we probably only read parts of the file, so set the // truncated flag to enable the [all...] link that // requests all matches truncated = true; // truncate to last line read (don't look more than 100 // characters back) for (int i = charsRead - 1; i > charsRead - 100; i--) { if (buffer[i] == '\n') { charsRead = i; break; } } } } catch (IOException e) { OpenGrokLogger.getLogger().log(Level.WARNING, "An error occured while reading data", e); return anything; } if (charsRead == 0) { return anything; } tokens.reInit(buffer, charsRead, out, Util.URIEncodePath(urlPrefix + path) + "#", matchingTags); } else { tokens.reInit(in, out, Util.URIEncodePath(urlPrefix + path) + "#", matchingTags); } if (hits != null) { tokens.setAlt(alt); tokens.setHitList(hits); tokens.setFilename(path); } try { String token; int matchState = LineMatcher.NOT_MATCHED; int matchedLines = 0; while ((token = tokens.yylex()) != null && (!lim || matchedLines < 10)) { for (int i = 0; i < m.length; i++) { matchState = m[i].match(token); if (matchState == LineMatcher.MATCHED) { tokens.printContext(); matchedLines++; //out.write("<br> <i>Matched " + token + " maxlines = " + matchedLines + "</i><br>"); break; } else if (matchState == LineMatcher.WAIT) { tokens.holdOn(); } else { tokens.neverMind(); } } } anything = matchedLines > 0; tokens.dumpRest(); if (lim && (truncated || matchedLines == 10) && out != null) { out.write("&nbsp; &nbsp; [<a href=\"" + Util.URIEncodePath(morePrefix + path) + "?" + queryAsURI + "\">all</a>...]"); } } catch (IOException e) { OpenGrokLogger.getLogger().log(Level.WARNING, "Could not get context for " + path, e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { OpenGrokLogger.getLogger().log(Level.WARNING, "An error occured while closing stream", e); } } if (out != null) { try { out.flush(); } catch (IOException e) { OpenGrokLogger.getLogger().log(Level.WARNING, "An error occured while flushing stream", e); } } } return anything; } }
true
true
public boolean getContext(Reader in, Writer out, String urlPrefix, String morePrefix, String path, Definitions tags, boolean limit, List<Hit> hits) { alt = !alt; if (m == null) { return false; } boolean anything = false; TreeMap<Integer, String[]> matchingTags = null; if (tags != null) { matchingTags = new TreeMap<Integer, String[]>(); try { for (Definitions.Tag tag : tags.getTags()) { for (int i = 0; i < m.length; i++) { //TODO symbol.toLowerCase makes below check work for all searches and shows the proper tag, hence QueryMatchers or someone from the matchers incorrectly lowercases search for index which IS case sensitive !!! // please fix bug 17582 if (m[i].match(tag.symbol) == LineMatcher.MATCHED) { /* * desc[1] is line number * desc[2] is type * desc[3] is matching line; */ String[] desc = { tag.symbol, Integer.toString(tag.line), tag.type, tag.text,}; if (in == null) { if (out == null) { Hit hit = new Hit(path, Util.htmlize(desc[3]).replaceAll( desc[0], "<b>" + desc[0] + "</b>"), desc[1], false, alt); hits.add(hit); anything = true; } else { out.write("<a class=\"s\" href=\""); out.write(Util.URIEncodePath(urlPrefix)); out.write(Util.URIEncodePath(path)); out.write("#"); out.write(desc[1]); out.write("\"><span class=\"l\">"); out.write(desc[1]); out.write("</span> "); out.write(Util.htmlize(desc[3]).replaceAll( desc[0], "<b>" + desc[0] + "</b>")); out.write("</a> <i> "); out.write(desc[2]); out.write(" </i><br/>"); anything = true; } } else { matchingTags.put(tag.line, desc); } break; } } } } catch (IOException e) { if (hits != null) { // @todo verify why we ignore all exceptions? OpenGrokLogger.getLogger().log(Level.WARNING, "Could not get context for " + path, e); } } } /** * Just to get the matching tag send a null in */ if (in == null) { return anything; } int charsRead = 0; boolean truncated = false; boolean lim = limit; if (!RuntimeEnvironment.getInstance().isQuickContextScan()) { lim = false; } if (lim) { try { charsRead = in.read(buffer); if (charsRead == MAXFILEREAD) { // we probably only read parts of the file, so set the // truncated flag to enable the [all...] link that // requests all matches truncated = true; // truncate to last line read (don't look more than 100 // characters back) for (int i = charsRead - 1; i > charsRead - 100; i--) { if (buffer[i] == '\n') { charsRead = i; break; } } } } catch (IOException e) { OpenGrokLogger.getLogger().log(Level.WARNING, "An error occured while reading data", e); return anything; } if (charsRead == 0) { return anything; } tokens.reInit(buffer, charsRead, out, Util.URIEncodePath(urlPrefix + path) + "#", matchingTags); } else { tokens.reInit(in, out, Util.URIEncodePath(urlPrefix + path) + "#", matchingTags); } if (hits != null) { tokens.setAlt(alt); tokens.setHitList(hits); tokens.setFilename(path); } try { String token; int matchState = LineMatcher.NOT_MATCHED; int matchedLines = 0; while ((token = tokens.yylex()) != null && (!lim || matchedLines < 10)) { for (int i = 0; i < m.length; i++) { matchState = m[i].match(token); if (matchState == LineMatcher.MATCHED) { tokens.printContext(); matchedLines++; //out.write("<br> <i>Matched " + token + " maxlines = " + matchedLines + "</i><br>"); break; } else if (matchState == LineMatcher.WAIT) { tokens.holdOn(); } else { tokens.neverMind(); } } } anything = matchedLines > 0; tokens.dumpRest(); if (lim && (truncated || matchedLines == 10) && out != null) { out.write("&nbsp; &nbsp; [<a href=\"" + Util.URIEncodePath(morePrefix + path) + "?" + queryAsURI + "\">all</a>...]"); } } catch (IOException e) { OpenGrokLogger.getLogger().log(Level.WARNING, "Could not get context for " + path, e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { OpenGrokLogger.getLogger().log(Level.WARNING, "An error occured while closing stream", e); } } if (out != null) { try { out.flush(); } catch (IOException e) { OpenGrokLogger.getLogger().log(Level.WARNING, "An error occured while flushing stream", e); } } } return anything; }
public boolean getContext(Reader in, Writer out, String urlPrefix, String morePrefix, String path, Definitions tags, boolean limit, List<Hit> hits) { alt = !alt; if (m == null) { return false; } boolean anything = false; TreeMap<Integer, String[]> matchingTags = null; if (tags != null) { matchingTags = new TreeMap<Integer, String[]>(); try { for (Definitions.Tag tag : tags.getTags()) { for (int i = 0; i < m.length; i++) { if (m[i].match(tag.symbol) == LineMatcher.MATCHED) { /* * desc[1] is line number * desc[2] is type * desc[3] is matching line; */ String[] desc = { tag.symbol, Integer.toString(tag.line), tag.type, tag.text,}; if (in == null) { if (out == null) { Hit hit = new Hit(path, Util.htmlize(desc[3]).replaceAll( desc[0], "<b>" + desc[0] + "</b>"), desc[1], false, alt); hits.add(hit); anything = true; } else { out.write("<a class=\"s\" href=\""); out.write(Util.URIEncodePath(urlPrefix)); out.write(Util.URIEncodePath(path)); out.write("#"); out.write(desc[1]); out.write("\"><span class=\"l\">"); out.write(desc[1]); out.write("</span> "); out.write(Util.htmlize(desc[3]).replaceAll( desc[0], "<b>" + desc[0] + "</b>")); out.write("</a> <i> "); out.write(desc[2]); out.write(" </i><br/>"); anything = true; } } else { matchingTags.put(tag.line, desc); } break; } } } } catch (IOException e) { if (hits != null) { // @todo verify why we ignore all exceptions? OpenGrokLogger.getLogger().log(Level.WARNING, "Could not get context for " + path, e); } } } /** * Just to get the matching tag send a null in */ if (in == null) { return anything; } int charsRead = 0; boolean truncated = false; boolean lim = limit; if (!RuntimeEnvironment.getInstance().isQuickContextScan()) { lim = false; } if (lim) { try { charsRead = in.read(buffer); if (charsRead == MAXFILEREAD) { // we probably only read parts of the file, so set the // truncated flag to enable the [all...] link that // requests all matches truncated = true; // truncate to last line read (don't look more than 100 // characters back) for (int i = charsRead - 1; i > charsRead - 100; i--) { if (buffer[i] == '\n') { charsRead = i; break; } } } } catch (IOException e) { OpenGrokLogger.getLogger().log(Level.WARNING, "An error occured while reading data", e); return anything; } if (charsRead == 0) { return anything; } tokens.reInit(buffer, charsRead, out, Util.URIEncodePath(urlPrefix + path) + "#", matchingTags); } else { tokens.reInit(in, out, Util.URIEncodePath(urlPrefix + path) + "#", matchingTags); } if (hits != null) { tokens.setAlt(alt); tokens.setHitList(hits); tokens.setFilename(path); } try { String token; int matchState = LineMatcher.NOT_MATCHED; int matchedLines = 0; while ((token = tokens.yylex()) != null && (!lim || matchedLines < 10)) { for (int i = 0; i < m.length; i++) { matchState = m[i].match(token); if (matchState == LineMatcher.MATCHED) { tokens.printContext(); matchedLines++; //out.write("<br> <i>Matched " + token + " maxlines = " + matchedLines + "</i><br>"); break; } else if (matchState == LineMatcher.WAIT) { tokens.holdOn(); } else { tokens.neverMind(); } } } anything = matchedLines > 0; tokens.dumpRest(); if (lim && (truncated || matchedLines == 10) && out != null) { out.write("&nbsp; &nbsp; [<a href=\"" + Util.URIEncodePath(morePrefix + path) + "?" + queryAsURI + "\">all</a>...]"); } } catch (IOException e) { OpenGrokLogger.getLogger().log(Level.WARNING, "Could not get context for " + path, e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { OpenGrokLogger.getLogger().log(Level.WARNING, "An error occured while closing stream", e); } } if (out != null) { try { out.flush(); } catch (IOException e) { OpenGrokLogger.getLogger().log(Level.WARNING, "An error occured while flushing stream", e); } } } return anything; }
diff --git a/src/com/xforj/productions/Program.java b/src/com/xforj/productions/Program.java index ce7fa43..54272a9 100644 --- a/src/com/xforj/productions/Program.java +++ b/src/com/xforj/productions/Program.java @@ -1,144 +1,144 @@ /* * Copyright 2012 Joseph Spencer * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.xforj.productions; import com.xforj.*; /** * * @author Joseph Spencer */ public class Program extends Production { Output programNamespaceOutput; Output importOutput; Output variableOutput; Output globalStatementsOutput; /** * Program is the entry point for all productions in the grammar. When importing * another file, Program is nested within other programs. * @param output * @param currentVariableOutput * @param previousContext May be null; */ public Program( Output output, VariableOutput currentVariableOutput, ProductionContext context, boolean isNested ){ super(output); programNamespaceOutput=new Output(); importOutput=new Output(); variableOutput=currentVariableOutput; globalStatementsOutput=new Output(); JSParameters globalParams = context.getParams(); JSParametersWrapper globalParamNames = context.getJSParametersWrapper(); output. prepend( "(function(").prepend(globalParamNames).prepend("){"). prepend(programNamespaceOutput). prepend(importOutput). prepend("(function(").prepend(globalParamNames).prepend("){"). prepend(variableOutput). prepend(globalStatementsOutput). prepend("})(").prepend(globalParamNames).prepend(");"); if(isNested){ output.prepend("})(").prepend(globalParamNames).prepend(");"); } else { if(!context.assignTemplatesGlobally){ output.prepend("return "+js_TemplateBasket); } output. prepend("})("). prepend(context.getArgumentsWrapper()). prepend(");"); globalParams.put(js_StringBuffer, //StringBuffer "function(){"+ "var r=[],i=0,t='number string boolean',f="+ "function(s){"+ "var y,v;"+ "try{"+ "v=s();"+ "}catch(e){"+ "v=s;"+ "}"+ "y=typeof(v);"+ "r[i++]=(t.indexOf(y)>-1)?v:''"+ "};"+ "f.s=function(){"+ "return r.join('')"+ "};"+ "return f"+ "}" ).put( js_TemplateBasket, ( context.assignTemplatesGlobally? "(function(){return this})()": "{}" ) ).put(js_SafeValue, - "function(val){try{return val()}catch(e){return val}}" + "function(v){try{return v()}catch(e){return typeof(v)==='function'?void(0):v}}" ); } } private boolean hasProgramNamespace; private boolean hasGlobalVariableDeclarations; @Override public void execute(CharWrapper characters, ProductionContext context) throws Exception { String exception = "The first Production must be a ProgramNamespace."; if(characters.charAt(0) == '{' && !hasProgramNamespace){ hasProgramNamespace=true; context.addProduction(new ProgramNamespace(programNamespaceOutput)); return; } else if(hasProgramNamespace){ characters.removeSpace(); if(characters.charAt(0) == '{'){ if(characters.charAt(1) == 'i'){ if(!hasGlobalVariableDeclarations){ Output importStatementsOutput = new Output(); importOutput. prepend(importStatementsOutput); context.addProduction(new ImportStatements(importStatementsOutput)); return; } else { throw new Exception("ImportStatements must appear before GlobalVariableStatements."); } } else if(characters.charAt(1) == 'v'){ hasGlobalVariableDeclarations=true; context.addProduction(new GlobalVariableDeclarations(variableOutput)); return; } context.addProduction(new GlobalStatements(globalStatementsOutput)); return; } } throw new Exception(exception); } @Override public void close(ProductionContext context) throws Exception { if(!hasProgramNamespace){ context.handleFileError("No ProgramNamespace was declared in: "); } } }
true
true
public Program( Output output, VariableOutput currentVariableOutput, ProductionContext context, boolean isNested ){ super(output); programNamespaceOutput=new Output(); importOutput=new Output(); variableOutput=currentVariableOutput; globalStatementsOutput=new Output(); JSParameters globalParams = context.getParams(); JSParametersWrapper globalParamNames = context.getJSParametersWrapper(); output. prepend( "(function(").prepend(globalParamNames).prepend("){"). prepend(programNamespaceOutput). prepend(importOutput). prepend("(function(").prepend(globalParamNames).prepend("){"). prepend(variableOutput). prepend(globalStatementsOutput). prepend("})(").prepend(globalParamNames).prepend(");"); if(isNested){ output.prepend("})(").prepend(globalParamNames).prepend(");"); } else { if(!context.assignTemplatesGlobally){ output.prepend("return "+js_TemplateBasket); } output. prepend("})("). prepend(context.getArgumentsWrapper()). prepend(");"); globalParams.put(js_StringBuffer, //StringBuffer "function(){"+ "var r=[],i=0,t='number string boolean',f="+ "function(s){"+ "var y,v;"+ "try{"+ "v=s();"+ "}catch(e){"+ "v=s;"+ "}"+ "y=typeof(v);"+ "r[i++]=(t.indexOf(y)>-1)?v:''"+ "};"+ "f.s=function(){"+ "return r.join('')"+ "};"+ "return f"+ "}" ).put( js_TemplateBasket, ( context.assignTemplatesGlobally? "(function(){return this})()": "{}" ) ).put(js_SafeValue, "function(val){try{return val()}catch(e){return val}}" ); } }
public Program( Output output, VariableOutput currentVariableOutput, ProductionContext context, boolean isNested ){ super(output); programNamespaceOutput=new Output(); importOutput=new Output(); variableOutput=currentVariableOutput; globalStatementsOutput=new Output(); JSParameters globalParams = context.getParams(); JSParametersWrapper globalParamNames = context.getJSParametersWrapper(); output. prepend( "(function(").prepend(globalParamNames).prepend("){"). prepend(programNamespaceOutput). prepend(importOutput). prepend("(function(").prepend(globalParamNames).prepend("){"). prepend(variableOutput). prepend(globalStatementsOutput). prepend("})(").prepend(globalParamNames).prepend(");"); if(isNested){ output.prepend("})(").prepend(globalParamNames).prepend(");"); } else { if(!context.assignTemplatesGlobally){ output.prepend("return "+js_TemplateBasket); } output. prepend("})("). prepend(context.getArgumentsWrapper()). prepend(");"); globalParams.put(js_StringBuffer, //StringBuffer "function(){"+ "var r=[],i=0,t='number string boolean',f="+ "function(s){"+ "var y,v;"+ "try{"+ "v=s();"+ "}catch(e){"+ "v=s;"+ "}"+ "y=typeof(v);"+ "r[i++]=(t.indexOf(y)>-1)?v:''"+ "};"+ "f.s=function(){"+ "return r.join('')"+ "};"+ "return f"+ "}" ).put( js_TemplateBasket, ( context.assignTemplatesGlobally? "(function(){return this})()": "{}" ) ).put(js_SafeValue, "function(v){try{return v()}catch(e){return typeof(v)==='function'?void(0):v}}" ); } }
diff --git a/src/sta/andswtch/extensionLead/AutoRefresh.java b/src/sta/andswtch/extensionLead/AutoRefresh.java index 0ad1011..5af3133 100644 --- a/src/sta/andswtch/extensionLead/AutoRefresh.java +++ b/src/sta/andswtch/extensionLead/AutoRefresh.java @@ -1,47 +1,47 @@ package sta.andswtch.extensionLead; public class AutoRefresh implements Runnable { private ExtensionLead extLead; private boolean isRunning = false; private Thread thread; AutoRefresh(ExtensionLead extLead) { this.extLead = extLead; } public boolean isAutoRefreshRunning() { return this.isRunning; } public void startAutoRefresh() { if(this.thread == null) this.thread = new Thread(this); if(!this.thread.isAlive()) if(!this.isRunning) this.thread.start(); } public void stopAutoRefresh() { this.isRunning = false; } @Override public void run() { this.isRunning = true; while(this.isRunning) { int seconds = this.extLead.getUpdateInterval(); try { Thread.sleep(seconds * 1000); } catch (InterruptedException e) { e.printStackTrace(); } - if(seconds != 0) { + if(seconds != 0 && this.isRunning) { this.extLead.sendUpdateMessage(); } } this.thread = null; } }
true
true
public void run() { this.isRunning = true; while(this.isRunning) { int seconds = this.extLead.getUpdateInterval(); try { Thread.sleep(seconds * 1000); } catch (InterruptedException e) { e.printStackTrace(); } if(seconds != 0) { this.extLead.sendUpdateMessage(); } } this.thread = null; }
public void run() { this.isRunning = true; while(this.isRunning) { int seconds = this.extLead.getUpdateInterval(); try { Thread.sleep(seconds * 1000); } catch (InterruptedException e) { e.printStackTrace(); } if(seconds != 0 && this.isRunning) { this.extLead.sendUpdateMessage(); } } this.thread = null; }
diff --git a/app/src/uk/co/jarofgreen/cityoutdoors/API/FeaturesCall.java b/app/src/uk/co/jarofgreen/cityoutdoors/API/FeaturesCall.java index 4372faa..656943c 100644 --- a/app/src/uk/co/jarofgreen/cityoutdoors/API/FeaturesCall.java +++ b/app/src/uk/co/jarofgreen/cityoutdoors/API/FeaturesCall.java @@ -1,71 +1,72 @@ package uk.co.jarofgreen.cityoutdoors.API; import org.xml.sax.Attributes; import uk.co.jarofgreen.cityoutdoors.Storage; import uk.co.jarofgreen.cityoutdoors.Model.Feature; import android.content.Context; import android.sax.Element; import android.sax.EndElementListener; import android.sax.RootElement; import android.sax.StartElementListener; /** * * @author James Baster <[email protected]> * @copyright City of Edinburgh Council & James Baster * @license Open Source under the 3-clause BSD License * @url https://github.com/City-Outdoors/City-Outdoors-Android */ public class FeaturesCall extends BaseCall { public FeaturesCall(Context context) { super(context); } Feature lastFeature; public void execute() { RootElement root = new RootElement("data"); Element features = root.getChild("features"); Element feature = features.getChild("feature"); final Storage storage = new Storage(context); feature.setStartElementListener(new StartElementListener(){ public void start(Attributes attributes) { lastFeature = new Feature(); lastFeature.setDeleted(attributes.getValue("deleted")); lastFeature.setId(attributes.getValue("id")); lastFeature.setLat(attributes.getValue("lat")); lastFeature.setLng(attributes.getValue("lng")); + lastFeature.setTitle(attributes.getValue("title")); lastFeature.setAnsweredAllQuestions(attributes.getValue("answeredAllQuestions")); } }); feature.setEndElementListener(new EndElementListener() { public void end() { storage.storeFeature(lastFeature); } }); Element item = feature.getChild("items").getChild("item"); item.setStartElementListener(new StartElementListener(){ public void start(Attributes attributes) { lastFeature.setCollectionID((int)Integer.parseInt(attributes.getValue("collectionID"))); } }); setUpCall("/api/v1/features.php?showLinks=0&"); makeCall(root); } }
true
true
public void execute() { RootElement root = new RootElement("data"); Element features = root.getChild("features"); Element feature = features.getChild("feature"); final Storage storage = new Storage(context); feature.setStartElementListener(new StartElementListener(){ public void start(Attributes attributes) { lastFeature = new Feature(); lastFeature.setDeleted(attributes.getValue("deleted")); lastFeature.setId(attributes.getValue("id")); lastFeature.setLat(attributes.getValue("lat")); lastFeature.setLng(attributes.getValue("lng")); lastFeature.setAnsweredAllQuestions(attributes.getValue("answeredAllQuestions")); } }); feature.setEndElementListener(new EndElementListener() { public void end() { storage.storeFeature(lastFeature); } }); Element item = feature.getChild("items").getChild("item"); item.setStartElementListener(new StartElementListener(){ public void start(Attributes attributes) { lastFeature.setCollectionID((int)Integer.parseInt(attributes.getValue("collectionID"))); } }); setUpCall("/api/v1/features.php?showLinks=0&"); makeCall(root); }
public void execute() { RootElement root = new RootElement("data"); Element features = root.getChild("features"); Element feature = features.getChild("feature"); final Storage storage = new Storage(context); feature.setStartElementListener(new StartElementListener(){ public void start(Attributes attributes) { lastFeature = new Feature(); lastFeature.setDeleted(attributes.getValue("deleted")); lastFeature.setId(attributes.getValue("id")); lastFeature.setLat(attributes.getValue("lat")); lastFeature.setLng(attributes.getValue("lng")); lastFeature.setTitle(attributes.getValue("title")); lastFeature.setAnsweredAllQuestions(attributes.getValue("answeredAllQuestions")); } }); feature.setEndElementListener(new EndElementListener() { public void end() { storage.storeFeature(lastFeature); } }); Element item = feature.getChild("items").getChild("item"); item.setStartElementListener(new StartElementListener(){ public void start(Attributes attributes) { lastFeature.setCollectionID((int)Integer.parseInt(attributes.getValue("collectionID"))); } }); setUpCall("/api/v1/features.php?showLinks=0&"); makeCall(root); }
diff --git a/src/main/java/me/tehbeard/BeardAch/BeardAch.java b/src/main/java/me/tehbeard/BeardAch/BeardAch.java index dd33163..a249fb1 100644 --- a/src/main/java/me/tehbeard/BeardAch/BeardAch.java +++ b/src/main/java/me/tehbeard/BeardAch/BeardAch.java @@ -1,290 +1,290 @@ package me.tehbeard.BeardAch; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import me.tehbeard.BeardAch.achievement.*; import me.tehbeard.BeardAch.achievement.rewards.IReward; import me.tehbeard.BeardAch.achievement.triggers.*; import me.tehbeard.BeardAch.achievement.rewards.*; import me.tehbeard.BeardAch.commands.*; import me.tehbeard.BeardAch.dataSource.*; import me.tehbeard.BeardAch.dataSource.configurable.IConfigurable; import me.tehbeard.BeardAch.listener.BeardAchPlayerListener; import me.tehbeard.BeardStat.BeardStat; import me.tehbeard.BeardStat.containers.PlayerStatManager; import me.tehbeard.utils.addons.AddonLoader; import me.tehbeard.utils.factory.ConfigurableFactory; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.*; import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.event.Listener; import org.bukkit.permissions.Permissible; import org.bukkit.plugin.java.JavaPlugin; import de.hydrox.bukkit.DroxPerms.DroxPerms; import de.hydrox.bukkit.DroxPerms.DroxPermsAPI; public class BeardAch extends JavaPlugin { public static BeardAch self; private PlayerStatManager stats = null; private AchievementManager achievementManager; private AddonLoader<IConfigurable> addonLoader; public PlayerStatManager getStats(){ return stats; } public static DroxPermsAPI droxAPI = null; private static final String PERM_PREFIX = "ach"; public static boolean hasPermission(Permissible player,String node){ return (player.hasPermission(PERM_PREFIX + "." + node) || player.isOp()); } public static void printCon(String line){ System.out.println("[BeardAch] " + line); } public static void printDebugCon(String line){ if(self.getConfig().getBoolean("general.debug")){ System.out.println("[BeardAch][DEBUG] " + line); } } public void onDisable() { achievementManager.database.flush(); } private void EnableBeardStat(){ BeardStat bs = (BeardStat) Bukkit.getServer().getPluginManager().getPlugin("BeardStat"); if(bs!=null && bs.isEnabled()){ stats = bs.getStatManager(); } } @SuppressWarnings("unchecked") public void onEnable() { self = this; achievementManager = new AchievementManager(); //Load config printCon("Starting BeardAch"); if(!getConfig().getKeys(false).contains("achievements")){ getConfig().options().copyDefaults(true); } saveConfig(); reloadConfig(); updateConfig(); reloadConfig(); EnableBeardStat(); //check DroxPerms DroxPerms droxPerms = ((DroxPerms) this.getServer().getPluginManager().getPlugin("DroxPerms")); if (droxPerms != null) { droxAPI = droxPerms.getAPI(); } //setup events Listener pl = new BeardAchPlayerListener(); getServer().getPluginManager().registerEvents(pl, this); - printCon("Loading data Adapters"); + printCon("Loading Data Adapters"); ConfigurableFactory<IDataSource,DataSourceDescriptor> dataSourceFactory = new ConfigurableFactory<IDataSource, DataSourceDescriptor>(DataSourceDescriptor.class) { @Override public String getTag(DataSourceDescriptor annotation) { return annotation.tag(); } }; /* if(getConfig().getString("ach.database.type","").equalsIgnoreCase("mysql")){ achievementManager.database = new SqlDataSource(); } if(getConfig().getString("ach.database.type","").equalsIgnoreCase("null")){ achievementManager.database = new NullDataSource(); } if(getConfig().getString("ach.database.type","").equalsIgnoreCase("file")){ achievementManager.database = new YamlDataSource(); }*/ achievementManager.database = dataSourceFactory.getProduct(getConfig().getString("ach.database.type","")); if(achievementManager.database == null){ printCon("!!NO SUITABLE DATABASE SELECTED!!"); printCon("!!DISABLING PLUGIN!!"); //onDisable(); setEnabled(false); return; } printCon("Installing default triggers"); //Load installed triggers addTrigger(AchCheckTrigger.class); addTrigger(CuboidCheckTrigger.class); addTrigger(LockedTrigger.class); addTrigger(NoAchCheckTrigger.class); addTrigger(PermCheckTrigger.class); addTrigger(StatCheckTrigger.class); addTrigger(StatWithinTrigger.class); addTrigger(EconomyTrigger.class); printCon("Installing default rewards"); //load installed rewards addReward(CommandReward.class); addReward(CounterReward.class); addReward(DroxSubGroupReward.class); addReward(DroxTrackReward.class); addReward(EconomyReward.class); printCon("Preparing to load addons"); //Create addon dir if it doesn't exist File addonDir = (new File(getDataFolder(),"addons")); if(!addonDir.exists()){ addonDir.mkdir(); } //create the addon loader addonLoader = new AddonLoader<IConfigurable>(addonDir, IConfigurable.class){ @Override public List<String> getClassList(ZipFile addon) { List<String> classList = new ArrayList<String>(); try { ZipEntry manifest = addon.getEntry("achaddon.yml"); if (manifest != null) { YamlConfiguration addonConfig = new YamlConfiguration(); addonConfig.load(addon.getInputStream(manifest)); BeardAch.printCon("Loading addon " + addonConfig.getString("name","N/A")); for(String className:addonConfig.getStringList("classes")){ classList.add(className); } } } catch (IOException e) { printCon("[ERROR] An I/O error occured while trying to access an addon. " + addon.getName()); if(self.getConfig().getBoolean("general.debug")){ e.printStackTrace(); } } catch (InvalidConfigurationException e) { printCon("[ERROR] Configuration header for "+ addon.getName() + " appears to be corrupt"); if(self.getConfig().getBoolean("general.debug")){ e.printStackTrace(); } } return classList; } @Override public void makeClass(Class<? extends IConfigurable> classType) { if(classType!=null){ if(ITrigger.class.isAssignableFrom(classType)){ addTrigger((Class<? extends ITrigger>) classType); }else if(IReward.class.isAssignableFrom(classType)){ addReward((Class<? extends IReward>) classType); } } } }; printCon("Loading addons"); addonLoader.loadAddons(); printCon("Loading Achievements"); achievementManager.loadAchievements(); printCon("Starting achievement checker"); getServer().getScheduler().scheduleSyncRepeatingTask(this, new Runnable(){ public void run() { achievementManager.checkPlayers(); } }, 600L,600L); printCon("Loading commands"); //commands getCommand("ach-reload").setExecutor(new AchReloadCommand()); getCommand("ach").setExecutor(new AchCommand()); getCommand("ach-fancy").setExecutor(new AchFancyCommand()); printCon("Loaded Version:" + getDescription().getVersion()); } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { sender.sendMessage("COMMAND NOT IMPLEMENTED"); return true; } private void updateConfig(){ File f = new File(getDataFolder(),"BeardAch.yml"); if(f.exists()){ try { YamlConfiguration.loadConfiguration(f).save(new File(getDataFolder(),"config.yml")); f.renameTo(new File(getDataFolder(),"BeardAch.yml.old")); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public void addTrigger(Class<? extends ITrigger > trigger){ AbstractDataSource.triggerFactory.addProduct(trigger); } public void addReward(Class<? extends IReward > reward){ AbstractDataSource.rewardFactory.addProduct(reward); } /** * return the achievement manager * @return */ public AchievementManager getAchievementManager(){ return achievementManager; } /** * Colorises strings containing &0-f * @param msg * @return */ public static String colorise(String msg){ for(int i = 0;i<=9;i++){ msg = msg.replaceAll("&" + i, ChatColor.getByChar(""+i).toString()); } for(char i = 'a';i<='f';i++){ msg = msg.replaceAll("&" + i, ChatColor.getByChar(i).toString()); } return msg; } }
true
true
public void onEnable() { self = this; achievementManager = new AchievementManager(); //Load config printCon("Starting BeardAch"); if(!getConfig().getKeys(false).contains("achievements")){ getConfig().options().copyDefaults(true); } saveConfig(); reloadConfig(); updateConfig(); reloadConfig(); EnableBeardStat(); //check DroxPerms DroxPerms droxPerms = ((DroxPerms) this.getServer().getPluginManager().getPlugin("DroxPerms")); if (droxPerms != null) { droxAPI = droxPerms.getAPI(); } //setup events Listener pl = new BeardAchPlayerListener(); getServer().getPluginManager().registerEvents(pl, this); printCon("Loading data Adapters"); ConfigurableFactory<IDataSource,DataSourceDescriptor> dataSourceFactory = new ConfigurableFactory<IDataSource, DataSourceDescriptor>(DataSourceDescriptor.class) { @Override public String getTag(DataSourceDescriptor annotation) { return annotation.tag(); } }; /* if(getConfig().getString("ach.database.type","").equalsIgnoreCase("mysql")){ achievementManager.database = new SqlDataSource(); } if(getConfig().getString("ach.database.type","").equalsIgnoreCase("null")){ achievementManager.database = new NullDataSource(); } if(getConfig().getString("ach.database.type","").equalsIgnoreCase("file")){ achievementManager.database = new YamlDataSource(); }*/ achievementManager.database = dataSourceFactory.getProduct(getConfig().getString("ach.database.type","")); if(achievementManager.database == null){ printCon("!!NO SUITABLE DATABASE SELECTED!!"); printCon("!!DISABLING PLUGIN!!"); //onDisable(); setEnabled(false); return; } printCon("Installing default triggers"); //Load installed triggers addTrigger(AchCheckTrigger.class); addTrigger(CuboidCheckTrigger.class); addTrigger(LockedTrigger.class); addTrigger(NoAchCheckTrigger.class); addTrigger(PermCheckTrigger.class); addTrigger(StatCheckTrigger.class); addTrigger(StatWithinTrigger.class); addTrigger(EconomyTrigger.class); printCon("Installing default rewards"); //load installed rewards addReward(CommandReward.class); addReward(CounterReward.class); addReward(DroxSubGroupReward.class); addReward(DroxTrackReward.class); addReward(EconomyReward.class); printCon("Preparing to load addons"); //Create addon dir if it doesn't exist File addonDir = (new File(getDataFolder(),"addons")); if(!addonDir.exists()){ addonDir.mkdir(); } //create the addon loader addonLoader = new AddonLoader<IConfigurable>(addonDir, IConfigurable.class){ @Override public List<String> getClassList(ZipFile addon) { List<String> classList = new ArrayList<String>(); try { ZipEntry manifest = addon.getEntry("achaddon.yml"); if (manifest != null) { YamlConfiguration addonConfig = new YamlConfiguration(); addonConfig.load(addon.getInputStream(manifest)); BeardAch.printCon("Loading addon " + addonConfig.getString("name","N/A")); for(String className:addonConfig.getStringList("classes")){ classList.add(className); } } } catch (IOException e) { printCon("[ERROR] An I/O error occured while trying to access an addon. " + addon.getName()); if(self.getConfig().getBoolean("general.debug")){ e.printStackTrace(); } } catch (InvalidConfigurationException e) { printCon("[ERROR] Configuration header for "+ addon.getName() + " appears to be corrupt"); if(self.getConfig().getBoolean("general.debug")){ e.printStackTrace(); } } return classList; } @Override public void makeClass(Class<? extends IConfigurable> classType) { if(classType!=null){ if(ITrigger.class.isAssignableFrom(classType)){ addTrigger((Class<? extends ITrigger>) classType); }else if(IReward.class.isAssignableFrom(classType)){ addReward((Class<? extends IReward>) classType); } } } }; printCon("Loading addons"); addonLoader.loadAddons(); printCon("Loading Achievements"); achievementManager.loadAchievements(); printCon("Starting achievement checker"); getServer().getScheduler().scheduleSyncRepeatingTask(this, new Runnable(){ public void run() { achievementManager.checkPlayers(); } }, 600L,600L); printCon("Loading commands"); //commands getCommand("ach-reload").setExecutor(new AchReloadCommand()); getCommand("ach").setExecutor(new AchCommand()); getCommand("ach-fancy").setExecutor(new AchFancyCommand()); printCon("Loaded Version:" + getDescription().getVersion()); }
public void onEnable() { self = this; achievementManager = new AchievementManager(); //Load config printCon("Starting BeardAch"); if(!getConfig().getKeys(false).contains("achievements")){ getConfig().options().copyDefaults(true); } saveConfig(); reloadConfig(); updateConfig(); reloadConfig(); EnableBeardStat(); //check DroxPerms DroxPerms droxPerms = ((DroxPerms) this.getServer().getPluginManager().getPlugin("DroxPerms")); if (droxPerms != null) { droxAPI = droxPerms.getAPI(); } //setup events Listener pl = new BeardAchPlayerListener(); getServer().getPluginManager().registerEvents(pl, this); printCon("Loading Data Adapters"); ConfigurableFactory<IDataSource,DataSourceDescriptor> dataSourceFactory = new ConfigurableFactory<IDataSource, DataSourceDescriptor>(DataSourceDescriptor.class) { @Override public String getTag(DataSourceDescriptor annotation) { return annotation.tag(); } }; /* if(getConfig().getString("ach.database.type","").equalsIgnoreCase("mysql")){ achievementManager.database = new SqlDataSource(); } if(getConfig().getString("ach.database.type","").equalsIgnoreCase("null")){ achievementManager.database = new NullDataSource(); } if(getConfig().getString("ach.database.type","").equalsIgnoreCase("file")){ achievementManager.database = new YamlDataSource(); }*/ achievementManager.database = dataSourceFactory.getProduct(getConfig().getString("ach.database.type","")); if(achievementManager.database == null){ printCon("!!NO SUITABLE DATABASE SELECTED!!"); printCon("!!DISABLING PLUGIN!!"); //onDisable(); setEnabled(false); return; } printCon("Installing default triggers"); //Load installed triggers addTrigger(AchCheckTrigger.class); addTrigger(CuboidCheckTrigger.class); addTrigger(LockedTrigger.class); addTrigger(NoAchCheckTrigger.class); addTrigger(PermCheckTrigger.class); addTrigger(StatCheckTrigger.class); addTrigger(StatWithinTrigger.class); addTrigger(EconomyTrigger.class); printCon("Installing default rewards"); //load installed rewards addReward(CommandReward.class); addReward(CounterReward.class); addReward(DroxSubGroupReward.class); addReward(DroxTrackReward.class); addReward(EconomyReward.class); printCon("Preparing to load addons"); //Create addon dir if it doesn't exist File addonDir = (new File(getDataFolder(),"addons")); if(!addonDir.exists()){ addonDir.mkdir(); } //create the addon loader addonLoader = new AddonLoader<IConfigurable>(addonDir, IConfigurable.class){ @Override public List<String> getClassList(ZipFile addon) { List<String> classList = new ArrayList<String>(); try { ZipEntry manifest = addon.getEntry("achaddon.yml"); if (manifest != null) { YamlConfiguration addonConfig = new YamlConfiguration(); addonConfig.load(addon.getInputStream(manifest)); BeardAch.printCon("Loading addon " + addonConfig.getString("name","N/A")); for(String className:addonConfig.getStringList("classes")){ classList.add(className); } } } catch (IOException e) { printCon("[ERROR] An I/O error occured while trying to access an addon. " + addon.getName()); if(self.getConfig().getBoolean("general.debug")){ e.printStackTrace(); } } catch (InvalidConfigurationException e) { printCon("[ERROR] Configuration header for "+ addon.getName() + " appears to be corrupt"); if(self.getConfig().getBoolean("general.debug")){ e.printStackTrace(); } } return classList; } @Override public void makeClass(Class<? extends IConfigurable> classType) { if(classType!=null){ if(ITrigger.class.isAssignableFrom(classType)){ addTrigger((Class<? extends ITrigger>) classType); }else if(IReward.class.isAssignableFrom(classType)){ addReward((Class<? extends IReward>) classType); } } } }; printCon("Loading addons"); addonLoader.loadAddons(); printCon("Loading Achievements"); achievementManager.loadAchievements(); printCon("Starting achievement checker"); getServer().getScheduler().scheduleSyncRepeatingTask(this, new Runnable(){ public void run() { achievementManager.checkPlayers(); } }, 600L,600L); printCon("Loading commands"); //commands getCommand("ach-reload").setExecutor(new AchReloadCommand()); getCommand("ach").setExecutor(new AchCommand()); getCommand("ach-fancy").setExecutor(new AchFancyCommand()); printCon("Loaded Version:" + getDescription().getVersion()); }
diff --git a/src/com/undeadscythes/udsplugin/commands/NickCmd.java b/src/com/undeadscythes/udsplugin/commands/NickCmd.java index 0a8c0a5..e348c64 100644 --- a/src/com/undeadscythes/udsplugin/commands/NickCmd.java +++ b/src/com/undeadscythes/udsplugin/commands/NickCmd.java @@ -1,28 +1,28 @@ package com.undeadscythes.udsplugin.commands; import com.undeadscythes.udsplugin.*; /** * Change a players nickname. * @author UndeadScythes */ public class NickCmd extends CommandWrapper { @Override public void playerExecute() { SaveablePlayer target; if(args.length == 1) { if(noCensor(args[0])) { if(player.getName().toLowerCase().contains(args[0].toLowerCase()) || hasPerm(Perm.NICK_OTHER)) { player.setDisplayName(args[0]); player.sendNormal("Your nickname has been changed to " + args[0] + "."); } else { player.sendError("Your nickname must be a shortened version of your Minecraft name."); } } } else if(numArgsHelp(2) && hasPerm(Perm.NICK_OTHER) && (target = getMatchingPlayer(args[0])) != null && noCensor(args[1])) { target.setDisplayName(args[1]); - player.sendNormal(player.getName() + "'s nickname has been changed to " + args[1] + "."); + player.sendNormal(target.getName() + "'s nickname has been changed to " + args[1] + "."); target.sendNormal("Your nickname has been changed to " + args[1] + "."); } } }
true
true
public void playerExecute() { SaveablePlayer target; if(args.length == 1) { if(noCensor(args[0])) { if(player.getName().toLowerCase().contains(args[0].toLowerCase()) || hasPerm(Perm.NICK_OTHER)) { player.setDisplayName(args[0]); player.sendNormal("Your nickname has been changed to " + args[0] + "."); } else { player.sendError("Your nickname must be a shortened version of your Minecraft name."); } } } else if(numArgsHelp(2) && hasPerm(Perm.NICK_OTHER) && (target = getMatchingPlayer(args[0])) != null && noCensor(args[1])) { target.setDisplayName(args[1]); player.sendNormal(player.getName() + "'s nickname has been changed to " + args[1] + "."); target.sendNormal("Your nickname has been changed to " + args[1] + "."); } }
public void playerExecute() { SaveablePlayer target; if(args.length == 1) { if(noCensor(args[0])) { if(player.getName().toLowerCase().contains(args[0].toLowerCase()) || hasPerm(Perm.NICK_OTHER)) { player.setDisplayName(args[0]); player.sendNormal("Your nickname has been changed to " + args[0] + "."); } else { player.sendError("Your nickname must be a shortened version of your Minecraft name."); } } } else if(numArgsHelp(2) && hasPerm(Perm.NICK_OTHER) && (target = getMatchingPlayer(args[0])) != null && noCensor(args[1])) { target.setDisplayName(args[1]); player.sendNormal(target.getName() + "'s nickname has been changed to " + args[1] + "."); target.sendNormal("Your nickname has been changed to " + args[1] + "."); } }
diff --git a/src/cn/uc/play/japid/template/TemplateLoaderMysqlImpl.java b/src/cn/uc/play/japid/template/TemplateLoaderMysqlImpl.java index 1aebad5..0aa2b7c 100644 --- a/src/cn/uc/play/japid/template/TemplateLoaderMysqlImpl.java +++ b/src/cn/uc/play/japid/template/TemplateLoaderMysqlImpl.java @@ -1,181 +1,181 @@ package cn.uc.play.japid.template; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import cn.uc.play.japid.exception.InvalidArgumentException; import cn.uc.play.japid.exception.TemplateCompileException; import cn.uc.play.japid.util.FileUtils; import play.Logger; import play.Play; import play.db.DB; import play.db.helper.JdbcHelper; import play.cache.Cache; import play.libs.Codec; /** * Load template(s) from mysql. * * @author Robin Han<[email protected]> * @date 2012-4-29 */ public class TemplateLoaderMysqlImpl implements UJapidTemplateLoader { private Map<String, UJapidTemplate> templatesCache = new ConcurrentHashMap(); private long nativeCacheExpire = 3 * 60 * 1000; private long remoteCacheExpire = 60 * 60 * 1000; private File root; public TemplateLoaderMysqlImpl(String templateDir, long nativeCacheExpire, long remoteCacheExpire) throws FileNotFoundException { if (nativeCacheExpire > -1) { this.nativeCacheExpire = nativeCacheExpire; } if (remoteCacheExpire > -1) { this.remoteCacheExpire = remoteCacheExpire / 1000; } this.root = new File(templateDir); if (!root.exists()) { throw new FileNotFoundException(templateDir); } } @Override public UJapidTemplate loadTemplate(String name) throws SQLException { if (name == null || name.isEmpty()) { return null; } UJapidTemplate template = templatesCache.get(name); if (template != null) { Long lastModifyInRemoteCache = Cache.get(Codec.hexMD5(name), Long.class); if (lastModifyInRemoteCache != null && template.lastModifyTime.getTime() >= lastModifyInRemoteCache) { return template; } } String sql = "select id, source, last_modify from TEMPLATE where id=?"; ResultSet rs = JdbcHelper.execute(sql, name); if (rs.next()) { UJapidTemplate t = createTemplateFromResultSet(rs); return t; } return null; } @Override public Map<String, UJapidTemplate> loadAllTemplates() throws SQLException { Map<String, UJapidTemplate> map = new HashMap<String, UJapidTemplate>(); String sql = "select id, source, last_modify from TEMPLATE"; ResultSet rs = JdbcHelper.execute(sql); while (rs.next()) { UJapidTemplate template = createTemplateFromResultSet(rs); map.put(template.nameWithPath, template); } return map; } private UJapidTemplate createTemplateFromResultSet(ResultSet rs) throws SQLException { - Date lastModifyTime = rs.getDate("last_modify"); + Date lastModifyTime = rs.getTimestamp("last_modify"); String path = rs.getString("id"); UJapidTemplate templateInNativeCache = templatesCache.get(path); if (templateInNativeCache != null && lastModifyTime.getTime() <= templateInNativeCache.lastModifyTime .getTime()) { Cache.set(Codec.hexMD5(path), new Long( lastModifyTime.getTime() / 1000), remoteCacheExpire + "s"); return templateInNativeCache; } UJapidTemplate template = new UJapidTemplate(); template.nameWithPath = rs.getString("id"); template.name = FileUtils.getFileNameInPath(template.nameWithPath); template.lastModifyTime = lastModifyTime; template.lastSyncTime = new Date(); template.source = rs.getString("source"); template.mode = TemplateStoreMode.DB; try { FileUtils.writeToFile( root + File.separator + template.nameWithPath, template.source); UJapidTemplate.compileTemplate(template); templatesCache.put(template.nameWithPath, template); Cache.set(Codec.hexMD5(template.nameWithPath), new Long( template.lastModifyTime.getTime() / 1000), remoteCacheExpire + "s"); } catch (Exception e) { revertTemplate(template.nameWithPath, e); } return template; } private void revertTemplate(String path, Exception e) { UJapidTemplate template = templatesCache.containsKey(path) ? templatesCache .get(path) : null; if (template != null) { try { FileUtils.writeToFile(root + File.separator + path, template.source); } catch (IOException e1) { Logger.error(e, "Revert template " + path + " faild."); } UJapidTemplate.compileTemplate(template); template.lastModifyTime = new Date(); template.lastSyncTime = new Date(); templatesCache.put(path, template); Logger.error( e, path + " compiling faild. Ignore this compiling request and return the older template object in cache."); } else { throw new TemplateCompileException(path + " compiling faild.", e); } if (Play.Mode.DEV == Play.mode) { throw new TemplateCompileException(path + " compiling faild.", e); } } @Override public UJapidTemplate getTemplate(String path) throws Exception { UJapidTemplate template = templatesCache.get(path); if (template != null && (new Date().getTime() - template.lastSyncTime.getTime()) < nativeCacheExpire) { return template; } return loadTemplate(path); } }
true
true
private UJapidTemplate createTemplateFromResultSet(ResultSet rs) throws SQLException { Date lastModifyTime = rs.getDate("last_modify"); String path = rs.getString("id"); UJapidTemplate templateInNativeCache = templatesCache.get(path); if (templateInNativeCache != null && lastModifyTime.getTime() <= templateInNativeCache.lastModifyTime .getTime()) { Cache.set(Codec.hexMD5(path), new Long( lastModifyTime.getTime() / 1000), remoteCacheExpire + "s"); return templateInNativeCache; } UJapidTemplate template = new UJapidTemplate(); template.nameWithPath = rs.getString("id"); template.name = FileUtils.getFileNameInPath(template.nameWithPath); template.lastModifyTime = lastModifyTime; template.lastSyncTime = new Date(); template.source = rs.getString("source"); template.mode = TemplateStoreMode.DB; try { FileUtils.writeToFile( root + File.separator + template.nameWithPath, template.source); UJapidTemplate.compileTemplate(template); templatesCache.put(template.nameWithPath, template); Cache.set(Codec.hexMD5(template.nameWithPath), new Long( template.lastModifyTime.getTime() / 1000), remoteCacheExpire + "s"); } catch (Exception e) { revertTemplate(template.nameWithPath, e); } return template; }
private UJapidTemplate createTemplateFromResultSet(ResultSet rs) throws SQLException { Date lastModifyTime = rs.getTimestamp("last_modify"); String path = rs.getString("id"); UJapidTemplate templateInNativeCache = templatesCache.get(path); if (templateInNativeCache != null && lastModifyTime.getTime() <= templateInNativeCache.lastModifyTime .getTime()) { Cache.set(Codec.hexMD5(path), new Long( lastModifyTime.getTime() / 1000), remoteCacheExpire + "s"); return templateInNativeCache; } UJapidTemplate template = new UJapidTemplate(); template.nameWithPath = rs.getString("id"); template.name = FileUtils.getFileNameInPath(template.nameWithPath); template.lastModifyTime = lastModifyTime; template.lastSyncTime = new Date(); template.source = rs.getString("source"); template.mode = TemplateStoreMode.DB; try { FileUtils.writeToFile( root + File.separator + template.nameWithPath, template.source); UJapidTemplate.compileTemplate(template); templatesCache.put(template.nameWithPath, template); Cache.set(Codec.hexMD5(template.nameWithPath), new Long( template.lastModifyTime.getTime() / 1000), remoteCacheExpire + "s"); } catch (Exception e) { revertTemplate(template.nameWithPath, e); } return template; }
diff --git a/org.emftext.sdk/src/org/emftext/sdk/codegen/generators/TextPrinterBaseGenerator.java b/org.emftext.sdk/src/org/emftext/sdk/codegen/generators/TextPrinterBaseGenerator.java index 244cdaa4f..72ac57619 100644 --- a/org.emftext.sdk/src/org/emftext/sdk/codegen/generators/TextPrinterBaseGenerator.java +++ b/org.emftext.sdk/src/org/emftext/sdk/codegen/generators/TextPrinterBaseGenerator.java @@ -1,764 +1,764 @@ /******************************************************************************* * Copyright (c) 2006-2009 * Software Technology Group, Dresden University of Technology * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) any * later version. This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU Lesser General Public License for more details. You should have * received a copy of the GNU Lesser General Public License along with this * program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, * Suite 330, Boston, MA 02111-1307 USA * * Contributors: * Software Technology Group - TU Dresden, Germany * - initial API and implementation ******************************************************************************/ package org.emftext.sdk.codegen.generators; import java.io.OutputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Queue; import java.util.Set; import org.eclipse.emf.codegen.ecore.genmodel.GenClass; import org.eclipse.emf.codegen.ecore.genmodel.GenFeature; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EReference; import org.eclipse.emf.ecore.EStructuralFeature; import org.emftext.runtime.resource.ITextResource; import org.emftext.runtime.resource.ITokenResolver; import org.emftext.runtime.resource.ITokenResolverFactory; import org.emftext.runtime.resource.impl.AbstractEMFTextPrinter; import org.emftext.sdk.codegen.GenerationContext; import org.emftext.sdk.codegen.OptionManager; import org.emftext.sdk.codegen.composites.JavaComposite; import org.emftext.sdk.codegen.composites.StringComponent; import org.emftext.sdk.codegen.composites.StringComposite; import org.emftext.sdk.codegen.util.GeneratorUtil; import org.emftext.sdk.codegen.util.StringUtil; import org.emftext.sdk.concretesyntax.Cardinality; import org.emftext.sdk.concretesyntax.CardinalityDefinition; import org.emftext.sdk.concretesyntax.Choice; import org.emftext.sdk.concretesyntax.CompoundDefinition; import org.emftext.sdk.concretesyntax.ConcreteSyntax; import org.emftext.sdk.concretesyntax.Containment; import org.emftext.sdk.concretesyntax.CsString; import org.emftext.sdk.concretesyntax.Definition; import org.emftext.sdk.concretesyntax.LineBreak; import org.emftext.sdk.concretesyntax.OptionTypes; import org.emftext.sdk.concretesyntax.PLUS; import org.emftext.sdk.concretesyntax.Placeholder; import org.emftext.sdk.concretesyntax.QUESTIONMARK; import org.emftext.sdk.concretesyntax.Rule; import org.emftext.sdk.concretesyntax.STAR; import org.emftext.sdk.concretesyntax.Sequence; import org.emftext.sdk.concretesyntax.Terminal; import org.emftext.sdk.concretesyntax.WhiteSpaces; import org.emftext.sdk.syntax_analysis.CollectInFeatureHelper; /** * A generator that creates the base class for the printer. * * @author Sven Karol ([email protected]) */ public class TextPrinterBaseGenerator extends BaseGenerator { private static final String OBJECT_CLASS_NAME = Object.class.getName(); private static final String STRING_CLASS_NAME = String.class.getName(); private static final String INTEGER_CLASS_NAME = Integer.class.getName(); private static final String COLLECTION_CLASS_NAME = Collection.class.getName(); private static final String LIST_CLASS_NAME = List.class.getName(); private static final String MAP_CLASS_NAME = Map.class.getName(); private static final String HASH_MAP_CLASS_NAME = HashMap.class.getName(); private static final String ARRAYS_CLASS_NAME = java.util.Arrays.class.getName(); private static final String LIST_ITERATOR_CLASS_NAME = ListIterator.class.getName(); private static final String NULL_POINTER_CLASS_NAME = NullPointerException.class.getName(); private static final String EOBJECT_CLASS_NAME = EObject.class.getName(); private static final String EREFERENCE_CLASS_NAME = EReference.class.getName(); private static final String ITEXT_RESOURCE_CLASS_NAME = ITextResource.class.getName(); private static final String ITOKEN_RESOLVER_FACTORY_CLASS_NAME = ITokenResolverFactory.class.getName(); private static final String OUTPUT_STREAM_CLASS_NAME = OutputStream.class.getName(); private static final String PRINTER_WRITER_CLASS_NAME = PrintWriter.class.getName(); private static final String STRING_WRITER_CLASS_NAME = StringWriter.class.getName(); private final static String localtabName = "localtab"; private ConcreteSyntax concretSyntax; private String tokenResolverFactoryClassName; private int tokenSpace; /** maps all choices to a method name */ private Map<Choice, String> choice2Name; /** maps all rules to choices nested somewhere, but not to the root choice! */ private Map<Rule, Set<Choice>> rule2SubChoice; /** * maps all sequences in all choices to all features which HAVE to be printed in the sequence */ private Map<Sequence, Set<String>> sequence2NecessaryFeatures; private Map<Sequence, Set<String>> sequence2ReachableFeatures; private GenerationContext context; public TextPrinterBaseGenerator(GenerationContext context) { super(context.getPackageName(), context.getPrinterBaseClassName()); this.context = context; this.concretSyntax = context.getConcreteSyntax(); this.tokenResolverFactoryClassName = context.getTokenResolverFactoryClassName(); } private void extractChoices(List<Rule> rules, Map<Rule, Set<Choice>> ruleMap, Map<Choice, String> choiceMap, Map<Sequence, Set<String>> necessaryMap, Map<Sequence, Set<String>> reachableMap) { for (Rule rule : rules) { choiceMap.put(rule.getDefinition(), getMethodName(rule)); Set<Choice> choices = new HashSet<Choice>(); ruleMap.put(rule, choices); extractChoices(rule.getDefinition(), choices, choiceMap, necessaryMap, reachableMap, null, getMethodName(rule) + "_", 0); } } private static void extractChoices(Choice choice, Set<Choice> choiceSet, Map<Choice, String> choiceMap, Map<Sequence, Set<String>> necessaryMap, Map<Sequence, Set<String>> reachableMap, Sequence parent, String namePrefix, int choiceIndex) { for (Sequence seq : choice.getOptions()) { Set<String> sequenceNecessaryFeatures = new HashSet<String>(); Set<String> sequenceReachableFeatures = new HashSet<String>(); necessaryMap.put(seq, sequenceNecessaryFeatures); reachableMap.put(seq, sequenceReachableFeatures); for (Definition def : seq.getParts()) { final boolean hasMinimalCardinalityOneOrHigher = GeneratorUtil.hasMinimalCardinalityOneOrHigher(def); if (def instanceof CompoundDefinition) { String subChoiceName = namePrefix + choiceIndex++; Choice currentChoice = ((CompoundDefinition) def) .getDefinitions(); choiceMap.put(currentChoice, subChoiceName); choiceSet.add(currentChoice); extractChoices(currentChoice, choiceSet, choiceMap, necessaryMap, reachableMap, hasMinimalCardinalityOneOrHigher ? seq : null, subChoiceName + "_", 0); } else if (def instanceof Terminal) { if (hasMinimalCardinalityOneOrHigher) { sequenceNecessaryFeatures.add(((Terminal) def) .getFeature().getName()); } sequenceReachableFeatures.add(((Terminal) def).getFeature() .getName()); } } if (parent != null) { necessaryMap.get(parent).addAll(sequenceNecessaryFeatures); reachableMap.get(parent).addAll(sequenceReachableFeatures); } } } private List<Rule> prepare() { List<Rule> rules = concretSyntax.getAllRules(); choice2Name = new HashMap<Choice, String>(rules.size()); sequence2NecessaryFeatures = new HashMap<Sequence, Set<String>>(rules .size()); sequence2ReachableFeatures = new HashMap<Sequence, Set<String>>(rules .size()); rule2SubChoice = new HashMap<Rule, Set<Choice>>(rules.size()); extractChoices(rules, rule2SubChoice, choice2Name, sequence2NecessaryFeatures, sequence2ReachableFeatures); tokenSpace = OptionManager.INSTANCE.getIntegerOptionValue(concretSyntax, OptionTypes.TOKENSPACE, true, this); if (tokenSpace < 0) { tokenSpace = 0; } return rules; } @Override public boolean generate(PrintWriter writer) { List<Rule> rules = prepare(); StringComposite sc = new JavaComposite(); sc.add("package " + getResourcePackageName() + ";"); sc.addLineBreak(); sc.add("public abstract class " + getResourceClassName() + " extends " + AbstractEMFTextPrinter.class.getName() + " {"); sc.addLineBreak(); generateMembers(sc); sc.addLineBreak(); generateConstructor(sc); sc.addLineBreak(); printMatchRule(sc); sc.addLineBreak(); generateDoPrintMethod(sc, rules); sc.addLineBreak(); for (Rule rule : rules) { generatePrintRuleMethod(sc, rule); sc.addLineBreak(); } sc.add("}"); writer.write(sc.toString()); return true; } private void generateDoPrintMethod(StringComposite sc, List<Rule> rules) { sc.add("protected void doPrint(" + EOBJECT_CLASS_NAME + " element, " + PRINTER_WRITER_CLASS_NAME + " out, " + STRING_CLASS_NAME + " globaltab) {"); sc.add("if (element == null || out == null) throw new " + NULL_POINTER_CLASS_NAME + "(\"Nothing to write or to write on.\");"); sc.addLineBreak(); Queue<Rule> ruleQueue = new LinkedList<Rule>(rules); while (!ruleQueue.isEmpty()) { Rule rule = ruleQueue.remove(); // check whether all subclass calls have been printed if (GeneratorUtil.hasSubClassesWithCS(rule.getMetaclass(), ruleQueue)) { ruleQueue.add(rule); } else { sc.add("if (element instanceof " + getMetaClassName(rule) + ") {"); sc.add(getMethodName(rule) + "((" + getMetaClassName(rule) + ") element, globaltab, out);"); sc.add("return;"); sc.add("}"); } } sc.addLineBreak(); sc.add("resource.addWarning(\"The cs printer can not handle \" + element.eClass().getName() + \" elements\", element);"); sc.add("}"); } private void generateConstructor(StringComposite sc) { sc.add("public " + super.getResourceClassName() + "(" + OUTPUT_STREAM_CLASS_NAME + " o, " + ITEXT_RESOURCE_CLASS_NAME + " resource) {"); sc.add("super(o, resource);"); sc.add("}"); } private void generateMembers(StringComposite sc) { sc.add("protected " + ITOKEN_RESOLVER_FACTORY_CLASS_NAME + " tokenResolverFactory = new " + tokenResolverFactoryClassName + "();"); //sc.add("protected " + referenceResolverSwitchClassName + " referenceResolverSwitch;"); } private void generatePrintRuleMethod(StringComposite sc, Rule rule) { final GenClass genClass = rule.getMetaclass(); List<GenFeature> featureList = genClass.getAllGenFeatures(); sc.add("public void " + getMethodName(rule) + "(" + getMetaClassName(rule) + " element, " + STRING_CLASS_NAME + " outertab, " + PRINTER_WRITER_CLASS_NAME + " out) {"); sc.add(new StringComponent(STRING_CLASS_NAME + " " + localtabName + " = outertab;", localtabName)); String printCountingMapName = "printCountingMap"; sc.add(new StringComponent(MAP_CLASS_NAME + "<" + STRING_CLASS_NAME + ", " + INTEGER_CLASS_NAME + "> " + printCountingMapName + " = new " + HASH_MAP_CLASS_NAME + "<" + STRING_CLASS_NAME + ", " + INTEGER_CLASS_NAME + ">(" + featureList.size() + ");", printCountingMapName)); if (featureList.size() > 0) { sc.add(OBJECT_CLASS_NAME + " temp;"); } for (GenFeature genFeature : featureList) { EStructuralFeature feature = genFeature.getEcoreFeature(); sc.add("temp = element." + generateAccessMethod(genClass, genFeature) + ";"); String featureSize = feature.getUpperBound() == -1 ? "((" + java.util.Collection.class.getName() + "<?>) temp).size()" : "1"; sc.add("printCountingMap.put(\"" + feature.getName() + "\", temp == null ? 0 : " + featureSize + ");"); //mapDefinition.enable(); } generatePrintCollectedTokensCode(sc, rule); printChoice(rule.getDefinition(), sc, genClass); sc.add("}"); printChoices(sc, rule); } private void printChoices(StringComposite sc, Rule rule) { for (Choice choice : rule2SubChoice.get(rule)) { sc .add("public void " + choice2Name.get(choice) + "(" + getMetaClassName(rule) + " element, " + STRING_CLASS_NAME + " outertab, " + PRINTER_WRITER_CLASS_NAME + " out, " + MAP_CLASS_NAME + "<" + STRING_CLASS_NAME + ", " + INTEGER_CLASS_NAME + "> printCountingMap){"); sc.add(new StringComponent(STRING_CLASS_NAME + " " + localtabName + " = outertab;", localtabName)); printChoice(choice, sc, rule.getMetaclass()); sc.add("}"); } } private String getMetaClassName(Rule rule) { if (hasMapType(rule.getMetaclass()) ) { return rule.getMetaclass().getQualifiedClassName(); } return rule.getMetaclass().getQualifiedInterfaceName(); } private String getMethodName(Rule rule) { String className = getMetaClassName(rule); // first escape underscore with their unicode value className = className.replace("_", "_005f"); // then replace package separator with underscore className = className.replace(".", "_"); return "print_" + className; } private void generatePrintCollectedTokensCode(StringComposite sc, Rule rule) { final GenClass genClass = rule.getMetaclass(); List<GenFeature> featureList = genClass.getAllGenFeatures(); sc.add("// print collected hidden tokens"); for (GenFeature genFeature : featureList) { EStructuralFeature feature = genFeature.getEcoreFeature(); if (new CollectInFeatureHelper().isCollectInFeature(rule.getSyntax(), feature)) { sc.add("{"); sc.add(EStructuralFeature.class.getName() + " feature = element.eClass()." + GeneratorUtil.createGetFeatureCall(genClass, genFeature) + ";"); sc.add(OBJECT_CLASS_NAME + " value = element.eGet(feature);"); sc.add("if (value instanceof " + LIST_CLASS_NAME + ") {"); sc.add("for (" + OBJECT_CLASS_NAME + " next : (" + LIST_CLASS_NAME + "<?>) value) {"); sc.add("out.print(tokenResolverFactory.createCollectInTokenResolver(\"" + feature.getName() + "\").deResolve(next, feature, element));"); sc.add("}"); sc.add("}"); sc.add("}"); } } } private void printChoice(Choice choice, StringComposite sc, GenClass genClass) { String countName = "count"; sc.add(new StringComponent("int " + countName + ";", countName)); if (choice.getOptions().size() > 1) { sc.add("int alt = -1;"); Iterator<Sequence> seqIt = choice.getOptions().iterator(); if (seqIt.hasNext()) { Sequence firstSeq = seqIt.next(); int count = 0; StringComposite sc1 = new JavaComposite(); sc1.add("switch(alt) {"); sc.add("alt=" + count++ + ";"); sc.add("int matches="); printMatchCall(firstSeq, sc); sc.add("int tempMatchCount;"); while (seqIt.hasNext()) { Sequence seq = seqIt.next(); sc.add("tempMatchCount="); printMatchCall(seq, sc); sc.add("if (tempMatchCount > matches) {"); sc.add("alt = " + count + ";"); sc.add("matches = tempMatchCount;"); sc.add("}"); sc1.add("case " + count + ":"); // extra scope for case begin sc1.add("{"); printSequence(seq, sc1, genClass); // extra scope for case end sc1.add("}"); sc1.add("break;"); count++; } sc1.add("default:"); printSequence(firstSeq, sc1, genClass); sc1.add("}"); sc.add(sc1); } } else if (choice.getOptions().size() == 1) { printSequence(choice.getOptions().get(0), sc, genClass); } } private Set<String> getReachableFeatures(Choice choice) { Set<String> result = new LinkedHashSet<String>(); for (Sequence seq : choice.getOptions()) { result.addAll(sequence2ReachableFeatures.get(seq)); } return result; } private void printSequence(Sequence sequence, StringComposite sc, GenClass genClass) { Set<String> neededFeatures = new LinkedHashSet<String>( sequence2NecessaryFeatures.get(sequence)); //EClass metaClass = genClass.getEcoreClass(); ListIterator<Definition> definitionIterator = sequence.getParts() .listIterator(); String iterateName = "iterate"; sc.add(new StringComponent("boolean " + iterateName + " = true;", iterateName)); String sWriteName = "sWriter"; sc.add(new StringComponent(STRING_WRITER_CLASS_NAME + " " + sWriteName + " = null;", sWriteName)); String out1Name = "out1"; sc.add(new StringComponent(PRINTER_WRITER_CLASS_NAME + " " + out1Name + " = null;", out1Name)); String printCountingMap1Name = "printCountingMap1"; sc.add(new StringComponent(HASH_MAP_CLASS_NAME + "<" + STRING_CLASS_NAME + ", " + INTEGER_CLASS_NAME + "> " + printCountingMap1Name + " = null;", printCountingMap1Name)); while (definitionIterator.hasNext()) { Definition definition = definitionIterator.next(); sc.add("//////////////DEFINITION PART BEGINS (" + definition.eClass().getName() + "):"); String printPrefix = "out.print("; if (definition instanceof LineBreak) { int count = ((LineBreak) definition).getTab(); if (count > 0) { String tab = getTabString(count); sc.add("localtab += \"" + tab + "\";"); } sc.add("out.println();"); sc.add("out.print(localtab);"); //localTabDefinition.enable(); } else { if (definition instanceof WhiteSpaces) { int count = ((WhiteSpaces) definition).getAmount(); if (count > 0) { String spaces = getWhiteSpaceString(count); sc.add(printPrefix + "\"" + spaces + "\");"); } } else if (definition instanceof CsString) { CsString terminal = (CsString) definition; sc.add(printPrefix + "\"" + terminal.getValue().replaceAll("\"", "\\\\\"") + "\");"); // the given tokenSpace (>0) causes an additional // print statement to be printed if (tokenSpace > 0) { Definition lookahead = null; if (definitionIterator.hasNext()){ lookahead = definitionIterator.next(); definitionIterator.previous(); } if (lookahead == null || !(lookahead instanceof WhiteSpaces)) { String printSuffix = getWhiteSpaceString(tokenSpace); sc.add(printPrefix + "\"" + printSuffix + "\");"); } } } else { Cardinality cardinality = null; if (definition instanceof CardinalityDefinition) { cardinality = ((CardinalityDefinition) definition).getCardinality(); } if (definition instanceof CompoundDefinition) { CompoundDefinition compound = (CompoundDefinition) definition; String printStatement = choice2Name.get(compound.getDefinitions()) + "(element, localtab, out, printCountingMap);"; //localTabDefinition.enable(); // enter once if (cardinality == null || cardinality instanceof PLUS) { sc.add(printStatement); // needed features in non optional choice are also // needed features in this sequence // note: this implementation might remove to much in // some cases! for (Sequence seq1 : compound.getDefinitions() .getOptions()) { neededFeatures .removeAll(sequence2NecessaryFeatures .get(seq1)); } } // optional cases if (cardinality != null) { boolean isMany = !(cardinality instanceof QUESTIONMARK); // runtime: iterate as long as no fixpoint is // reached // make sure that NOT all elements of needed // features are printed in optional compounds! if (isMany) { sc.add("iterate = true;"); sc.add("while (iterate) {"); //iterateDeclaration.enable(); } sc.add("sWriter = new " + STRING_WRITER_CLASS_NAME + "();"); sc.add("out1 = new " + PRINTER_WRITER_CLASS_NAME + "(sWriter);"); sc.add("printCountingMap1 = new " + HASH_MAP_CLASS_NAME + "<" + STRING_CLASS_NAME + ", " + INTEGER_CLASS_NAME + ">(printCountingMap);"); //compoundDeclaration.enable(); sc.add(choice2Name.get(compound .getDefinitions()) + "(element, localtab, out1, printCountingMap1);"); sc.add("if (printCountingMap.equals(printCountingMap1)) {"); if (isMany) { sc.add("iterate = false;"); } sc.add("out1.close();"); sc.add("} else {"); // check if printed features are needed by // subsequent features // at least one element has to be preserved in that // case! // this could be enhanced by a counter on needed // features Collection<String> reachableFeatures = getReachableFeatures(compound .getDefinitions()); if (!neededFeatures.isEmpty() && !Collections.disjoint(neededFeatures, reachableFeatures)) { sc.add("if("); Iterator<String> it = neededFeatures.iterator(); sc.add("printCountingMap1.get(\"" + it.next() + "\")<1"); while (it.hasNext()) { String feature = it.next(); - sc.add("printCountingMap1.get(\"" + sc.add("||printCountingMap1.get(\"" + feature + "\")<1"); } sc.add(") {"); if (isMany) { sc.add("iterate = false;"); } sc.add("out1.close();"); sc.add("} else {"); sc.add("out1.flush();"); sc.add("out1.close();"); sc.add("out.print(sWriter.toString());"); sc.add("printCountingMap.putAll(printCountingMap1);"); sc.add("}"); } else { sc.add("out1.flush();"); sc.add("out1.close();"); sc.add("out.print(sWriter.toString());"); sc.add("printCountingMap.putAll(printCountingMap1);"); } sc.add("}"); if (isMany) { sc.add("}"); } } } // next steps: references --> proxy uri --> tokenresolver! else if (definition instanceof Terminal) { Terminal terminal = (Terminal) definition; final GenFeature genFeature = terminal.getFeature(); final String featureName = genFeature.getName(); sc.add("count = printCountingMap.get(\"" + featureName + "\");"); EStructuralFeature feature = genFeature .getEcoreFeature(); StringComposite printStatements = new JavaComposite(); if (terminal instanceof Placeholder) { String tokenName; tokenName = ((Placeholder) terminal).getToken().getName(); /* if (terminal instanceof DefinedPlaceholder) tokenName = ((DefinedPlaceholder) terminal) .getToken().getName(); else { assert terminal instanceof DerivedPlaceholder; tokenName = placeholder2TokenName .get(terminal); } */ if (feature instanceof EReference) { printStatements.add(ITokenResolver.class.getName() + " resolver = tokenResolverFactory.createTokenResolver(\"" + tokenName + "\");"); printStatements.add("resolver.setOptions(getOptions());"); printStatements.add(printPrefix + "resolver.deResolve(" + context.getReferenceResolverAccessor(genFeature) + ".deResolve((" + genFeature.getTypeGenClass().getQualifiedInterfaceName() + ") o, element, (" + EREFERENCE_CLASS_NAME + ") element.eClass().getEStructuralFeature(" + GeneratorUtil.getFeatureConstant(genClass, genFeature) + ")), element.eClass().getEStructuralFeature(" + GeneratorUtil.getFeatureConstant(genClass, genFeature) + "), element));"); } else { printStatements.add(ITokenResolver.class.getName() + " resolver = tokenResolverFactory.createTokenResolver(\"" + tokenName + "\");"); printStatements.add("resolver.setOptions(getOptions());"); printStatements.add(printPrefix + "resolver.deResolve((" + OBJECT_CLASS_NAME + ") o, element.eClass().getEStructuralFeature(" + GeneratorUtil.getFeatureConstant(genClass, genFeature) + "), element));"); } // the given tokenSpace (>0) causes an additional // print statement to be printed if (tokenSpace > 0) { Definition lookahead = null; if (definitionIterator.hasNext()){ lookahead = definitionIterator.next(); definitionIterator.previous(); } if (lookahead == null || !(lookahead instanceof WhiteSpaces)) { String printSuffix = getWhiteSpaceString(tokenSpace); printStatements.add("out.print(\"" + printSuffix + "\");"); } } } else { assert terminal instanceof Containment; printStatements.add("doPrint((" + EOBJECT_CLASS_NAME + ") o, out, localtab);"); //localTabDefinition.enable(); } sc.add("if (count > 0) {"); //countDefintion.enable(); if (cardinality == null || (cardinality instanceof QUESTIONMARK && !neededFeatures .contains(featureName))) { sc.add("Object o = element." + generateAccessMethod(genClass, genFeature) + ";"); if (feature.getUpperBound() != 1) { sc.add("o = ((" + LIST_CLASS_NAME +"<?>)o).get(((" + LIST_CLASS_NAME +"<?>)o).size() - count);"); } sc.add(printStatements); sc.add("printCountingMap.put(\"" + featureName + "\",count-1);"); neededFeatures.remove(featureName); } else if (cardinality instanceof PLUS || cardinality instanceof STAR) { if (feature.getUpperBound() != 1) { sc.add(LIST_ITERATOR_CLASS_NAME + "<?> it = ((" + LIST_CLASS_NAME +"<?>) element." + generateAccessMethod(genClass, genFeature) + ").listIterator(((" + LIST_CLASS_NAME +"<?>)element." + generateAccessMethod(genClass, genFeature) + ").size()-count);"); sc.add("while(it.hasNext()){"); sc.add(OBJECT_CLASS_NAME + " o = it.next();"); if (cardinality instanceof STAR && neededFeatures.contains(featureName)) { sc.add("if(!it.hasNext())"); sc.add("break;"); } sc.add(printStatements); sc.add("}"); sc.add("printCountingMap.put(\"" + featureName + "\",0);"); } else if (cardinality instanceof PLUS) { sc.add(OBJECT_CLASS_NAME + " o =element." + generateAccessMethod(genClass, genFeature) + ";"); sc.add(printStatements); sc.add("printCountingMap.put(\"" + featureName + "\",count-1);"); } if (cardinality instanceof PLUS) neededFeatures.remove(featureName); } sc.add("}"); // tab for if(count>0) } } } } } private void printMatchCall(Sequence seq, StringComposite sc) { if (sequence2NecessaryFeatures.get(seq).isEmpty()) { sc.add("0;"); return; } sc.add("matchCount(printCountingMap, " + ARRAYS_CLASS_NAME + ".asList("); boolean notFirst = false; for (String featureName : sequence2NecessaryFeatures.get(seq)) { if (notFirst) { sc.add(","); } else { notFirst = true; } sc.add("\"" + featureName + "\""); } sc.add("));"); } private void printMatchRule(StringComposite sc) { sc.add("protected static int matchCount(" + MAP_CLASS_NAME + "<" + STRING_CLASS_NAME + ", " + INTEGER_CLASS_NAME + "> featureCounter, " + COLLECTION_CLASS_NAME + "<" + STRING_CLASS_NAME+ "> needed){"); sc.add("int pos = 0;"); sc.add("int neg = 0;"); sc.addLineBreak(); sc.add("for(" + STRING_CLASS_NAME + " featureName:featureCounter.keySet()){"); sc.add("if(needed.contains(featureName)){"); sc.add("int value = featureCounter.get(featureName);"); sc.add("if (value == 0) {"); sc.add("neg += 1;"); sc.add("} else {"); sc.add("pos += 1;"); sc.add("}"); sc.add("}"); sc.add("}"); sc.add("return neg > 0 ? -neg : pos;"); sc.add("}"); } protected static String generateAccessMethod(GenClass genClass, GenFeature genFeature) { if (hasMapType(genClass)) { return "get" + StringUtil.capitalize(genFeature.getName()) + "()"; } else { String method = "eGet(element.eClass().getEStructuralFeature(" + GeneratorUtil.getFeatureConstant(genClass, genFeature) + "))"; return method; } } private static boolean hasMapType(GenClass genClass) { return java.util.Map.Entry.class.getName().equals(genClass.getEcoreClass().getInstanceClassName()); } private String getTabString(int count) { return getRepeatingString(count, '\t'); } private String getWhiteSpaceString(int count) { return getRepeatingString(count, ' '); } private String getRepeatingString(int count, char character) { StringBuffer spaces = new StringBuffer(); for (int i = 0; i < count; i++) { spaces.append(character); } return spaces.toString(); } }
true
true
private void printSequence(Sequence sequence, StringComposite sc, GenClass genClass) { Set<String> neededFeatures = new LinkedHashSet<String>( sequence2NecessaryFeatures.get(sequence)); //EClass metaClass = genClass.getEcoreClass(); ListIterator<Definition> definitionIterator = sequence.getParts() .listIterator(); String iterateName = "iterate"; sc.add(new StringComponent("boolean " + iterateName + " = true;", iterateName)); String sWriteName = "sWriter"; sc.add(new StringComponent(STRING_WRITER_CLASS_NAME + " " + sWriteName + " = null;", sWriteName)); String out1Name = "out1"; sc.add(new StringComponent(PRINTER_WRITER_CLASS_NAME + " " + out1Name + " = null;", out1Name)); String printCountingMap1Name = "printCountingMap1"; sc.add(new StringComponent(HASH_MAP_CLASS_NAME + "<" + STRING_CLASS_NAME + ", " + INTEGER_CLASS_NAME + "> " + printCountingMap1Name + " = null;", printCountingMap1Name)); while (definitionIterator.hasNext()) { Definition definition = definitionIterator.next(); sc.add("//////////////DEFINITION PART BEGINS (" + definition.eClass().getName() + "):"); String printPrefix = "out.print("; if (definition instanceof LineBreak) { int count = ((LineBreak) definition).getTab(); if (count > 0) { String tab = getTabString(count); sc.add("localtab += \"" + tab + "\";"); } sc.add("out.println();"); sc.add("out.print(localtab);"); //localTabDefinition.enable(); } else { if (definition instanceof WhiteSpaces) { int count = ((WhiteSpaces) definition).getAmount(); if (count > 0) { String spaces = getWhiteSpaceString(count); sc.add(printPrefix + "\"" + spaces + "\");"); } } else if (definition instanceof CsString) { CsString terminal = (CsString) definition; sc.add(printPrefix + "\"" + terminal.getValue().replaceAll("\"", "\\\\\"") + "\");"); // the given tokenSpace (>0) causes an additional // print statement to be printed if (tokenSpace > 0) { Definition lookahead = null; if (definitionIterator.hasNext()){ lookahead = definitionIterator.next(); definitionIterator.previous(); } if (lookahead == null || !(lookahead instanceof WhiteSpaces)) { String printSuffix = getWhiteSpaceString(tokenSpace); sc.add(printPrefix + "\"" + printSuffix + "\");"); } } } else { Cardinality cardinality = null; if (definition instanceof CardinalityDefinition) { cardinality = ((CardinalityDefinition) definition).getCardinality(); } if (definition instanceof CompoundDefinition) { CompoundDefinition compound = (CompoundDefinition) definition; String printStatement = choice2Name.get(compound.getDefinitions()) + "(element, localtab, out, printCountingMap);"; //localTabDefinition.enable(); // enter once if (cardinality == null || cardinality instanceof PLUS) { sc.add(printStatement); // needed features in non optional choice are also // needed features in this sequence // note: this implementation might remove to much in // some cases! for (Sequence seq1 : compound.getDefinitions() .getOptions()) { neededFeatures .removeAll(sequence2NecessaryFeatures .get(seq1)); } } // optional cases if (cardinality != null) { boolean isMany = !(cardinality instanceof QUESTIONMARK); // runtime: iterate as long as no fixpoint is // reached // make sure that NOT all elements of needed // features are printed in optional compounds! if (isMany) { sc.add("iterate = true;"); sc.add("while (iterate) {"); //iterateDeclaration.enable(); } sc.add("sWriter = new " + STRING_WRITER_CLASS_NAME + "();"); sc.add("out1 = new " + PRINTER_WRITER_CLASS_NAME + "(sWriter);"); sc.add("printCountingMap1 = new " + HASH_MAP_CLASS_NAME + "<" + STRING_CLASS_NAME + ", " + INTEGER_CLASS_NAME + ">(printCountingMap);"); //compoundDeclaration.enable(); sc.add(choice2Name.get(compound .getDefinitions()) + "(element, localtab, out1, printCountingMap1);"); sc.add("if (printCountingMap.equals(printCountingMap1)) {"); if (isMany) { sc.add("iterate = false;"); } sc.add("out1.close();"); sc.add("} else {"); // check if printed features are needed by // subsequent features // at least one element has to be preserved in that // case! // this could be enhanced by a counter on needed // features Collection<String> reachableFeatures = getReachableFeatures(compound .getDefinitions()); if (!neededFeatures.isEmpty() && !Collections.disjoint(neededFeatures, reachableFeatures)) { sc.add("if("); Iterator<String> it = neededFeatures.iterator(); sc.add("printCountingMap1.get(\"" + it.next() + "\")<1"); while (it.hasNext()) { String feature = it.next(); sc.add("printCountingMap1.get(\"" + feature + "\")<1"); } sc.add(") {"); if (isMany) { sc.add("iterate = false;"); } sc.add("out1.close();"); sc.add("} else {"); sc.add("out1.flush();"); sc.add("out1.close();"); sc.add("out.print(sWriter.toString());"); sc.add("printCountingMap.putAll(printCountingMap1);"); sc.add("}"); } else { sc.add("out1.flush();"); sc.add("out1.close();"); sc.add("out.print(sWriter.toString());"); sc.add("printCountingMap.putAll(printCountingMap1);"); } sc.add("}"); if (isMany) { sc.add("}"); } } } // next steps: references --> proxy uri --> tokenresolver! else if (definition instanceof Terminal) { Terminal terminal = (Terminal) definition; final GenFeature genFeature = terminal.getFeature(); final String featureName = genFeature.getName(); sc.add("count = printCountingMap.get(\"" + featureName + "\");"); EStructuralFeature feature = genFeature .getEcoreFeature(); StringComposite printStatements = new JavaComposite(); if (terminal instanceof Placeholder) { String tokenName; tokenName = ((Placeholder) terminal).getToken().getName(); /* if (terminal instanceof DefinedPlaceholder) tokenName = ((DefinedPlaceholder) terminal) .getToken().getName(); else { assert terminal instanceof DerivedPlaceholder; tokenName = placeholder2TokenName .get(terminal); } */ if (feature instanceof EReference) { printStatements.add(ITokenResolver.class.getName() + " resolver = tokenResolverFactory.createTokenResolver(\"" + tokenName + "\");"); printStatements.add("resolver.setOptions(getOptions());"); printStatements.add(printPrefix + "resolver.deResolve(" + context.getReferenceResolverAccessor(genFeature) + ".deResolve((" + genFeature.getTypeGenClass().getQualifiedInterfaceName() + ") o, element, (" + EREFERENCE_CLASS_NAME + ") element.eClass().getEStructuralFeature(" + GeneratorUtil.getFeatureConstant(genClass, genFeature) + ")), element.eClass().getEStructuralFeature(" + GeneratorUtil.getFeatureConstant(genClass, genFeature) + "), element));"); } else { printStatements.add(ITokenResolver.class.getName() + " resolver = tokenResolverFactory.createTokenResolver(\"" + tokenName + "\");"); printStatements.add("resolver.setOptions(getOptions());"); printStatements.add(printPrefix + "resolver.deResolve((" + OBJECT_CLASS_NAME + ") o, element.eClass().getEStructuralFeature(" + GeneratorUtil.getFeatureConstant(genClass, genFeature) + "), element));"); } // the given tokenSpace (>0) causes an additional // print statement to be printed if (tokenSpace > 0) { Definition lookahead = null; if (definitionIterator.hasNext()){ lookahead = definitionIterator.next(); definitionIterator.previous(); } if (lookahead == null || !(lookahead instanceof WhiteSpaces)) { String printSuffix = getWhiteSpaceString(tokenSpace); printStatements.add("out.print(\"" + printSuffix + "\");"); } } } else { assert terminal instanceof Containment; printStatements.add("doPrint((" + EOBJECT_CLASS_NAME + ") o, out, localtab);"); //localTabDefinition.enable(); } sc.add("if (count > 0) {"); //countDefintion.enable(); if (cardinality == null || (cardinality instanceof QUESTIONMARK && !neededFeatures .contains(featureName))) { sc.add("Object o = element." + generateAccessMethod(genClass, genFeature) + ";"); if (feature.getUpperBound() != 1) { sc.add("o = ((" + LIST_CLASS_NAME +"<?>)o).get(((" + LIST_CLASS_NAME +"<?>)o).size() - count);"); } sc.add(printStatements); sc.add("printCountingMap.put(\"" + featureName + "\",count-1);"); neededFeatures.remove(featureName); } else if (cardinality instanceof PLUS || cardinality instanceof STAR) { if (feature.getUpperBound() != 1) { sc.add(LIST_ITERATOR_CLASS_NAME + "<?> it = ((" + LIST_CLASS_NAME +"<?>) element." + generateAccessMethod(genClass, genFeature) + ").listIterator(((" + LIST_CLASS_NAME +"<?>)element." + generateAccessMethod(genClass, genFeature) + ").size()-count);"); sc.add("while(it.hasNext()){"); sc.add(OBJECT_CLASS_NAME + " o = it.next();"); if (cardinality instanceof STAR && neededFeatures.contains(featureName)) { sc.add("if(!it.hasNext())"); sc.add("break;"); } sc.add(printStatements); sc.add("}"); sc.add("printCountingMap.put(\"" + featureName + "\",0);"); } else if (cardinality instanceof PLUS) { sc.add(OBJECT_CLASS_NAME + " o =element." + generateAccessMethod(genClass, genFeature) + ";"); sc.add(printStatements); sc.add("printCountingMap.put(\"" + featureName + "\",count-1);"); } if (cardinality instanceof PLUS) neededFeatures.remove(featureName); } sc.add("}"); // tab for if(count>0) } } } } }
private void printSequence(Sequence sequence, StringComposite sc, GenClass genClass) { Set<String> neededFeatures = new LinkedHashSet<String>( sequence2NecessaryFeatures.get(sequence)); //EClass metaClass = genClass.getEcoreClass(); ListIterator<Definition> definitionIterator = sequence.getParts() .listIterator(); String iterateName = "iterate"; sc.add(new StringComponent("boolean " + iterateName + " = true;", iterateName)); String sWriteName = "sWriter"; sc.add(new StringComponent(STRING_WRITER_CLASS_NAME + " " + sWriteName + " = null;", sWriteName)); String out1Name = "out1"; sc.add(new StringComponent(PRINTER_WRITER_CLASS_NAME + " " + out1Name + " = null;", out1Name)); String printCountingMap1Name = "printCountingMap1"; sc.add(new StringComponent(HASH_MAP_CLASS_NAME + "<" + STRING_CLASS_NAME + ", " + INTEGER_CLASS_NAME + "> " + printCountingMap1Name + " = null;", printCountingMap1Name)); while (definitionIterator.hasNext()) { Definition definition = definitionIterator.next(); sc.add("//////////////DEFINITION PART BEGINS (" + definition.eClass().getName() + "):"); String printPrefix = "out.print("; if (definition instanceof LineBreak) { int count = ((LineBreak) definition).getTab(); if (count > 0) { String tab = getTabString(count); sc.add("localtab += \"" + tab + "\";"); } sc.add("out.println();"); sc.add("out.print(localtab);"); //localTabDefinition.enable(); } else { if (definition instanceof WhiteSpaces) { int count = ((WhiteSpaces) definition).getAmount(); if (count > 0) { String spaces = getWhiteSpaceString(count); sc.add(printPrefix + "\"" + spaces + "\");"); } } else if (definition instanceof CsString) { CsString terminal = (CsString) definition; sc.add(printPrefix + "\"" + terminal.getValue().replaceAll("\"", "\\\\\"") + "\");"); // the given tokenSpace (>0) causes an additional // print statement to be printed if (tokenSpace > 0) { Definition lookahead = null; if (definitionIterator.hasNext()){ lookahead = definitionIterator.next(); definitionIterator.previous(); } if (lookahead == null || !(lookahead instanceof WhiteSpaces)) { String printSuffix = getWhiteSpaceString(tokenSpace); sc.add(printPrefix + "\"" + printSuffix + "\");"); } } } else { Cardinality cardinality = null; if (definition instanceof CardinalityDefinition) { cardinality = ((CardinalityDefinition) definition).getCardinality(); } if (definition instanceof CompoundDefinition) { CompoundDefinition compound = (CompoundDefinition) definition; String printStatement = choice2Name.get(compound.getDefinitions()) + "(element, localtab, out, printCountingMap);"; //localTabDefinition.enable(); // enter once if (cardinality == null || cardinality instanceof PLUS) { sc.add(printStatement); // needed features in non optional choice are also // needed features in this sequence // note: this implementation might remove to much in // some cases! for (Sequence seq1 : compound.getDefinitions() .getOptions()) { neededFeatures .removeAll(sequence2NecessaryFeatures .get(seq1)); } } // optional cases if (cardinality != null) { boolean isMany = !(cardinality instanceof QUESTIONMARK); // runtime: iterate as long as no fixpoint is // reached // make sure that NOT all elements of needed // features are printed in optional compounds! if (isMany) { sc.add("iterate = true;"); sc.add("while (iterate) {"); //iterateDeclaration.enable(); } sc.add("sWriter = new " + STRING_WRITER_CLASS_NAME + "();"); sc.add("out1 = new " + PRINTER_WRITER_CLASS_NAME + "(sWriter);"); sc.add("printCountingMap1 = new " + HASH_MAP_CLASS_NAME + "<" + STRING_CLASS_NAME + ", " + INTEGER_CLASS_NAME + ">(printCountingMap);"); //compoundDeclaration.enable(); sc.add(choice2Name.get(compound .getDefinitions()) + "(element, localtab, out1, printCountingMap1);"); sc.add("if (printCountingMap.equals(printCountingMap1)) {"); if (isMany) { sc.add("iterate = false;"); } sc.add("out1.close();"); sc.add("} else {"); // check if printed features are needed by // subsequent features // at least one element has to be preserved in that // case! // this could be enhanced by a counter on needed // features Collection<String> reachableFeatures = getReachableFeatures(compound .getDefinitions()); if (!neededFeatures.isEmpty() && !Collections.disjoint(neededFeatures, reachableFeatures)) { sc.add("if("); Iterator<String> it = neededFeatures.iterator(); sc.add("printCountingMap1.get(\"" + it.next() + "\")<1"); while (it.hasNext()) { String feature = it.next(); sc.add("||printCountingMap1.get(\"" + feature + "\")<1"); } sc.add(") {"); if (isMany) { sc.add("iterate = false;"); } sc.add("out1.close();"); sc.add("} else {"); sc.add("out1.flush();"); sc.add("out1.close();"); sc.add("out.print(sWriter.toString());"); sc.add("printCountingMap.putAll(printCountingMap1);"); sc.add("}"); } else { sc.add("out1.flush();"); sc.add("out1.close();"); sc.add("out.print(sWriter.toString());"); sc.add("printCountingMap.putAll(printCountingMap1);"); } sc.add("}"); if (isMany) { sc.add("}"); } } } // next steps: references --> proxy uri --> tokenresolver! else if (definition instanceof Terminal) { Terminal terminal = (Terminal) definition; final GenFeature genFeature = terminal.getFeature(); final String featureName = genFeature.getName(); sc.add("count = printCountingMap.get(\"" + featureName + "\");"); EStructuralFeature feature = genFeature .getEcoreFeature(); StringComposite printStatements = new JavaComposite(); if (terminal instanceof Placeholder) { String tokenName; tokenName = ((Placeholder) terminal).getToken().getName(); /* if (terminal instanceof DefinedPlaceholder) tokenName = ((DefinedPlaceholder) terminal) .getToken().getName(); else { assert terminal instanceof DerivedPlaceholder; tokenName = placeholder2TokenName .get(terminal); } */ if (feature instanceof EReference) { printStatements.add(ITokenResolver.class.getName() + " resolver = tokenResolverFactory.createTokenResolver(\"" + tokenName + "\");"); printStatements.add("resolver.setOptions(getOptions());"); printStatements.add(printPrefix + "resolver.deResolve(" + context.getReferenceResolverAccessor(genFeature) + ".deResolve((" + genFeature.getTypeGenClass().getQualifiedInterfaceName() + ") o, element, (" + EREFERENCE_CLASS_NAME + ") element.eClass().getEStructuralFeature(" + GeneratorUtil.getFeatureConstant(genClass, genFeature) + ")), element.eClass().getEStructuralFeature(" + GeneratorUtil.getFeatureConstant(genClass, genFeature) + "), element));"); } else { printStatements.add(ITokenResolver.class.getName() + " resolver = tokenResolverFactory.createTokenResolver(\"" + tokenName + "\");"); printStatements.add("resolver.setOptions(getOptions());"); printStatements.add(printPrefix + "resolver.deResolve((" + OBJECT_CLASS_NAME + ") o, element.eClass().getEStructuralFeature(" + GeneratorUtil.getFeatureConstant(genClass, genFeature) + "), element));"); } // the given tokenSpace (>0) causes an additional // print statement to be printed if (tokenSpace > 0) { Definition lookahead = null; if (definitionIterator.hasNext()){ lookahead = definitionIterator.next(); definitionIterator.previous(); } if (lookahead == null || !(lookahead instanceof WhiteSpaces)) { String printSuffix = getWhiteSpaceString(tokenSpace); printStatements.add("out.print(\"" + printSuffix + "\");"); } } } else { assert terminal instanceof Containment; printStatements.add("doPrint((" + EOBJECT_CLASS_NAME + ") o, out, localtab);"); //localTabDefinition.enable(); } sc.add("if (count > 0) {"); //countDefintion.enable(); if (cardinality == null || (cardinality instanceof QUESTIONMARK && !neededFeatures .contains(featureName))) { sc.add("Object o = element." + generateAccessMethod(genClass, genFeature) + ";"); if (feature.getUpperBound() != 1) { sc.add("o = ((" + LIST_CLASS_NAME +"<?>)o).get(((" + LIST_CLASS_NAME +"<?>)o).size() - count);"); } sc.add(printStatements); sc.add("printCountingMap.put(\"" + featureName + "\",count-1);"); neededFeatures.remove(featureName); } else if (cardinality instanceof PLUS || cardinality instanceof STAR) { if (feature.getUpperBound() != 1) { sc.add(LIST_ITERATOR_CLASS_NAME + "<?> it = ((" + LIST_CLASS_NAME +"<?>) element." + generateAccessMethod(genClass, genFeature) + ").listIterator(((" + LIST_CLASS_NAME +"<?>)element." + generateAccessMethod(genClass, genFeature) + ").size()-count);"); sc.add("while(it.hasNext()){"); sc.add(OBJECT_CLASS_NAME + " o = it.next();"); if (cardinality instanceof STAR && neededFeatures.contains(featureName)) { sc.add("if(!it.hasNext())"); sc.add("break;"); } sc.add(printStatements); sc.add("}"); sc.add("printCountingMap.put(\"" + featureName + "\",0);"); } else if (cardinality instanceof PLUS) { sc.add(OBJECT_CLASS_NAME + " o =element." + generateAccessMethod(genClass, genFeature) + ";"); sc.add(printStatements); sc.add("printCountingMap.put(\"" + featureName + "\",count-1);"); } if (cardinality instanceof PLUS) neededFeatures.remove(featureName); } sc.add("}"); // tab for if(count>0) } } } } }
diff --git a/bundles/core/org.openhab.core/src/main/java/org/openhab/core/items/GenericItem.java b/bundles/core/org.openhab.core/src/main/java/org/openhab/core/items/GenericItem.java index 9512de60..acf2ea56 100644 --- a/bundles/core/org.openhab.core/src/main/java/org/openhab/core/items/GenericItem.java +++ b/bundles/core/org.openhab.core/src/main/java/org/openhab/core/items/GenericItem.java @@ -1,144 +1,144 @@ /** * openHAB, the open Home Automation Bus. * Copyright (C) 2010, openHAB.org <[email protected]> * * See the contributors.txt file in the distribution for a * full listing of individual contributors. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses>. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or * combining it with Eclipse (or a modified version of that library), * containing parts covered by the terms of the Eclipse Public License * (EPL), the licensors of this Program grant you additional permission * to convey the resulting work. */ package org.openhab.core.items; import java.util.Collection; import java.util.HashSet; import org.openhab.core.events.EventPublisher; import org.openhab.core.types.Command; import org.openhab.core.types.State; import org.openhab.core.types.UnDefType; /** * The abstract base class for all items. It provides all relevant logic * for the infrastructure, such as publishing updates to the event bus * or notifying listeners. * * @author Kai Kreuzer * */ abstract public class GenericItem implements Item { protected EventPublisher eventPublisher; protected Collection<StateChangeListener> listeners = new HashSet<StateChangeListener>(); final protected String name; protected State state = UnDefType.UNDEF; private boolean changed; private boolean updated; public GenericItem(String name) { this.name = name; } /* (non-Javadoc) * @see org.openhab.core.items.Item#getState() */ public State getState() { return state; } public void initialize() {} public void dispose() { this.eventPublisher = null; } /* (non-Javadoc) * @see org.openhab.core.items.Item#getName() */ public String getName() { return name; } @Override public boolean hasChanged() { return changed; } public void setChanged(boolean changed) { this.changed = changed; } @Override public boolean wasUpdated() { return updated; } public void setUpdated(boolean updated) { this.updated = updated; } public void setEventPublisher(EventPublisher eventPublisher) { this.eventPublisher = eventPublisher; } protected void internalSend(Command command) { // try to send the command to the bus if(eventPublisher!=null) { eventPublisher.sendCommand(this.getName(), command); } } public void setState(State state) { State oldState = this.state; this.state = state; notifyListeners(oldState, state); } - private void notifyListeners(State oldState, State newState) { + private synchronized void notifyListeners(State oldState, State newState) { // if nothing has changed, we do not need to send notifications if(oldState.equals(newState)) return; for(StateChangeListener listener : listeners) { listener.stateChanged(this, oldState, newState); } } @Override public String toString() { return getName() + " (" + "Type=" + getClass().getSimpleName() + ", " + "State=" + getState() + ")"; } public void addStateChangeListener(StateChangeListener listener) { listeners.add(listener); } public void removeStateChangeListener(StateChangeListener listener) { listeners.remove(listener); } }
true
true
private void notifyListeners(State oldState, State newState) { // if nothing has changed, we do not need to send notifications if(oldState.equals(newState)) return; for(StateChangeListener listener : listeners) { listener.stateChanged(this, oldState, newState); } }
private synchronized void notifyListeners(State oldState, State newState) { // if nothing has changed, we do not need to send notifications if(oldState.equals(newState)) return; for(StateChangeListener listener : listeners) { listener.stateChanged(this, oldState, newState); } }
diff --git a/src/net/minecraft/src/mod_IngameInfo.java b/src/net/minecraft/src/mod_IngameInfo.java index d01c1ec..c4b5022 100644 --- a/src/net/minecraft/src/mod_IngameInfo.java +++ b/src/net/minecraft/src/mod_IngameInfo.java @@ -1,1339 +1,1342 @@ package net.minecraft.src; import java.io.File; import java.io.FileWriter; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Scanner; import java.util.logging.Level; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiChat; import net.minecraft.client.gui.ScaledResolution; import net.minecraft.command.CommandBase; import net.minecraft.command.ICommandSender; import net.minecraft.command.WrongUsageException; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumMovingObjectType; import net.minecraft.util.MathHelper; import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.EnumGameType; import net.minecraft.world.EnumSkyBlock; import net.minecraft.world.World; import net.minecraft.world.biome.BiomeGenBase; import net.minecraft.world.chunk.Chunk; import org.lwjgl.opengl.GL11; import bspkrs.client.util.HUDUtils; import bspkrs.util.BSProp; import bspkrs.util.BSPropRegistry; import bspkrs.util.BlockID; import bspkrs.util.CommonUtils; import bspkrs.util.Const; import bspkrs.util.Coord; import bspkrs.util.ForgeUtils; import bspkrs.util.ModVersionChecker; public class mod_IngameInfo extends BaseMod { private final Minecraft mc; private ScaledResolution scaledResolution; private int alignMode; int rowNum[]; int rowCount[]; String text[]; String fileName; private boolean enabled = true; private boolean isForgeEnv = false; @BSProp(info = "Valid memory unit strings are KB, MB, GB") public static String memoryUnit = "MB"; @BSProp(info = "Horizontal offsets from the edge of the screen (when using right alignments the x offset is relative to the right edge of the screen)") public static String xOffsets = "2, 0, 2, 2, 0, 2, 2, 0, 2"; public static int[] xOffset; @BSProp(info = "Vertical offsets for each alignment position starting at top left (when using bottom alignments the y offset is relative to the bottom edge of the screen)") public static String yOffsets = "2, 2, 2, 0, 0, 0, 2, 41, 2"; public static int[] yOffset; @BSProp(info = "Set to true to show info when chat is open, false to disable info when chat is open\n\n**ONLY EDIT WHAT IS BELOW THIS**") public static boolean showInChat = false; private final String[] defaultConfig = { "<topleft>&fDay <day> (<daytime[&e/&8]><mctime[12]>&f) <slimes[<darkgreen>/&b]><biome>", "Light: <max[<lightnosunfeet>/7[&e/&c]]><max[<lightnosunfeet>/9[&a/]]><lightnosunfeet>", "&fXP: &e<xpthislevel>&f / &e<xpcap>", "Time: &b<rltime[h:mma]>" }; private final String configPath; private ModVersionChecker versionChecker; private boolean allowUpdateCheck; private final String versionURL = Const.VERSION_URL + "/Minecraft/" + Const.MCVERSION + "/ingameInfo.version"; private final String mcfTopic = "http://www.minecraftforum.net/topic/1009577-"; @Override public String getName() { return "IngameInfo"; } @Override public String getVersion() { return "ML " + Const.MCVERSION + ".r02"; } @Override public String getPriorities() { return "required-after:mod_bspkrsCore"; } public mod_IngameInfo() { BSPropRegistry.registerPropHandler(this.getClass()); mc = ModLoader.getMinecraftInstance(); configPath = "/config/IngameInfo/"; fileName = "ingameInfo.txt"; } public void loadFormatFile() { alignMode = 0; rowCount = (new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0 }); xOffset = (new int[] { 2, 0, 2, 2, 0, 2, 2, 0, 2 }); yOffset = (new int[] { 2, 2, 2, 0, 0, 0, 2, 41, 2 }); text = loadText(new File(CommonUtils.getMinecraftDir(), configPath + fileName)); for (int i = 0; i < text.length; i++) { if (text[i].toLowerCase().contains("<left>") || text[i].toLowerCase().contains("<topleft>")) alignMode = 0; else if (text[i].toLowerCase().contains("<center>") || text[i].toLowerCase().contains("<topcenter>")) alignMode = 1; else if (text[i].toLowerCase().contains("<right>") || text[i].toLowerCase().contains("<topright>")) alignMode = 2; else if (text[i].toLowerCase().contains("<middleleft>")) alignMode = 3; else if (text[i].toLowerCase().contains("<middlecenter>")) alignMode = 4; else if (text[i].toLowerCase().contains("<middleright>")) alignMode = 5; else if (text[i].toLowerCase().contains("<bottomleft>")) alignMode = 6; else if (text[i].toLowerCase().contains("<bottomcenter>")) alignMode = 7; else if (text[i].toLowerCase().contains("<bottomright>")) alignMode = 8; rowCount[alignMode]++; } String[] o = xOffsets.split(","); for (int i = 0; i < o.length; i++) xOffset[i] = CommonUtils.parseInt(o[i].trim()); o = yOffsets.split(","); for (int i = 0; i < o.length; i++) yOffset[i] = CommonUtils.parseInt(o[i].trim()); } @Override public void load() { loadFormatFile(); ModLoader.addCommand(new CommandIGI()); ModLoader.addLocalization("commands.igi.usage", "igi [reload/enable/disable/toggle]"); allowUpdateCheck = mod_bspkrsCore.allowUpdateCheck; if (allowUpdateCheck) { versionChecker = new ModVersionChecker(getName(), getVersion(), versionURL, mcfTopic); versionChecker.checkVersionWithLogging(); } ModLoader.setInGameHook(this, true, false); isForgeEnv = ForgeUtils.isForgeEnv(); } @Override public boolean onTickInGame(float f, Minecraft mc) { if (enabled && (mc.inGameHasFocus || mc.currentScreen == null || (mc.currentScreen instanceof GuiChat && showInChat)) && !mc.gameSettings.showDebugInfo) { scaledResolution = new ScaledResolution(mc.gameSettings, mc.displayWidth, mc.displayHeight); rowNum = (new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0 }); String lines[] = text; int i = lines.length; GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); //mc.renderEngine.resetBoundTexture(); for (int j = 0; j < i; j++) { try { String s = lines[j]; s = replaceAllTags(s); // if(!(alignMode == 6 && mc.currentScreen != null && // mc.currentScreen instanceof GuiChat)) //if chat is open, don't display bottomleft info mc.fontRenderer.drawStringWithShadow(s, getX(mc.fontRenderer.getStringWidth(HUDUtils.stripCtrl(s))), getY(rowCount[alignMode], rowNum[alignMode]), 0xffffff); rowNum[alignMode]++; } catch (Throwable e) { mc.thePlayer.addChatMessage(String.format("IngameInfo encountered an exception parsing ingameInfo.txt. Check %s for details.", CommonUtils.getLogFileName())); e.printStackTrace(); enabled = false; } } GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); } if (allowUpdateCheck && versionChecker != null) { if (!versionChecker.isCurrentVersion()) for (String msg : versionChecker.getInGameMessage()) mc.thePlayer.addChatMessage(msg); allowUpdateCheck = false; GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); } return true; } private String[] loadText(File file) { ArrayList arraylist = new ArrayList(); Scanner scanner = null; if (!file.exists()) { file = createFile(); } try { scanner = new Scanner(file); } catch (Throwable e) { ModLoader.getLogger().log(Level.WARNING, "Error getting ingameInfo.txt: " + e.getMessage()); e.printStackTrace(); if (scanner != null) scanner.close(); return new String[] { "" }; } while (scanner.hasNextLine()) { arraylist.add(scanner.nextLine()); } scanner.close(); return (String[]) arraylist.toArray(new String[arraylist.size()]); } private File createFile() { File file = new File(CommonUtils.getMinecraftDir(), configPath); if (!file.exists()) file.mkdir(); file = new File(file, fileName); try { file.createNewFile(); PrintWriter out = new PrintWriter(new FileWriter(file)); for (String s : defaultConfig) out.println(s); out.close(); return file; } catch (Throwable exception) { System.err.println("File couldn't be created, aborting mod_ingameInfo!"); } return null; } private int getX(int width) { if (alignMode == 1 || alignMode == 4 || alignMode == 7) return scaledResolution.getScaledWidth() / 2 - width / 2 + xOffset[alignMode]; else if (alignMode == 2 || alignMode == 5 || alignMode == 8) return scaledResolution.getScaledWidth() - width - xOffset[alignMode]; else return xOffset[alignMode]; } private int getY(int rowCount, int rowNum) { if (alignMode == 3 || alignMode == 4 || alignMode == 5) return (scaledResolution.getScaledHeight() / 2) - (rowCount * 10 / 2) + (rowNum * 10) + yOffset[alignMode]; else if (alignMode == 6 || alignMode == 7 || alignMode == 8) return scaledResolution.getScaledHeight() - (rowCount * 10) + (rowNum * 10) - yOffset[alignMode]; else return (rowNum * 10) + yOffset[alignMode]; } private String replaceAllTags(String s) { for (; s.indexOf('<') != -1; s = replaceTags(s)) {} return s.replaceAll("&", "\247"); } private String replaceTags(String s) { int startIndex = s.indexOf('<'); int endIndex = s.indexOf('>'); int openParamIndex = s.indexOf('[', startIndex); if (openParamIndex < endIndex) endIndex = s.indexOf('>', s.indexOf(']', startIndex)); if (startIndex == -1) return s; else if (endIndex == -1) return s.replace("<", ""); else { String s1 = s.substring(startIndex + 1, endIndex); s = s.replace((new StringBuilder()).append("<").append(s1).append(">").toString(), getTag(s1)); return s; } } public String getTag(String s) { Coord coord = new Coord(MathHelper.floor_double(mc.thePlayer.posX), MathHelper.floor_double(mc.thePlayer.posY), MathHelper.floor_double(mc.thePlayer.posZ)); World world = mc.isIntegratedServerRunning() ? mc.getIntegratedServer().worldServerForDimension(mc.thePlayer.dimension) : mc.theWorld; BiomeGenBase biome = world.getBiomeGenForCoords(coord.x, coord.z); Chunk chunk = world.getChunkFromBlockCoords(coord.x, coord.z); /* * ******************************************************************************************************************** * Utility tags */ if (s.toLowerCase().startsWith("max")) { int startIndex = s.indexOf('['); int endIndex = s.indexOf('[', startIndex + 1); int divIndex = s.indexOf('/'); if (s.indexOf('[') == -1 || endIndex == -1 || endIndex < divIndex) return "(ERROR: Incorrect syntax in MAX tag)"; else { try { float val1 = Float.valueOf(getTag(s.substring(startIndex + 1, divIndex).replace("<", "").replace(">", ""))); float val2 = Float.valueOf(getTag(s.substring(divIndex + 1, endIndex).replace("<", "").replace(">", ""))); return parseBoolean(s.substring(endIndex), val1 >= val2); } catch (NumberFormatException e) { return "(MAX tag: NumberFormatException: '" + s.substring(startIndex + 1, divIndex) + "', '" + s.substring(divIndex + 1, endIndex) + "')"; } } } if (s.toLowerCase().startsWith("pct")) { try { float value = Float.valueOf(getTag(s.substring(s.indexOf('(') + 1, s.indexOf(',')).replace("<", "").replace(">", ""))); float pct = Float.valueOf(getTag(s.substring(s.indexOf(',') + 1, s.indexOf(')')).replace("<", "").replace(">", ""))) / 100F; return String.valueOf(MathHelper.floor_double(value * pct)); } catch (NumberFormatException e) { return "(PCT tag: NumberFormatException: '" + s + "')"; } } /* * ******************************************************************************************************************** * Alignment tags */ if (s.equalsIgnoreCase("left") || s.equalsIgnoreCase("topleft")) { alignMode = 0; return ""; } if (s.equalsIgnoreCase("center") || s.equalsIgnoreCase("topcenter")) { alignMode = 1; return ""; } if (s.equalsIgnoreCase("right") || s.equalsIgnoreCase("topright")) { alignMode = 2; return ""; } if (s.equalsIgnoreCase("middleleft")) { alignMode = 3; return ""; } if (s.equalsIgnoreCase("middlecenter")) { alignMode = 4; return ""; } if (s.equalsIgnoreCase("middleright")) { alignMode = 5; return ""; } if (s.equalsIgnoreCase("bottomleft")) { alignMode = 6; return ""; } if (s.equalsIgnoreCase("bottomcenter")) { alignMode = 7; return ""; } if (s.equalsIgnoreCase("bottomright")) { alignMode = 8; return ""; } /* * ******************************************************************************************************************** * Color tags */ if (s.equalsIgnoreCase("black")) { return "\2470"; } if (s.equalsIgnoreCase("darkblue") || s.equalsIgnoreCase("navy")) { return "\2471"; } if (s.equalsIgnoreCase("darkgreen") || s.equalsIgnoreCase("green")) { return "\2472"; } if (s.equalsIgnoreCase("darkaqua") || s.equalsIgnoreCase("darkcyan") || s.equalsIgnoreCase("turquoise")) { return "\2473"; } if (s.equalsIgnoreCase("darkred")) { return "\2474"; } if (s.equalsIgnoreCase("purple") || s.equalsIgnoreCase("violet")) { return "\2475"; } if (s.equalsIgnoreCase("orange") || s.equalsIgnoreCase("gold")) { return "\2476"; } if (s.equalsIgnoreCase("lightgrey") || s.equalsIgnoreCase("lightgray") || s.equalsIgnoreCase("grey") || s.equalsIgnoreCase("gray")) { return "\2477"; } if (s.equalsIgnoreCase("darkgrey") || s.equalsIgnoreCase("darkgray") || s.equalsIgnoreCase("charcoal")) { return "\2478"; } if (s.equalsIgnoreCase("indigo") || s.equalsIgnoreCase("blue") || s.equalsIgnoreCase("lightblue")) { return "\2479"; } if (s.equalsIgnoreCase("brightgreen") || s.equalsIgnoreCase("lightgreen") || s.equalsIgnoreCase("lime")) { return "\247a"; } if (s.equalsIgnoreCase("aqua") || s.equalsIgnoreCase("lightcyan") || s.equalsIgnoreCase("celeste") || s.equalsIgnoreCase("diamond")) { return "\247b"; } if (s.equalsIgnoreCase("red") || s.equalsIgnoreCase("lightred") || s.equalsIgnoreCase("salmon")) { return "\247c"; } if (s.equalsIgnoreCase("pink") || s.equalsIgnoreCase("magenta")) { return "\247d"; } if (s.equalsIgnoreCase("yellow")) { return "\247e"; } if (s.equalsIgnoreCase("white")) { return "\247f"; } /* * ******************************************************************************************************************** * Formatting tags */ if (s.equalsIgnoreCase("random")) { return "\247k"; } if (s.equalsIgnoreCase("bold") || s.equalsIgnoreCase("b")) { return "\247l"; } if (s.equalsIgnoreCase("strikethrough") || s.equalsIgnoreCase("strike") || s.equalsIgnoreCase("s")) { return "\247m"; } if (s.equalsIgnoreCase("underline") || s.equalsIgnoreCase("u")) { return "\247n"; } if (s.equalsIgnoreCase("italic") || s.equalsIgnoreCase("italics") || s.equalsIgnoreCase("i")) { return "\247o"; } if (s.equalsIgnoreCase("reset") || s.equalsIgnoreCase("r")) { return "\247r"; } /* * ******************************************************************************************************************** * World tags */ if (s.toLowerCase().startsWith("irltime") || s.toLowerCase().startsWith("rltime")) { int startIndex = s.indexOf('['); int endIndex = s.indexOf(']', startIndex + 1); String fmt = ""; if (startIndex != -1 && endIndex != -1) fmt = s.substring(startIndex + 1, endIndex); if (fmt.equals("")) fmt = "hh:mma"; return new SimpleDateFormat(fmt).format(new Date()); } if (s.toLowerCase().startsWith("mctime")) { int startIndex = s.indexOf('['); int endIndex = s.indexOf(']', startIndex + 1); long fmt = 12L; if (startIndex != -1 && endIndex != -1 && s.substring(startIndex + 1, endIndex).equals("24")) fmt = 24L; return CommonUtils.getMCTimeString(mc.theWorld.getWorldTime(), fmt); } if (s.equalsIgnoreCase("day")) { try { return Integer.toString((int) world.getWorldInfo().getWorldTime() / 24000); } catch (Throwable e) { return "0"; } } if (s.equalsIgnoreCase("biome")) { try { return biome.biomeName; } catch (Throwable e) { return "&onull"; } } if (s.equalsIgnoreCase("dimension")) { // return mc.thePlayer.dimension == -1 ? "Nether" : mc.thePlayer.dimension == 1 ? "The End" : "Overworld"; return mc.theWorld.provider.getDimensionName(); } if (s.toLowerCase().startsWith("daytime")) { return parseBoolean(s, Boolean.valueOf(world.calculateSkylightSubtracted(1.0F) < 4)); } if (s.toLowerCase().startsWith("raining")) { return parseBoolean(s, Boolean.valueOf(world.isRaining() && biome.canSpawnLightningBolt())); } if (s.toLowerCase().startsWith("snowing")) { return parseBoolean(s, Boolean.valueOf(world.isRaining() && !biome.canSpawnLightningBolt() && !biome.equals(BiomeGenBase.desert) && !biome.equals(BiomeGenBase.desertHills))); } if (s.equalsIgnoreCase("nextrain")) { return CommonUtils.ticksToTimeString(world.getWorldInfo().getRainTime()); } if (s.toLowerCase().startsWith("thundering")) { return parseBoolean(s, Boolean.valueOf(world.getWorldInfo().isThundering() && biome.canSpawnLightningBolt())); } if (s.toLowerCase().startsWith("slimes")) { return parseBoolean(s, Boolean.valueOf(chunk.getRandomWithSeed(987234911L).nextInt(10) == 0)); } if (s.toLowerCase().startsWith("hardcore")) { return parseBoolean(s, Boolean.valueOf(world.getWorldInfo().isHardcoreModeEnabled())); } if (s.equalsIgnoreCase("light")) { try { return Integer.toString(chunk.getBlockLightValue(coord.x & 0xf, coord.y, coord.z & 0xf, world.calculateSkylightSubtracted(1.0F))); } catch (Throwable e) { return "0"; } } if (s.equalsIgnoreCase("lightfeet")) { try { return Integer.toString(chunk.getBlockLightValue(coord.x & 0xf, (int) Math.round(mc.thePlayer.boundingBox.minY), coord.z & 0xf, world.calculateSkylightSubtracted(1.0F))); } catch (Throwable e) { return "0"; } } if (s.equalsIgnoreCase("lightnosun")) { try { return Integer.toString(chunk.getSavedLightValue(EnumSkyBlock.Block, coord.x & 0xf, coord.y, coord.z & 0xf)); } catch (Throwable e) { return "0"; } } if (s.equalsIgnoreCase("lightnosunfeet")) { try { return Integer.toString(chunk.getSavedLightValue(EnumSkyBlock.Block, coord.x & 0xf, (int) Math.round(mc.thePlayer.boundingBox.minY), coord.z & 0xf)); } catch (Throwable e) { return "0"; } } if (s.equalsIgnoreCase("x") || s.equalsIgnoreCase("xi")) { return Integer.toString(coord.x); } if (s.equalsIgnoreCase("y") || s.equalsIgnoreCase("yi")) { return Integer.toString(coord.y); } if (s.equalsIgnoreCase("yfeet") || s.equalsIgnoreCase("yfeeti")) { return Integer.toString((int) Math.round(mc.thePlayer.boundingBox.minY)); } if (s.equalsIgnoreCase("z") || s.equalsIgnoreCase("zi")) { return Integer.toString(coord.z); } if (s.equalsIgnoreCase("decx")) { return Double.toString(Math.round(mc.thePlayer.posX * 10.0) / 10.0); } if (s.equalsIgnoreCase("decy")) { return Double.toString(Math.round(mc.thePlayer.posY * 10.0) / 10.0); } if (s.equalsIgnoreCase("decyfeet")) { return Double.toString(Math.round(mc.thePlayer.boundingBox.minY * 10.0) / 10.0); } if (s.equalsIgnoreCase("decz")) { return Double.toString(Math.round(mc.thePlayer.posZ * 10.0) / 10.0); } if (s.equalsIgnoreCase("worldname")) { try { return world.getWorldInfo().getWorldName(); } catch (Throwable e) { return "&onull"; } } if (s.equalsIgnoreCase("worldsize")) { try { return Long.toString(world.getWorldInfo().getSizeOnDisk()); } catch (Throwable e) { return "&onull"; } } if (s.equalsIgnoreCase("worldsizemb")) { try { return Float.toString((((world.getWorldInfo().getSizeOnDisk() / 1024L) * 100L) / 1024L) / 100F); } catch (Throwable e) { return "&onull"; } } if (s.equalsIgnoreCase("seed")) { try { return mc.isIntegratedServerRunning() ? Long.toString(world.getSeed()) : "&onull"; } catch (Throwable e) { return "&onull"; } } if (s.equalsIgnoreCase("roughdirection")) { try { switch (MathHelper.floor_double(((mc.thePlayer.rotationYaw * 4F) / 360F) + 0.5D) & 3) { case 0: return "South"; case 1: return "West"; case 2: return "North"; case 3: return "East"; } } catch (Throwable e) { return "&onull"; } } if (s.equalsIgnoreCase("finedirection")) { try { switch (MathHelper.floor_double(((mc.thePlayer.rotationYaw * 8F) / 360F) + 0.5D) & 7) { case 0: return "South"; case 1: return "South West"; case 2: return "West"; case 3: return "North West"; case 4: return "North"; case 5: return "North East"; case 6: return "East"; case 7: return "South East"; } } catch (Throwable e) { return "&onull"; } } if (s.equalsIgnoreCase("abrroughdirection")) { try { switch (MathHelper.floor_double(((mc.thePlayer.rotationYaw * 4F) / 360F) + 0.5D) & 3) { case 0: return "S"; case 1: return "W"; case 2: return "N"; case 3: return "E"; } } catch (Throwable e) { return "&onull"; } } if (s.equalsIgnoreCase("abrfinedirection")) { try { switch (MathHelper.floor_double(((mc.thePlayer.rotationYaw * 8F) / 360F) + 0.5D) & 7) { case 0: return "S"; case 1: return "SW"; case 2: return "W"; case 3: return "NW"; case 4: return "N"; case 5: return "NE"; case 6: return "E"; case 7: return "SE"; } } catch (Throwable e) { return "&onull"; } } if (s.equalsIgnoreCase("directionhud")) { try { int direction = MathHelper.floor_double(((mc.thePlayer.rotationYaw * 16F) / 360F) + 0.5D) & 15; if (direction == 0) return "SE &cS &f SW"; if (direction == 1) return " S SW "; if (direction == 2) return "S &cSW&f W"; if (direction == 3) return " SW W "; if (direction == 4) return "SW &cW &f NW"; if (direction == 5) return " W NW "; if (direction == 6) return "W &cNW&f N"; if (direction == 7) return " NW N "; if (direction == 8) return "NW &cN &f NE"; if (direction == 9) return " N NE "; if (direction == 10) return "N &cNE&f E"; if (direction == 11) return " NE E "; if (direction == 12) return "NE &cE &f SE"; if (direction == 13) return " E SE "; if (direction == 14) return "E &cSE&f S"; if (direction == 15) return " SE S "; else return "this shit isn't working"; } catch (Throwable e) { return "&onull"; } } /* * ******************************************************************************************************************** * Debug tags */ if (s.equalsIgnoreCase("fps")) { try { return mc.debug.substring(0, mc.debug.indexOf(" fps")); } catch (Throwable e) { return "0"; } } if (s.equalsIgnoreCase("entitiesrendered")) { try { String str = mc.getEntityDebug(); return str.substring(str.indexOf(' ') + 1, str.indexOf('/')); } catch (Throwable e) { return "&onull"; } } if (s.equalsIgnoreCase("entitiestotal")) { try { String str = mc.getEntityDebug(); return str.substring(str.indexOf('/') + 1, str.indexOf('.')); } catch (Throwable e) { return "&onull"; } } if (s.equalsIgnoreCase("memtotal")) { try { if (memoryUnit.equalsIgnoreCase("KB")) return Long.toString(Runtime.getRuntime().totalMemory() / 1024L) + memoryUnit; if (memoryUnit.equalsIgnoreCase("MB")) return Long.toString(Runtime.getRuntime().totalMemory() / 1024L / 1024L) + memoryUnit; if (memoryUnit.equalsIgnoreCase("GB")) return Long.toString(Runtime.getRuntime().totalMemory() / 1024L / 1024L / 1024L) + memoryUnit; } catch (Throwable e) { return "&onull"; } } if (s.equalsIgnoreCase("memmax")) { try { if (memoryUnit.equalsIgnoreCase("KB")) return Long.toString(Runtime.getRuntime().maxMemory() / 1024L) + memoryUnit; if (memoryUnit.equalsIgnoreCase("MB")) return Long.toString(Runtime.getRuntime().maxMemory() / 1024L / 1024L) + memoryUnit; if (memoryUnit.equalsIgnoreCase("GB")) return Long.toString(Runtime.getRuntime().maxMemory() / 1024L / 1024L / 1024L) + memoryUnit; } catch (Throwable e) { return "&onull"; } } if (s.equalsIgnoreCase("memfree")) { try { if (memoryUnit.equalsIgnoreCase("KB")) return Long.toString(Runtime.getRuntime().freeMemory() / 1024L) + memoryUnit; if (memoryUnit.equalsIgnoreCase("MB")) return Long.toString(Runtime.getRuntime().freeMemory() / 1024L / 1024L) + memoryUnit; if (memoryUnit.equalsIgnoreCase("GB")) return Long.toString(Runtime.getRuntime().freeMemory() / 1024L / 1024L / 1024L) + memoryUnit; } catch (Throwable e) { return "&onull"; } } if (s.equalsIgnoreCase("memused")) { try { if (memoryUnit.equalsIgnoreCase("KB")) return Long.toString((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024L) + memoryUnit; if (memoryUnit.equalsIgnoreCase("MB")) return Long.toString((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024L / 1024L) + memoryUnit; if (memoryUnit.equalsIgnoreCase("GB")) return Long.toString((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024L / 1024L / 1024L) + memoryUnit; } catch (Throwable e) { return "&onull"; } } /* * ******************************************************************************************************************** * Player tags */ if (s.equalsIgnoreCase("mouseover")) { MovingObjectPosition objectMouseOver = mc.objectMouseOver; if (objectMouseOver != null) { if (objectMouseOver.typeOfHit == EnumMovingObjectType.ENTITY) { return objectMouseOver.entityHit.getEntityName(); } else if (objectMouseOver.typeOfHit == EnumMovingObjectType.TILE) { Block block = Block.blocksList[world.getBlockId(objectMouseOver.blockX, objectMouseOver.blockY, objectMouseOver.blockZ)]; if (block != null) { ItemStack pickBlock = block.getPickBlock(objectMouseOver, world, objectMouseOver.blockX, objectMouseOver.blockY, objectMouseOver.blockZ); if (pickBlock != null) { return pickBlock.getDisplayName(); } return block.getLocalizedName(); } } } return ""; } if (s.equalsIgnoreCase("mouseoverid")) { MovingObjectPosition objectMouseOver = mc.objectMouseOver; if (objectMouseOver != null) { if (objectMouseOver.typeOfHit == EnumMovingObjectType.ENTITY) { return objectMouseOver.entityHit.entityId + ""; } else if (objectMouseOver.typeOfHit == EnumMovingObjectType.TILE) { BlockID blockID = new BlockID(world, objectMouseOver.blockX, objectMouseOver.blockY, objectMouseOver.blockZ); if (blockID.id != 0) { return blockID.toString(); } } } return ""; } if (s.equalsIgnoreCase("mouseoverpowerweak")) { MovingObjectPosition objectMouseOver = mc.objectMouseOver; if (objectMouseOver != null) { if (objectMouseOver.typeOfHit == EnumMovingObjectType.TILE) { Block block = Block.blocksList[world.getBlockId(objectMouseOver.blockX, objectMouseOver.blockY, objectMouseOver.blockZ)]; if (block != null) { int power = -1; for (int side = 0; side < 6; side++) { power = Math.max(power, block.isProvidingWeakPower(world, objectMouseOver.blockX, objectMouseOver.blockY, objectMouseOver.blockZ, side)); } return Integer.toString(power); } } } return "-1"; } if (s.equalsIgnoreCase("mouseoverpowerstrong")) { MovingObjectPosition objectMouseOver = mc.objectMouseOver; if (objectMouseOver != null) { if (objectMouseOver.typeOfHit == EnumMovingObjectType.TILE) { Block block = Block.blocksList[world.getBlockId(objectMouseOver.blockX, objectMouseOver.blockY, objectMouseOver.blockZ)]; if (block != null) { int power = -1; for (int side = 0; side < 6; side++) { power = Math.max(power, block.isProvidingStrongPower(world, objectMouseOver.blockX, objectMouseOver.blockY, objectMouseOver.blockZ, side)); } return Integer.toString(power); } } } return "-1"; } if (s.equalsIgnoreCase("mouseoverpowerinput")) { MovingObjectPosition objectMouseOver = mc.objectMouseOver; if (objectMouseOver != null) { if (objectMouseOver.typeOfHit == EnumMovingObjectType.TILE) { return Integer.toString(world.getBlockPowerInput(objectMouseOver.blockX, objectMouseOver.blockY, objectMouseOver.blockZ)); } } return "-1"; } if (s.equalsIgnoreCase("underwater") || s.equalsIgnoreCase("inwater")) { return Boolean.toString(mc.thePlayer.isInWater()); } if (s.equalsIgnoreCase("wet")) { return Boolean.toString(mc.thePlayer.isWet()); } if (s.equalsIgnoreCase("alive")) { return Boolean.toString(mc.thePlayer.isEntityAlive()); } if (s.equalsIgnoreCase("burning")) { return Boolean.toString(mc.thePlayer.isBurning()); } if (s.equalsIgnoreCase("riding")) { return Boolean.toString(mc.thePlayer.isRiding()); } if (s.equalsIgnoreCase("sneaking")) { return Boolean.toString(mc.thePlayer.isSneaking()); } if (s.equalsIgnoreCase("sprinting")) { return Boolean.toString(mc.thePlayer.isSprinting()); } if (s.equalsIgnoreCase("invisible")) { return Boolean.toString(mc.thePlayer.isInvisible()); } if (s.equalsIgnoreCase("eating")) { return Boolean.toString(mc.thePlayer.isEating()); } if (s.equalsIgnoreCase("invulnerable")) { return Boolean.toString(mc.thePlayer.isEntityInvulnerable()); } if (s.equalsIgnoreCase("gamemode")) { try { if (mc.thePlayer.capabilities.isCreativeMode) return "Creative"; else if (world.getWorldInfo().getGameType().equals(EnumGameType.SURVIVAL)) return "Survival"; else if (world.getWorldInfo().getGameType().equals(EnumGameType.CREATIVE)) return "Creative/Survival?"; else if (world.getWorldInfo().getGameType().equals(EnumGameType.ADVENTURE)) return "Adventure"; else return "???"; } catch (Throwable e) { return "&onull"; } } if (s.equalsIgnoreCase("score")) { try { return Integer.toString(mc.thePlayer.getScore()); } catch (Throwable e) { return "0"; } } if (s.equalsIgnoreCase("difficulty")) { if (mc.gameSettings.difficulty == 0) return "Peaceful"; else if (mc.gameSettings.difficulty == 1) return "Easy"; else if (mc.gameSettings.difficulty == 2) return "Normal"; else if (mc.gameSettings.difficulty == 3) return "Hard"; } if (s.equalsIgnoreCase("playerlevel")) { return Integer.toString(mc.thePlayer.experienceLevel); } if (s.equalsIgnoreCase("xpthislevel")) { return Integer.toString((int) Math.ceil(mc.thePlayer.experience * mc.thePlayer.xpBarCap())); } if (s.equalsIgnoreCase("xpuntilnext")) { return Integer.toString((int) ((1.0F - mc.thePlayer.experience) * mc.thePlayer.xpBarCap())); } if (s.equalsIgnoreCase("xpcap")) { return Integer.toString(mc.thePlayer.xpBarCap()); } if (s.equalsIgnoreCase("username")) { return mc.thePlayer.username; } if (s.equalsIgnoreCase("texturepack")) { return mc.gameSettings.skin; } if (s.toLowerCase().startsWith("itemquantity")) { int startIndex = s.indexOf('['); int endIndex = s.indexOf(']', startIndex + 1); if (startIndex != -1 && endIndex != -1) { String ss = s.substring(startIndex + 1, endIndex).trim(); String[] sa = ss.split(","); int id = CommonUtils.parseInt(sa[0].trim()); int md = -1; if (sa.length > 1) md = CommonUtils.parseInt(sa[1].trim()); return HUDUtils.countInInventory(mc.thePlayer, id, md) + ""; } return "itemquantity syntax error"; } ItemStack itemStack = mc.thePlayer.getCurrentEquippedItem(); - Item item = itemStack.getItem(); if (s.equalsIgnoreCase("equippedquantity")) { if (itemStack != null) { - return Integer.toString(HUDUtils.countInInventory(mc.thePlayer, itemStack.itemID, itemStack.getItemDamage())); + Item item = itemStack.getItem(); + if (isForgeEnv) + return Integer.toString(HUDUtils.countInInventory(mc.thePlayer, itemStack.itemID, item.getDamage(itemStack))); + else + return Integer.toString(HUDUtils.countInInventory(mc.thePlayer, itemStack.itemID, itemStack.getItemDamage())); } return "0"; } if (s.matches("(equipped|helmet|chestplate|leggings|boots)(name|maxdamage|damage|damageleft)")) { if (s.startsWith("equipped")) { itemStack = mc.thePlayer.getCurrentEquippedItem(); } else { int slot = -1; if (s.startsWith("helmet")) { slot = 3; } else if (s.startsWith("chestplate")) { slot = 2; } else if (s.startsWith("leggings")) { slot = 1; } else if (s.startsWith("boots")) { slot = 0; } itemStack = mc.thePlayer.inventory.armorItemInSlot(slot); } if (itemStack != null) { - item = itemStack.getItem(); + Item item = itemStack.getItem(); if (item != null) { if (s.endsWith("name")) { String arrows = itemStack.itemID == Item.bow.itemID ? " (" + HUDUtils.countInInventory(mc.thePlayer, Item.arrow.itemID, -1) + ")" : ""; return itemStack.getDisplayName() + arrows; } else if (s.endsWith("maxdamage")) { if (isForgeEnv) return Integer.toString(item.isDamageable() ? item.getMaxDamage(itemStack) + 1 : 0); else return Integer.toString(itemStack.isItemStackDamageable() ? itemStack.getMaxDamage() + 1 : 0); } else if (s.endsWith("damage")) { if (isForgeEnv) return Integer.toString(item.isDamageable() ? item.getDamage(itemStack) : 0); else return Integer.toString(itemStack.isItemStackDamageable() ? itemStack.getItemDamage() : 0); } else if (s.endsWith("damageleft")) { if (isForgeEnv) return Integer.toString(item.isDamageable() ? item.getMaxDamage(itemStack) + 1 - item.getDamage(itemStack) : 0); else return Integer.toString(itemStack.isItemStackDamageable() ? (itemStack.getMaxDamage() + 1) - (itemStack.getItemDamage()) : 0); } } } } try { Float.valueOf(s); return s; } catch (Throwable e) { return ""; } } private String parseBoolean(String s, Boolean boolean1) { String s1 = ""; if (s.indexOf('[') == -1 || s.indexOf('/') == -1 || s.indexOf(']') == -1) { return s1; } if (boolean1.booleanValue()) { s1 = s.substring(s.indexOf('[') + 1, s.indexOf('/')); } else { s1 = s.substring(s.indexOf('/') + 1, s.indexOf(']')); } return s1; } public class CommandIGI extends CommandBase { @Override public String getCommandName() { return "igi"; } @Override public String getCommandUsage(ICommandSender icommandsender) { return "commands.igi.usage"; } @Override public void processCommand(ICommandSender icommandsender, String[] args) { if (args.length == 1) { if (args[0].equalsIgnoreCase("reload")) { loadFormatFile(); enabled = true; return; } else if (args[0].equalsIgnoreCase("enable")) { enabled = true; return; } else if (args[0].equalsIgnoreCase("disable")) { enabled = false; return; } else if (args[0].equalsIgnoreCase("toggle")) { enabled = !enabled; return; } } throw new WrongUsageException("commands.igi.usage", new Object[0]); } } }
false
true
public String getTag(String s) { Coord coord = new Coord(MathHelper.floor_double(mc.thePlayer.posX), MathHelper.floor_double(mc.thePlayer.posY), MathHelper.floor_double(mc.thePlayer.posZ)); World world = mc.isIntegratedServerRunning() ? mc.getIntegratedServer().worldServerForDimension(mc.thePlayer.dimension) : mc.theWorld; BiomeGenBase biome = world.getBiomeGenForCoords(coord.x, coord.z); Chunk chunk = world.getChunkFromBlockCoords(coord.x, coord.z); /* * ******************************************************************************************************************** * Utility tags */ if (s.toLowerCase().startsWith("max")) { int startIndex = s.indexOf('['); int endIndex = s.indexOf('[', startIndex + 1); int divIndex = s.indexOf('/'); if (s.indexOf('[') == -1 || endIndex == -1 || endIndex < divIndex) return "(ERROR: Incorrect syntax in MAX tag)"; else { try { float val1 = Float.valueOf(getTag(s.substring(startIndex + 1, divIndex).replace("<", "").replace(">", ""))); float val2 = Float.valueOf(getTag(s.substring(divIndex + 1, endIndex).replace("<", "").replace(">", ""))); return parseBoolean(s.substring(endIndex), val1 >= val2); } catch (NumberFormatException e) { return "(MAX tag: NumberFormatException: '" + s.substring(startIndex + 1, divIndex) + "', '" + s.substring(divIndex + 1, endIndex) + "')"; } } } if (s.toLowerCase().startsWith("pct")) { try { float value = Float.valueOf(getTag(s.substring(s.indexOf('(') + 1, s.indexOf(',')).replace("<", "").replace(">", ""))); float pct = Float.valueOf(getTag(s.substring(s.indexOf(',') + 1, s.indexOf(')')).replace("<", "").replace(">", ""))) / 100F; return String.valueOf(MathHelper.floor_double(value * pct)); } catch (NumberFormatException e) { return "(PCT tag: NumberFormatException: '" + s + "')"; } } /* * ******************************************************************************************************************** * Alignment tags */ if (s.equalsIgnoreCase("left") || s.equalsIgnoreCase("topleft")) { alignMode = 0; return ""; } if (s.equalsIgnoreCase("center") || s.equalsIgnoreCase("topcenter")) { alignMode = 1; return ""; } if (s.equalsIgnoreCase("right") || s.equalsIgnoreCase("topright")) { alignMode = 2; return ""; } if (s.equalsIgnoreCase("middleleft")) { alignMode = 3; return ""; } if (s.equalsIgnoreCase("middlecenter")) { alignMode = 4; return ""; } if (s.equalsIgnoreCase("middleright")) { alignMode = 5; return ""; } if (s.equalsIgnoreCase("bottomleft")) { alignMode = 6; return ""; } if (s.equalsIgnoreCase("bottomcenter")) { alignMode = 7; return ""; } if (s.equalsIgnoreCase("bottomright")) { alignMode = 8; return ""; } /* * ******************************************************************************************************************** * Color tags */ if (s.equalsIgnoreCase("black")) { return "\2470"; } if (s.equalsIgnoreCase("darkblue") || s.equalsIgnoreCase("navy")) { return "\2471"; } if (s.equalsIgnoreCase("darkgreen") || s.equalsIgnoreCase("green")) { return "\2472"; } if (s.equalsIgnoreCase("darkaqua") || s.equalsIgnoreCase("darkcyan") || s.equalsIgnoreCase("turquoise")) { return "\2473"; } if (s.equalsIgnoreCase("darkred")) { return "\2474"; } if (s.equalsIgnoreCase("purple") || s.equalsIgnoreCase("violet")) { return "\2475"; } if (s.equalsIgnoreCase("orange") || s.equalsIgnoreCase("gold")) { return "\2476"; } if (s.equalsIgnoreCase("lightgrey") || s.equalsIgnoreCase("lightgray") || s.equalsIgnoreCase("grey") || s.equalsIgnoreCase("gray")) { return "\2477"; } if (s.equalsIgnoreCase("darkgrey") || s.equalsIgnoreCase("darkgray") || s.equalsIgnoreCase("charcoal")) { return "\2478"; } if (s.equalsIgnoreCase("indigo") || s.equalsIgnoreCase("blue") || s.equalsIgnoreCase("lightblue")) { return "\2479"; } if (s.equalsIgnoreCase("brightgreen") || s.equalsIgnoreCase("lightgreen") || s.equalsIgnoreCase("lime")) { return "\247a"; } if (s.equalsIgnoreCase("aqua") || s.equalsIgnoreCase("lightcyan") || s.equalsIgnoreCase("celeste") || s.equalsIgnoreCase("diamond")) { return "\247b"; } if (s.equalsIgnoreCase("red") || s.equalsIgnoreCase("lightred") || s.equalsIgnoreCase("salmon")) { return "\247c"; } if (s.equalsIgnoreCase("pink") || s.equalsIgnoreCase("magenta")) { return "\247d"; } if (s.equalsIgnoreCase("yellow")) { return "\247e"; } if (s.equalsIgnoreCase("white")) { return "\247f"; } /* * ******************************************************************************************************************** * Formatting tags */ if (s.equalsIgnoreCase("random")) { return "\247k"; } if (s.equalsIgnoreCase("bold") || s.equalsIgnoreCase("b")) { return "\247l"; } if (s.equalsIgnoreCase("strikethrough") || s.equalsIgnoreCase("strike") || s.equalsIgnoreCase("s")) { return "\247m"; } if (s.equalsIgnoreCase("underline") || s.equalsIgnoreCase("u")) { return "\247n"; } if (s.equalsIgnoreCase("italic") || s.equalsIgnoreCase("italics") || s.equalsIgnoreCase("i")) { return "\247o"; } if (s.equalsIgnoreCase("reset") || s.equalsIgnoreCase("r")) { return "\247r"; } /* * ******************************************************************************************************************** * World tags */ if (s.toLowerCase().startsWith("irltime") || s.toLowerCase().startsWith("rltime")) { int startIndex = s.indexOf('['); int endIndex = s.indexOf(']', startIndex + 1); String fmt = ""; if (startIndex != -1 && endIndex != -1) fmt = s.substring(startIndex + 1, endIndex); if (fmt.equals("")) fmt = "hh:mma"; return new SimpleDateFormat(fmt).format(new Date()); } if (s.toLowerCase().startsWith("mctime")) { int startIndex = s.indexOf('['); int endIndex = s.indexOf(']', startIndex + 1); long fmt = 12L; if (startIndex != -1 && endIndex != -1 && s.substring(startIndex + 1, endIndex).equals("24")) fmt = 24L; return CommonUtils.getMCTimeString(mc.theWorld.getWorldTime(), fmt); } if (s.equalsIgnoreCase("day")) { try { return Integer.toString((int) world.getWorldInfo().getWorldTime() / 24000); } catch (Throwable e) { return "0"; } } if (s.equalsIgnoreCase("biome")) { try { return biome.biomeName; } catch (Throwable e) { return "&onull"; } } if (s.equalsIgnoreCase("dimension")) { // return mc.thePlayer.dimension == -1 ? "Nether" : mc.thePlayer.dimension == 1 ? "The End" : "Overworld"; return mc.theWorld.provider.getDimensionName(); } if (s.toLowerCase().startsWith("daytime")) { return parseBoolean(s, Boolean.valueOf(world.calculateSkylightSubtracted(1.0F) < 4)); } if (s.toLowerCase().startsWith("raining")) { return parseBoolean(s, Boolean.valueOf(world.isRaining() && biome.canSpawnLightningBolt())); } if (s.toLowerCase().startsWith("snowing")) { return parseBoolean(s, Boolean.valueOf(world.isRaining() && !biome.canSpawnLightningBolt() && !biome.equals(BiomeGenBase.desert) && !biome.equals(BiomeGenBase.desertHills))); } if (s.equalsIgnoreCase("nextrain")) { return CommonUtils.ticksToTimeString(world.getWorldInfo().getRainTime()); } if (s.toLowerCase().startsWith("thundering")) { return parseBoolean(s, Boolean.valueOf(world.getWorldInfo().isThundering() && biome.canSpawnLightningBolt())); } if (s.toLowerCase().startsWith("slimes")) { return parseBoolean(s, Boolean.valueOf(chunk.getRandomWithSeed(987234911L).nextInt(10) == 0)); } if (s.toLowerCase().startsWith("hardcore")) { return parseBoolean(s, Boolean.valueOf(world.getWorldInfo().isHardcoreModeEnabled())); } if (s.equalsIgnoreCase("light")) { try { return Integer.toString(chunk.getBlockLightValue(coord.x & 0xf, coord.y, coord.z & 0xf, world.calculateSkylightSubtracted(1.0F))); } catch (Throwable e) { return "0"; } } if (s.equalsIgnoreCase("lightfeet")) { try { return Integer.toString(chunk.getBlockLightValue(coord.x & 0xf, (int) Math.round(mc.thePlayer.boundingBox.minY), coord.z & 0xf, world.calculateSkylightSubtracted(1.0F))); } catch (Throwable e) { return "0"; } } if (s.equalsIgnoreCase("lightnosun")) { try { return Integer.toString(chunk.getSavedLightValue(EnumSkyBlock.Block, coord.x & 0xf, coord.y, coord.z & 0xf)); } catch (Throwable e) { return "0"; } } if (s.equalsIgnoreCase("lightnosunfeet")) { try { return Integer.toString(chunk.getSavedLightValue(EnumSkyBlock.Block, coord.x & 0xf, (int) Math.round(mc.thePlayer.boundingBox.minY), coord.z & 0xf)); } catch (Throwable e) { return "0"; } } if (s.equalsIgnoreCase("x") || s.equalsIgnoreCase("xi")) { return Integer.toString(coord.x); } if (s.equalsIgnoreCase("y") || s.equalsIgnoreCase("yi")) { return Integer.toString(coord.y); } if (s.equalsIgnoreCase("yfeet") || s.equalsIgnoreCase("yfeeti")) { return Integer.toString((int) Math.round(mc.thePlayer.boundingBox.minY)); } if (s.equalsIgnoreCase("z") || s.equalsIgnoreCase("zi")) { return Integer.toString(coord.z); } if (s.equalsIgnoreCase("decx")) { return Double.toString(Math.round(mc.thePlayer.posX * 10.0) / 10.0); } if (s.equalsIgnoreCase("decy")) { return Double.toString(Math.round(mc.thePlayer.posY * 10.0) / 10.0); } if (s.equalsIgnoreCase("decyfeet")) { return Double.toString(Math.round(mc.thePlayer.boundingBox.minY * 10.0) / 10.0); } if (s.equalsIgnoreCase("decz")) { return Double.toString(Math.round(mc.thePlayer.posZ * 10.0) / 10.0); } if (s.equalsIgnoreCase("worldname")) { try { return world.getWorldInfo().getWorldName(); } catch (Throwable e) { return "&onull"; } } if (s.equalsIgnoreCase("worldsize")) { try { return Long.toString(world.getWorldInfo().getSizeOnDisk()); } catch (Throwable e) { return "&onull"; } } if (s.equalsIgnoreCase("worldsizemb")) { try { return Float.toString((((world.getWorldInfo().getSizeOnDisk() / 1024L) * 100L) / 1024L) / 100F); } catch (Throwable e) { return "&onull"; } } if (s.equalsIgnoreCase("seed")) { try { return mc.isIntegratedServerRunning() ? Long.toString(world.getSeed()) : "&onull"; } catch (Throwable e) { return "&onull"; } } if (s.equalsIgnoreCase("roughdirection")) { try { switch (MathHelper.floor_double(((mc.thePlayer.rotationYaw * 4F) / 360F) + 0.5D) & 3) { case 0: return "South"; case 1: return "West"; case 2: return "North"; case 3: return "East"; } } catch (Throwable e) { return "&onull"; } } if (s.equalsIgnoreCase("finedirection")) { try { switch (MathHelper.floor_double(((mc.thePlayer.rotationYaw * 8F) / 360F) + 0.5D) & 7) { case 0: return "South"; case 1: return "South West"; case 2: return "West"; case 3: return "North West"; case 4: return "North"; case 5: return "North East"; case 6: return "East"; case 7: return "South East"; } } catch (Throwable e) { return "&onull"; } } if (s.equalsIgnoreCase("abrroughdirection")) { try { switch (MathHelper.floor_double(((mc.thePlayer.rotationYaw * 4F) / 360F) + 0.5D) & 3) { case 0: return "S"; case 1: return "W"; case 2: return "N"; case 3: return "E"; } } catch (Throwable e) { return "&onull"; } } if (s.equalsIgnoreCase("abrfinedirection")) { try { switch (MathHelper.floor_double(((mc.thePlayer.rotationYaw * 8F) / 360F) + 0.5D) & 7) { case 0: return "S"; case 1: return "SW"; case 2: return "W"; case 3: return "NW"; case 4: return "N"; case 5: return "NE"; case 6: return "E"; case 7: return "SE"; } } catch (Throwable e) { return "&onull"; } } if (s.equalsIgnoreCase("directionhud")) { try { int direction = MathHelper.floor_double(((mc.thePlayer.rotationYaw * 16F) / 360F) + 0.5D) & 15; if (direction == 0) return "SE &cS &f SW"; if (direction == 1) return " S SW "; if (direction == 2) return "S &cSW&f W"; if (direction == 3) return " SW W "; if (direction == 4) return "SW &cW &f NW"; if (direction == 5) return " W NW "; if (direction == 6) return "W &cNW&f N"; if (direction == 7) return " NW N "; if (direction == 8) return "NW &cN &f NE"; if (direction == 9) return " N NE "; if (direction == 10) return "N &cNE&f E"; if (direction == 11) return " NE E "; if (direction == 12) return "NE &cE &f SE"; if (direction == 13) return " E SE "; if (direction == 14) return "E &cSE&f S"; if (direction == 15) return " SE S "; else return "this shit isn't working"; } catch (Throwable e) { return "&onull"; } } /* * ******************************************************************************************************************** * Debug tags */ if (s.equalsIgnoreCase("fps")) { try { return mc.debug.substring(0, mc.debug.indexOf(" fps")); } catch (Throwable e) { return "0"; } } if (s.equalsIgnoreCase("entitiesrendered")) { try { String str = mc.getEntityDebug(); return str.substring(str.indexOf(' ') + 1, str.indexOf('/')); } catch (Throwable e) { return "&onull"; } } if (s.equalsIgnoreCase("entitiestotal")) { try { String str = mc.getEntityDebug(); return str.substring(str.indexOf('/') + 1, str.indexOf('.')); } catch (Throwable e) { return "&onull"; } } if (s.equalsIgnoreCase("memtotal")) { try { if (memoryUnit.equalsIgnoreCase("KB")) return Long.toString(Runtime.getRuntime().totalMemory() / 1024L) + memoryUnit; if (memoryUnit.equalsIgnoreCase("MB")) return Long.toString(Runtime.getRuntime().totalMemory() / 1024L / 1024L) + memoryUnit; if (memoryUnit.equalsIgnoreCase("GB")) return Long.toString(Runtime.getRuntime().totalMemory() / 1024L / 1024L / 1024L) + memoryUnit; } catch (Throwable e) { return "&onull"; } } if (s.equalsIgnoreCase("memmax")) { try { if (memoryUnit.equalsIgnoreCase("KB")) return Long.toString(Runtime.getRuntime().maxMemory() / 1024L) + memoryUnit; if (memoryUnit.equalsIgnoreCase("MB")) return Long.toString(Runtime.getRuntime().maxMemory() / 1024L / 1024L) + memoryUnit; if (memoryUnit.equalsIgnoreCase("GB")) return Long.toString(Runtime.getRuntime().maxMemory() / 1024L / 1024L / 1024L) + memoryUnit; } catch (Throwable e) { return "&onull"; } } if (s.equalsIgnoreCase("memfree")) { try { if (memoryUnit.equalsIgnoreCase("KB")) return Long.toString(Runtime.getRuntime().freeMemory() / 1024L) + memoryUnit; if (memoryUnit.equalsIgnoreCase("MB")) return Long.toString(Runtime.getRuntime().freeMemory() / 1024L / 1024L) + memoryUnit; if (memoryUnit.equalsIgnoreCase("GB")) return Long.toString(Runtime.getRuntime().freeMemory() / 1024L / 1024L / 1024L) + memoryUnit; } catch (Throwable e) { return "&onull"; } } if (s.equalsIgnoreCase("memused")) { try { if (memoryUnit.equalsIgnoreCase("KB")) return Long.toString((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024L) + memoryUnit; if (memoryUnit.equalsIgnoreCase("MB")) return Long.toString((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024L / 1024L) + memoryUnit; if (memoryUnit.equalsIgnoreCase("GB")) return Long.toString((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024L / 1024L / 1024L) + memoryUnit; } catch (Throwable e) { return "&onull"; } } /* * ******************************************************************************************************************** * Player tags */ if (s.equalsIgnoreCase("mouseover")) { MovingObjectPosition objectMouseOver = mc.objectMouseOver; if (objectMouseOver != null) { if (objectMouseOver.typeOfHit == EnumMovingObjectType.ENTITY) { return objectMouseOver.entityHit.getEntityName(); } else if (objectMouseOver.typeOfHit == EnumMovingObjectType.TILE) { Block block = Block.blocksList[world.getBlockId(objectMouseOver.blockX, objectMouseOver.blockY, objectMouseOver.blockZ)]; if (block != null) { ItemStack pickBlock = block.getPickBlock(objectMouseOver, world, objectMouseOver.blockX, objectMouseOver.blockY, objectMouseOver.blockZ); if (pickBlock != null) { return pickBlock.getDisplayName(); } return block.getLocalizedName(); } } } return ""; } if (s.equalsIgnoreCase("mouseoverid")) { MovingObjectPosition objectMouseOver = mc.objectMouseOver; if (objectMouseOver != null) { if (objectMouseOver.typeOfHit == EnumMovingObjectType.ENTITY) { return objectMouseOver.entityHit.entityId + ""; } else if (objectMouseOver.typeOfHit == EnumMovingObjectType.TILE) { BlockID blockID = new BlockID(world, objectMouseOver.blockX, objectMouseOver.blockY, objectMouseOver.blockZ); if (blockID.id != 0) { return blockID.toString(); } } } return ""; } if (s.equalsIgnoreCase("mouseoverpowerweak")) { MovingObjectPosition objectMouseOver = mc.objectMouseOver; if (objectMouseOver != null) { if (objectMouseOver.typeOfHit == EnumMovingObjectType.TILE) { Block block = Block.blocksList[world.getBlockId(objectMouseOver.blockX, objectMouseOver.blockY, objectMouseOver.blockZ)]; if (block != null) { int power = -1; for (int side = 0; side < 6; side++) { power = Math.max(power, block.isProvidingWeakPower(world, objectMouseOver.blockX, objectMouseOver.blockY, objectMouseOver.blockZ, side)); } return Integer.toString(power); } } } return "-1"; } if (s.equalsIgnoreCase("mouseoverpowerstrong")) { MovingObjectPosition objectMouseOver = mc.objectMouseOver; if (objectMouseOver != null) { if (objectMouseOver.typeOfHit == EnumMovingObjectType.TILE) { Block block = Block.blocksList[world.getBlockId(objectMouseOver.blockX, objectMouseOver.blockY, objectMouseOver.blockZ)]; if (block != null) { int power = -1; for (int side = 0; side < 6; side++) { power = Math.max(power, block.isProvidingStrongPower(world, objectMouseOver.blockX, objectMouseOver.blockY, objectMouseOver.blockZ, side)); } return Integer.toString(power); } } } return "-1"; } if (s.equalsIgnoreCase("mouseoverpowerinput")) { MovingObjectPosition objectMouseOver = mc.objectMouseOver; if (objectMouseOver != null) { if (objectMouseOver.typeOfHit == EnumMovingObjectType.TILE) { return Integer.toString(world.getBlockPowerInput(objectMouseOver.blockX, objectMouseOver.blockY, objectMouseOver.blockZ)); } } return "-1"; } if (s.equalsIgnoreCase("underwater") || s.equalsIgnoreCase("inwater")) { return Boolean.toString(mc.thePlayer.isInWater()); } if (s.equalsIgnoreCase("wet")) { return Boolean.toString(mc.thePlayer.isWet()); } if (s.equalsIgnoreCase("alive")) { return Boolean.toString(mc.thePlayer.isEntityAlive()); } if (s.equalsIgnoreCase("burning")) { return Boolean.toString(mc.thePlayer.isBurning()); } if (s.equalsIgnoreCase("riding")) { return Boolean.toString(mc.thePlayer.isRiding()); } if (s.equalsIgnoreCase("sneaking")) { return Boolean.toString(mc.thePlayer.isSneaking()); } if (s.equalsIgnoreCase("sprinting")) { return Boolean.toString(mc.thePlayer.isSprinting()); } if (s.equalsIgnoreCase("invisible")) { return Boolean.toString(mc.thePlayer.isInvisible()); } if (s.equalsIgnoreCase("eating")) { return Boolean.toString(mc.thePlayer.isEating()); } if (s.equalsIgnoreCase("invulnerable")) { return Boolean.toString(mc.thePlayer.isEntityInvulnerable()); } if (s.equalsIgnoreCase("gamemode")) { try { if (mc.thePlayer.capabilities.isCreativeMode) return "Creative"; else if (world.getWorldInfo().getGameType().equals(EnumGameType.SURVIVAL)) return "Survival"; else if (world.getWorldInfo().getGameType().equals(EnumGameType.CREATIVE)) return "Creative/Survival?"; else if (world.getWorldInfo().getGameType().equals(EnumGameType.ADVENTURE)) return "Adventure"; else return "???"; } catch (Throwable e) { return "&onull"; } } if (s.equalsIgnoreCase("score")) { try { return Integer.toString(mc.thePlayer.getScore()); } catch (Throwable e) { return "0"; } } if (s.equalsIgnoreCase("difficulty")) { if (mc.gameSettings.difficulty == 0) return "Peaceful"; else if (mc.gameSettings.difficulty == 1) return "Easy"; else if (mc.gameSettings.difficulty == 2) return "Normal"; else if (mc.gameSettings.difficulty == 3) return "Hard"; } if (s.equalsIgnoreCase("playerlevel")) { return Integer.toString(mc.thePlayer.experienceLevel); } if (s.equalsIgnoreCase("xpthislevel")) { return Integer.toString((int) Math.ceil(mc.thePlayer.experience * mc.thePlayer.xpBarCap())); } if (s.equalsIgnoreCase("xpuntilnext")) { return Integer.toString((int) ((1.0F - mc.thePlayer.experience) * mc.thePlayer.xpBarCap())); } if (s.equalsIgnoreCase("xpcap")) { return Integer.toString(mc.thePlayer.xpBarCap()); } if (s.equalsIgnoreCase("username")) { return mc.thePlayer.username; } if (s.equalsIgnoreCase("texturepack")) { return mc.gameSettings.skin; } if (s.toLowerCase().startsWith("itemquantity")) { int startIndex = s.indexOf('['); int endIndex = s.indexOf(']', startIndex + 1); if (startIndex != -1 && endIndex != -1) { String ss = s.substring(startIndex + 1, endIndex).trim(); String[] sa = ss.split(","); int id = CommonUtils.parseInt(sa[0].trim()); int md = -1; if (sa.length > 1) md = CommonUtils.parseInt(sa[1].trim()); return HUDUtils.countInInventory(mc.thePlayer, id, md) + ""; } return "itemquantity syntax error"; } ItemStack itemStack = mc.thePlayer.getCurrentEquippedItem(); Item item = itemStack.getItem(); if (s.equalsIgnoreCase("equippedquantity")) { if (itemStack != null) { return Integer.toString(HUDUtils.countInInventory(mc.thePlayer, itemStack.itemID, itemStack.getItemDamage())); } return "0"; } if (s.matches("(equipped|helmet|chestplate|leggings|boots)(name|maxdamage|damage|damageleft)")) { if (s.startsWith("equipped")) { itemStack = mc.thePlayer.getCurrentEquippedItem(); } else { int slot = -1; if (s.startsWith("helmet")) { slot = 3; } else if (s.startsWith("chestplate")) { slot = 2; } else if (s.startsWith("leggings")) { slot = 1; } else if (s.startsWith("boots")) { slot = 0; } itemStack = mc.thePlayer.inventory.armorItemInSlot(slot); } if (itemStack != null) { item = itemStack.getItem(); if (item != null) { if (s.endsWith("name")) { String arrows = itemStack.itemID == Item.bow.itemID ? " (" + HUDUtils.countInInventory(mc.thePlayer, Item.arrow.itemID, -1) + ")" : ""; return itemStack.getDisplayName() + arrows; } else if (s.endsWith("maxdamage")) { if (isForgeEnv) return Integer.toString(item.isDamageable() ? item.getMaxDamage(itemStack) + 1 : 0); else return Integer.toString(itemStack.isItemStackDamageable() ? itemStack.getMaxDamage() + 1 : 0); } else if (s.endsWith("damage")) { if (isForgeEnv) return Integer.toString(item.isDamageable() ? item.getDamage(itemStack) : 0); else return Integer.toString(itemStack.isItemStackDamageable() ? itemStack.getItemDamage() : 0); } else if (s.endsWith("damageleft")) { if (isForgeEnv) return Integer.toString(item.isDamageable() ? item.getMaxDamage(itemStack) + 1 - item.getDamage(itemStack) : 0); else return Integer.toString(itemStack.isItemStackDamageable() ? (itemStack.getMaxDamage() + 1) - (itemStack.getItemDamage()) : 0); } } } } try { Float.valueOf(s); return s; } catch (Throwable e) { return ""; } }
public String getTag(String s) { Coord coord = new Coord(MathHelper.floor_double(mc.thePlayer.posX), MathHelper.floor_double(mc.thePlayer.posY), MathHelper.floor_double(mc.thePlayer.posZ)); World world = mc.isIntegratedServerRunning() ? mc.getIntegratedServer().worldServerForDimension(mc.thePlayer.dimension) : mc.theWorld; BiomeGenBase biome = world.getBiomeGenForCoords(coord.x, coord.z); Chunk chunk = world.getChunkFromBlockCoords(coord.x, coord.z); /* * ******************************************************************************************************************** * Utility tags */ if (s.toLowerCase().startsWith("max")) { int startIndex = s.indexOf('['); int endIndex = s.indexOf('[', startIndex + 1); int divIndex = s.indexOf('/'); if (s.indexOf('[') == -1 || endIndex == -1 || endIndex < divIndex) return "(ERROR: Incorrect syntax in MAX tag)"; else { try { float val1 = Float.valueOf(getTag(s.substring(startIndex + 1, divIndex).replace("<", "").replace(">", ""))); float val2 = Float.valueOf(getTag(s.substring(divIndex + 1, endIndex).replace("<", "").replace(">", ""))); return parseBoolean(s.substring(endIndex), val1 >= val2); } catch (NumberFormatException e) { return "(MAX tag: NumberFormatException: '" + s.substring(startIndex + 1, divIndex) + "', '" + s.substring(divIndex + 1, endIndex) + "')"; } } } if (s.toLowerCase().startsWith("pct")) { try { float value = Float.valueOf(getTag(s.substring(s.indexOf('(') + 1, s.indexOf(',')).replace("<", "").replace(">", ""))); float pct = Float.valueOf(getTag(s.substring(s.indexOf(',') + 1, s.indexOf(')')).replace("<", "").replace(">", ""))) / 100F; return String.valueOf(MathHelper.floor_double(value * pct)); } catch (NumberFormatException e) { return "(PCT tag: NumberFormatException: '" + s + "')"; } } /* * ******************************************************************************************************************** * Alignment tags */ if (s.equalsIgnoreCase("left") || s.equalsIgnoreCase("topleft")) { alignMode = 0; return ""; } if (s.equalsIgnoreCase("center") || s.equalsIgnoreCase("topcenter")) { alignMode = 1; return ""; } if (s.equalsIgnoreCase("right") || s.equalsIgnoreCase("topright")) { alignMode = 2; return ""; } if (s.equalsIgnoreCase("middleleft")) { alignMode = 3; return ""; } if (s.equalsIgnoreCase("middlecenter")) { alignMode = 4; return ""; } if (s.equalsIgnoreCase("middleright")) { alignMode = 5; return ""; } if (s.equalsIgnoreCase("bottomleft")) { alignMode = 6; return ""; } if (s.equalsIgnoreCase("bottomcenter")) { alignMode = 7; return ""; } if (s.equalsIgnoreCase("bottomright")) { alignMode = 8; return ""; } /* * ******************************************************************************************************************** * Color tags */ if (s.equalsIgnoreCase("black")) { return "\2470"; } if (s.equalsIgnoreCase("darkblue") || s.equalsIgnoreCase("navy")) { return "\2471"; } if (s.equalsIgnoreCase("darkgreen") || s.equalsIgnoreCase("green")) { return "\2472"; } if (s.equalsIgnoreCase("darkaqua") || s.equalsIgnoreCase("darkcyan") || s.equalsIgnoreCase("turquoise")) { return "\2473"; } if (s.equalsIgnoreCase("darkred")) { return "\2474"; } if (s.equalsIgnoreCase("purple") || s.equalsIgnoreCase("violet")) { return "\2475"; } if (s.equalsIgnoreCase("orange") || s.equalsIgnoreCase("gold")) { return "\2476"; } if (s.equalsIgnoreCase("lightgrey") || s.equalsIgnoreCase("lightgray") || s.equalsIgnoreCase("grey") || s.equalsIgnoreCase("gray")) { return "\2477"; } if (s.equalsIgnoreCase("darkgrey") || s.equalsIgnoreCase("darkgray") || s.equalsIgnoreCase("charcoal")) { return "\2478"; } if (s.equalsIgnoreCase("indigo") || s.equalsIgnoreCase("blue") || s.equalsIgnoreCase("lightblue")) { return "\2479"; } if (s.equalsIgnoreCase("brightgreen") || s.equalsIgnoreCase("lightgreen") || s.equalsIgnoreCase("lime")) { return "\247a"; } if (s.equalsIgnoreCase("aqua") || s.equalsIgnoreCase("lightcyan") || s.equalsIgnoreCase("celeste") || s.equalsIgnoreCase("diamond")) { return "\247b"; } if (s.equalsIgnoreCase("red") || s.equalsIgnoreCase("lightred") || s.equalsIgnoreCase("salmon")) { return "\247c"; } if (s.equalsIgnoreCase("pink") || s.equalsIgnoreCase("magenta")) { return "\247d"; } if (s.equalsIgnoreCase("yellow")) { return "\247e"; } if (s.equalsIgnoreCase("white")) { return "\247f"; } /* * ******************************************************************************************************************** * Formatting tags */ if (s.equalsIgnoreCase("random")) { return "\247k"; } if (s.equalsIgnoreCase("bold") || s.equalsIgnoreCase("b")) { return "\247l"; } if (s.equalsIgnoreCase("strikethrough") || s.equalsIgnoreCase("strike") || s.equalsIgnoreCase("s")) { return "\247m"; } if (s.equalsIgnoreCase("underline") || s.equalsIgnoreCase("u")) { return "\247n"; } if (s.equalsIgnoreCase("italic") || s.equalsIgnoreCase("italics") || s.equalsIgnoreCase("i")) { return "\247o"; } if (s.equalsIgnoreCase("reset") || s.equalsIgnoreCase("r")) { return "\247r"; } /* * ******************************************************************************************************************** * World tags */ if (s.toLowerCase().startsWith("irltime") || s.toLowerCase().startsWith("rltime")) { int startIndex = s.indexOf('['); int endIndex = s.indexOf(']', startIndex + 1); String fmt = ""; if (startIndex != -1 && endIndex != -1) fmt = s.substring(startIndex + 1, endIndex); if (fmt.equals("")) fmt = "hh:mma"; return new SimpleDateFormat(fmt).format(new Date()); } if (s.toLowerCase().startsWith("mctime")) { int startIndex = s.indexOf('['); int endIndex = s.indexOf(']', startIndex + 1); long fmt = 12L; if (startIndex != -1 && endIndex != -1 && s.substring(startIndex + 1, endIndex).equals("24")) fmt = 24L; return CommonUtils.getMCTimeString(mc.theWorld.getWorldTime(), fmt); } if (s.equalsIgnoreCase("day")) { try { return Integer.toString((int) world.getWorldInfo().getWorldTime() / 24000); } catch (Throwable e) { return "0"; } } if (s.equalsIgnoreCase("biome")) { try { return biome.biomeName; } catch (Throwable e) { return "&onull"; } } if (s.equalsIgnoreCase("dimension")) { // return mc.thePlayer.dimension == -1 ? "Nether" : mc.thePlayer.dimension == 1 ? "The End" : "Overworld"; return mc.theWorld.provider.getDimensionName(); } if (s.toLowerCase().startsWith("daytime")) { return parseBoolean(s, Boolean.valueOf(world.calculateSkylightSubtracted(1.0F) < 4)); } if (s.toLowerCase().startsWith("raining")) { return parseBoolean(s, Boolean.valueOf(world.isRaining() && biome.canSpawnLightningBolt())); } if (s.toLowerCase().startsWith("snowing")) { return parseBoolean(s, Boolean.valueOf(world.isRaining() && !biome.canSpawnLightningBolt() && !biome.equals(BiomeGenBase.desert) && !biome.equals(BiomeGenBase.desertHills))); } if (s.equalsIgnoreCase("nextrain")) { return CommonUtils.ticksToTimeString(world.getWorldInfo().getRainTime()); } if (s.toLowerCase().startsWith("thundering")) { return parseBoolean(s, Boolean.valueOf(world.getWorldInfo().isThundering() && biome.canSpawnLightningBolt())); } if (s.toLowerCase().startsWith("slimes")) { return parseBoolean(s, Boolean.valueOf(chunk.getRandomWithSeed(987234911L).nextInt(10) == 0)); } if (s.toLowerCase().startsWith("hardcore")) { return parseBoolean(s, Boolean.valueOf(world.getWorldInfo().isHardcoreModeEnabled())); } if (s.equalsIgnoreCase("light")) { try { return Integer.toString(chunk.getBlockLightValue(coord.x & 0xf, coord.y, coord.z & 0xf, world.calculateSkylightSubtracted(1.0F))); } catch (Throwable e) { return "0"; } } if (s.equalsIgnoreCase("lightfeet")) { try { return Integer.toString(chunk.getBlockLightValue(coord.x & 0xf, (int) Math.round(mc.thePlayer.boundingBox.minY), coord.z & 0xf, world.calculateSkylightSubtracted(1.0F))); } catch (Throwable e) { return "0"; } } if (s.equalsIgnoreCase("lightnosun")) { try { return Integer.toString(chunk.getSavedLightValue(EnumSkyBlock.Block, coord.x & 0xf, coord.y, coord.z & 0xf)); } catch (Throwable e) { return "0"; } } if (s.equalsIgnoreCase("lightnosunfeet")) { try { return Integer.toString(chunk.getSavedLightValue(EnumSkyBlock.Block, coord.x & 0xf, (int) Math.round(mc.thePlayer.boundingBox.minY), coord.z & 0xf)); } catch (Throwable e) { return "0"; } } if (s.equalsIgnoreCase("x") || s.equalsIgnoreCase("xi")) { return Integer.toString(coord.x); } if (s.equalsIgnoreCase("y") || s.equalsIgnoreCase("yi")) { return Integer.toString(coord.y); } if (s.equalsIgnoreCase("yfeet") || s.equalsIgnoreCase("yfeeti")) { return Integer.toString((int) Math.round(mc.thePlayer.boundingBox.minY)); } if (s.equalsIgnoreCase("z") || s.equalsIgnoreCase("zi")) { return Integer.toString(coord.z); } if (s.equalsIgnoreCase("decx")) { return Double.toString(Math.round(mc.thePlayer.posX * 10.0) / 10.0); } if (s.equalsIgnoreCase("decy")) { return Double.toString(Math.round(mc.thePlayer.posY * 10.0) / 10.0); } if (s.equalsIgnoreCase("decyfeet")) { return Double.toString(Math.round(mc.thePlayer.boundingBox.minY * 10.0) / 10.0); } if (s.equalsIgnoreCase("decz")) { return Double.toString(Math.round(mc.thePlayer.posZ * 10.0) / 10.0); } if (s.equalsIgnoreCase("worldname")) { try { return world.getWorldInfo().getWorldName(); } catch (Throwable e) { return "&onull"; } } if (s.equalsIgnoreCase("worldsize")) { try { return Long.toString(world.getWorldInfo().getSizeOnDisk()); } catch (Throwable e) { return "&onull"; } } if (s.equalsIgnoreCase("worldsizemb")) { try { return Float.toString((((world.getWorldInfo().getSizeOnDisk() / 1024L) * 100L) / 1024L) / 100F); } catch (Throwable e) { return "&onull"; } } if (s.equalsIgnoreCase("seed")) { try { return mc.isIntegratedServerRunning() ? Long.toString(world.getSeed()) : "&onull"; } catch (Throwable e) { return "&onull"; } } if (s.equalsIgnoreCase("roughdirection")) { try { switch (MathHelper.floor_double(((mc.thePlayer.rotationYaw * 4F) / 360F) + 0.5D) & 3) { case 0: return "South"; case 1: return "West"; case 2: return "North"; case 3: return "East"; } } catch (Throwable e) { return "&onull"; } } if (s.equalsIgnoreCase("finedirection")) { try { switch (MathHelper.floor_double(((mc.thePlayer.rotationYaw * 8F) / 360F) + 0.5D) & 7) { case 0: return "South"; case 1: return "South West"; case 2: return "West"; case 3: return "North West"; case 4: return "North"; case 5: return "North East"; case 6: return "East"; case 7: return "South East"; } } catch (Throwable e) { return "&onull"; } } if (s.equalsIgnoreCase("abrroughdirection")) { try { switch (MathHelper.floor_double(((mc.thePlayer.rotationYaw * 4F) / 360F) + 0.5D) & 3) { case 0: return "S"; case 1: return "W"; case 2: return "N"; case 3: return "E"; } } catch (Throwable e) { return "&onull"; } } if (s.equalsIgnoreCase("abrfinedirection")) { try { switch (MathHelper.floor_double(((mc.thePlayer.rotationYaw * 8F) / 360F) + 0.5D) & 7) { case 0: return "S"; case 1: return "SW"; case 2: return "W"; case 3: return "NW"; case 4: return "N"; case 5: return "NE"; case 6: return "E"; case 7: return "SE"; } } catch (Throwable e) { return "&onull"; } } if (s.equalsIgnoreCase("directionhud")) { try { int direction = MathHelper.floor_double(((mc.thePlayer.rotationYaw * 16F) / 360F) + 0.5D) & 15; if (direction == 0) return "SE &cS &f SW"; if (direction == 1) return " S SW "; if (direction == 2) return "S &cSW&f W"; if (direction == 3) return " SW W "; if (direction == 4) return "SW &cW &f NW"; if (direction == 5) return " W NW "; if (direction == 6) return "W &cNW&f N"; if (direction == 7) return " NW N "; if (direction == 8) return "NW &cN &f NE"; if (direction == 9) return " N NE "; if (direction == 10) return "N &cNE&f E"; if (direction == 11) return " NE E "; if (direction == 12) return "NE &cE &f SE"; if (direction == 13) return " E SE "; if (direction == 14) return "E &cSE&f S"; if (direction == 15) return " SE S "; else return "this shit isn't working"; } catch (Throwable e) { return "&onull"; } } /* * ******************************************************************************************************************** * Debug tags */ if (s.equalsIgnoreCase("fps")) { try { return mc.debug.substring(0, mc.debug.indexOf(" fps")); } catch (Throwable e) { return "0"; } } if (s.equalsIgnoreCase("entitiesrendered")) { try { String str = mc.getEntityDebug(); return str.substring(str.indexOf(' ') + 1, str.indexOf('/')); } catch (Throwable e) { return "&onull"; } } if (s.equalsIgnoreCase("entitiestotal")) { try { String str = mc.getEntityDebug(); return str.substring(str.indexOf('/') + 1, str.indexOf('.')); } catch (Throwable e) { return "&onull"; } } if (s.equalsIgnoreCase("memtotal")) { try { if (memoryUnit.equalsIgnoreCase("KB")) return Long.toString(Runtime.getRuntime().totalMemory() / 1024L) + memoryUnit; if (memoryUnit.equalsIgnoreCase("MB")) return Long.toString(Runtime.getRuntime().totalMemory() / 1024L / 1024L) + memoryUnit; if (memoryUnit.equalsIgnoreCase("GB")) return Long.toString(Runtime.getRuntime().totalMemory() / 1024L / 1024L / 1024L) + memoryUnit; } catch (Throwable e) { return "&onull"; } } if (s.equalsIgnoreCase("memmax")) { try { if (memoryUnit.equalsIgnoreCase("KB")) return Long.toString(Runtime.getRuntime().maxMemory() / 1024L) + memoryUnit; if (memoryUnit.equalsIgnoreCase("MB")) return Long.toString(Runtime.getRuntime().maxMemory() / 1024L / 1024L) + memoryUnit; if (memoryUnit.equalsIgnoreCase("GB")) return Long.toString(Runtime.getRuntime().maxMemory() / 1024L / 1024L / 1024L) + memoryUnit; } catch (Throwable e) { return "&onull"; } } if (s.equalsIgnoreCase("memfree")) { try { if (memoryUnit.equalsIgnoreCase("KB")) return Long.toString(Runtime.getRuntime().freeMemory() / 1024L) + memoryUnit; if (memoryUnit.equalsIgnoreCase("MB")) return Long.toString(Runtime.getRuntime().freeMemory() / 1024L / 1024L) + memoryUnit; if (memoryUnit.equalsIgnoreCase("GB")) return Long.toString(Runtime.getRuntime().freeMemory() / 1024L / 1024L / 1024L) + memoryUnit; } catch (Throwable e) { return "&onull"; } } if (s.equalsIgnoreCase("memused")) { try { if (memoryUnit.equalsIgnoreCase("KB")) return Long.toString((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024L) + memoryUnit; if (memoryUnit.equalsIgnoreCase("MB")) return Long.toString((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024L / 1024L) + memoryUnit; if (memoryUnit.equalsIgnoreCase("GB")) return Long.toString((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024L / 1024L / 1024L) + memoryUnit; } catch (Throwable e) { return "&onull"; } } /* * ******************************************************************************************************************** * Player tags */ if (s.equalsIgnoreCase("mouseover")) { MovingObjectPosition objectMouseOver = mc.objectMouseOver; if (objectMouseOver != null) { if (objectMouseOver.typeOfHit == EnumMovingObjectType.ENTITY) { return objectMouseOver.entityHit.getEntityName(); } else if (objectMouseOver.typeOfHit == EnumMovingObjectType.TILE) { Block block = Block.blocksList[world.getBlockId(objectMouseOver.blockX, objectMouseOver.blockY, objectMouseOver.blockZ)]; if (block != null) { ItemStack pickBlock = block.getPickBlock(objectMouseOver, world, objectMouseOver.blockX, objectMouseOver.blockY, objectMouseOver.blockZ); if (pickBlock != null) { return pickBlock.getDisplayName(); } return block.getLocalizedName(); } } } return ""; } if (s.equalsIgnoreCase("mouseoverid")) { MovingObjectPosition objectMouseOver = mc.objectMouseOver; if (objectMouseOver != null) { if (objectMouseOver.typeOfHit == EnumMovingObjectType.ENTITY) { return objectMouseOver.entityHit.entityId + ""; } else if (objectMouseOver.typeOfHit == EnumMovingObjectType.TILE) { BlockID blockID = new BlockID(world, objectMouseOver.blockX, objectMouseOver.blockY, objectMouseOver.blockZ); if (blockID.id != 0) { return blockID.toString(); } } } return ""; } if (s.equalsIgnoreCase("mouseoverpowerweak")) { MovingObjectPosition objectMouseOver = mc.objectMouseOver; if (objectMouseOver != null) { if (objectMouseOver.typeOfHit == EnumMovingObjectType.TILE) { Block block = Block.blocksList[world.getBlockId(objectMouseOver.blockX, objectMouseOver.blockY, objectMouseOver.blockZ)]; if (block != null) { int power = -1; for (int side = 0; side < 6; side++) { power = Math.max(power, block.isProvidingWeakPower(world, objectMouseOver.blockX, objectMouseOver.blockY, objectMouseOver.blockZ, side)); } return Integer.toString(power); } } } return "-1"; } if (s.equalsIgnoreCase("mouseoverpowerstrong")) { MovingObjectPosition objectMouseOver = mc.objectMouseOver; if (objectMouseOver != null) { if (objectMouseOver.typeOfHit == EnumMovingObjectType.TILE) { Block block = Block.blocksList[world.getBlockId(objectMouseOver.blockX, objectMouseOver.blockY, objectMouseOver.blockZ)]; if (block != null) { int power = -1; for (int side = 0; side < 6; side++) { power = Math.max(power, block.isProvidingStrongPower(world, objectMouseOver.blockX, objectMouseOver.blockY, objectMouseOver.blockZ, side)); } return Integer.toString(power); } } } return "-1"; } if (s.equalsIgnoreCase("mouseoverpowerinput")) { MovingObjectPosition objectMouseOver = mc.objectMouseOver; if (objectMouseOver != null) { if (objectMouseOver.typeOfHit == EnumMovingObjectType.TILE) { return Integer.toString(world.getBlockPowerInput(objectMouseOver.blockX, objectMouseOver.blockY, objectMouseOver.blockZ)); } } return "-1"; } if (s.equalsIgnoreCase("underwater") || s.equalsIgnoreCase("inwater")) { return Boolean.toString(mc.thePlayer.isInWater()); } if (s.equalsIgnoreCase("wet")) { return Boolean.toString(mc.thePlayer.isWet()); } if (s.equalsIgnoreCase("alive")) { return Boolean.toString(mc.thePlayer.isEntityAlive()); } if (s.equalsIgnoreCase("burning")) { return Boolean.toString(mc.thePlayer.isBurning()); } if (s.equalsIgnoreCase("riding")) { return Boolean.toString(mc.thePlayer.isRiding()); } if (s.equalsIgnoreCase("sneaking")) { return Boolean.toString(mc.thePlayer.isSneaking()); } if (s.equalsIgnoreCase("sprinting")) { return Boolean.toString(mc.thePlayer.isSprinting()); } if (s.equalsIgnoreCase("invisible")) { return Boolean.toString(mc.thePlayer.isInvisible()); } if (s.equalsIgnoreCase("eating")) { return Boolean.toString(mc.thePlayer.isEating()); } if (s.equalsIgnoreCase("invulnerable")) { return Boolean.toString(mc.thePlayer.isEntityInvulnerable()); } if (s.equalsIgnoreCase("gamemode")) { try { if (mc.thePlayer.capabilities.isCreativeMode) return "Creative"; else if (world.getWorldInfo().getGameType().equals(EnumGameType.SURVIVAL)) return "Survival"; else if (world.getWorldInfo().getGameType().equals(EnumGameType.CREATIVE)) return "Creative/Survival?"; else if (world.getWorldInfo().getGameType().equals(EnumGameType.ADVENTURE)) return "Adventure"; else return "???"; } catch (Throwable e) { return "&onull"; } } if (s.equalsIgnoreCase("score")) { try { return Integer.toString(mc.thePlayer.getScore()); } catch (Throwable e) { return "0"; } } if (s.equalsIgnoreCase("difficulty")) { if (mc.gameSettings.difficulty == 0) return "Peaceful"; else if (mc.gameSettings.difficulty == 1) return "Easy"; else if (mc.gameSettings.difficulty == 2) return "Normal"; else if (mc.gameSettings.difficulty == 3) return "Hard"; } if (s.equalsIgnoreCase("playerlevel")) { return Integer.toString(mc.thePlayer.experienceLevel); } if (s.equalsIgnoreCase("xpthislevel")) { return Integer.toString((int) Math.ceil(mc.thePlayer.experience * mc.thePlayer.xpBarCap())); } if (s.equalsIgnoreCase("xpuntilnext")) { return Integer.toString((int) ((1.0F - mc.thePlayer.experience) * mc.thePlayer.xpBarCap())); } if (s.equalsIgnoreCase("xpcap")) { return Integer.toString(mc.thePlayer.xpBarCap()); } if (s.equalsIgnoreCase("username")) { return mc.thePlayer.username; } if (s.equalsIgnoreCase("texturepack")) { return mc.gameSettings.skin; } if (s.toLowerCase().startsWith("itemquantity")) { int startIndex = s.indexOf('['); int endIndex = s.indexOf(']', startIndex + 1); if (startIndex != -1 && endIndex != -1) { String ss = s.substring(startIndex + 1, endIndex).trim(); String[] sa = ss.split(","); int id = CommonUtils.parseInt(sa[0].trim()); int md = -1; if (sa.length > 1) md = CommonUtils.parseInt(sa[1].trim()); return HUDUtils.countInInventory(mc.thePlayer, id, md) + ""; } return "itemquantity syntax error"; } ItemStack itemStack = mc.thePlayer.getCurrentEquippedItem(); if (s.equalsIgnoreCase("equippedquantity")) { if (itemStack != null) { Item item = itemStack.getItem(); if (isForgeEnv) return Integer.toString(HUDUtils.countInInventory(mc.thePlayer, itemStack.itemID, item.getDamage(itemStack))); else return Integer.toString(HUDUtils.countInInventory(mc.thePlayer, itemStack.itemID, itemStack.getItemDamage())); } return "0"; } if (s.matches("(equipped|helmet|chestplate|leggings|boots)(name|maxdamage|damage|damageleft)")) { if (s.startsWith("equipped")) { itemStack = mc.thePlayer.getCurrentEquippedItem(); } else { int slot = -1; if (s.startsWith("helmet")) { slot = 3; } else if (s.startsWith("chestplate")) { slot = 2; } else if (s.startsWith("leggings")) { slot = 1; } else if (s.startsWith("boots")) { slot = 0; } itemStack = mc.thePlayer.inventory.armorItemInSlot(slot); } if (itemStack != null) { Item item = itemStack.getItem(); if (item != null) { if (s.endsWith("name")) { String arrows = itemStack.itemID == Item.bow.itemID ? " (" + HUDUtils.countInInventory(mc.thePlayer, Item.arrow.itemID, -1) + ")" : ""; return itemStack.getDisplayName() + arrows; } else if (s.endsWith("maxdamage")) { if (isForgeEnv) return Integer.toString(item.isDamageable() ? item.getMaxDamage(itemStack) + 1 : 0); else return Integer.toString(itemStack.isItemStackDamageable() ? itemStack.getMaxDamage() + 1 : 0); } else if (s.endsWith("damage")) { if (isForgeEnv) return Integer.toString(item.isDamageable() ? item.getDamage(itemStack) : 0); else return Integer.toString(itemStack.isItemStackDamageable() ? itemStack.getItemDamage() : 0); } else if (s.endsWith("damageleft")) { if (isForgeEnv) return Integer.toString(item.isDamageable() ? item.getMaxDamage(itemStack) + 1 - item.getDamage(itemStack) : 0); else return Integer.toString(itemStack.isItemStackDamageable() ? (itemStack.getMaxDamage() + 1) - (itemStack.getItemDamage()) : 0); } } } } try { Float.valueOf(s); return s; } catch (Throwable e) { return ""; } }
diff --git a/src/main/java/net/battlenexus/paintball/game/weapon/AbstractWeapon.java b/src/main/java/net/battlenexus/paintball/game/weapon/AbstractWeapon.java index ca069ec..cba11cd 100644 --- a/src/main/java/net/battlenexus/paintball/game/weapon/AbstractWeapon.java +++ b/src/main/java/net/battlenexus/paintball/game/weapon/AbstractWeapon.java @@ -1,270 +1,270 @@ package net.battlenexus.paintball.game.weapon; import net.battlenexus.paintball.Paintball; import net.battlenexus.paintball.entities.PBPlayer; import net.battlenexus.paintball.game.PaintballGame; import org.bukkit.*; import org.bukkit.entity.Player; import org.bukkit.entity.Snowball; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.util.Vector; import java.util.Random; public abstract class AbstractWeapon implements Weapon { private PBPlayer owner; private int bullets; protected int currentClip; public static AbstractWeapon createWeapon(Class<? extends AbstractWeapon> class_, PBPlayer owner) { try { AbstractWeapon w = class_.newInstance(); w.owner = owner; w.addBullets(w.startBullets()); return w; } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return null; } protected AbstractWeapon() { } protected void updateGUI() { float max = (float)getMaxBullets(); float percent = (max == 0.0f ? 0.0f : (float)bullets / max); getOwner().getBukkitPlayer().setExp(percent); //TODO Display EXP properly getOwner().getBukkitPlayer().setLevel(bullets); } public int getMaxBullets() { ItemStack[] items = owner.getBukkitPlayer().getInventory().getContents(); int i = 0; for (ItemStack item : items) { i += Weapon.WeaponUtils.getBulletCount(item); } return i; } @Override public Material getMaterial() { if (getOwner().getCurrentGame() == null || getOwner().getCurrentTeam() == null) return getNormalMaterial(); else { PaintballGame pg = getOwner().getCurrentGame(); if (pg.getConfig().getBlueTeam().equals(getOwner().getCurrentTeam())) { return getBlueTeamMaterial(); } else { return getRedTeamMaterial(); } } } public void addBullets(int amount) { if (amount <= clipeSize()) { ItemStack item = Weapon.WeaponUtils.createReloadItem(getReloadItem(), amount); owner.getBukkitPlayer().getInventory().addItem(item); } else { while (amount > 0) { int t; if (amount - clipeSize() >= 0) { t = clipeSize(); } else { t = amount; } ItemStack item = Weapon.WeaponUtils.createReloadItem(getReloadItem(), t); owner.getBukkitPlayer().getInventory().addItem(item); amount -= t; } } } public abstract Material getBlueTeamMaterial(); public abstract Material getRedTeamMaterial(); public abstract Material getNormalMaterial(); private boolean reloading = false; @Override public void reload(ItemStack item) { if (!reloading) { int c = Weapon.WeaponUtils.getBulletCount(item); if (c == 0) return; int bneeded = clipeSize() - bullets; if (bneeded == 0) { owner.sendMessage(ChatColor.DARK_RED + "Reload failed! Your gun is full!"); return; } int take = 0; float reloadtime = (bneeded / clipeSize()) * (reloadDelay() * 2); if (bneeded == c) { take = c; } else if (bneeded < c) { take = bneeded; } else if (bneeded > c) { take = c; } bullets += take; reloading = true; if (c - take > 0) { Weapon.WeaponUtils.setBulletCount(item, c - take); } else { if (item.getAmount() > 1) { item.setAmount(item.getAmount() - 1); } else { owner.getBukkitPlayer().getInventory().clear(owner.getBukkitPlayer().getInventory().getHeldItemSlot()); final Inventory i = owner.getBukkitPlayer().getInventory(); while (true) { int first_index = i.first(getReloadItem()); if (first_index == -1) { reloading = false; owner.sendMessage(ChatColor.DARK_RED + "You're all out!"); - return; + break; } ItemStack item_to_move = i.getItem(first_index); if (!item_to_move.hasItemMeta() || !item_to_move.getItemMeta().hasDisplayName() || !item_to_move.getItemMeta().hasLore()) { i.remove(first_index); continue; } i.clear(first_index); int clear = i.firstEmpty(); i.setItem(clear, item_to_move); break; } owner.getBukkitPlayer().updateInventory(); } } updateGUI(); owner.getBukkitPlayer().sendMessage(Paintball.formatMessage("Reloading...")); displayReloadAnimation(reloadtime); Runnable stopReload = new Runnable() { @Override public void run() { reloading = false; owner.getBukkitPlayer().sendMessage(Paintball.formatMessage(ChatColor.GREEN + "Reloaded!")); updateGUI(); } }; Bukkit.getScheduler().scheduleSyncDelayedTask(Paintball.INSTANCE, stopReload, (long) Math.round(reloadtime * 20)); } } private void displayReloadAnimation(float speed) { owner.getBukkitPlayer().setExp(0); final Player thePlayer = owner.getBukkitPlayer(); final int finalspeed = Math.round((speed / 10) * 20); Runnable fixTask = new Runnable() { @Override public void run() { thePlayer.setExp((float) (thePlayer.getExp() + 0.1)); } }; for (int i = 1; i <= 10; i++) { Bukkit.getScheduler().scheduleSyncDelayedTask(Paintball.INSTANCE, fixTask, (long) finalspeed * i); } } @Override public void shoot() { shoot(0); } @Override public int currentClipSize() { return bullets; } @Override public int totalBullets() { return getMaxBullets(); } long lastFire = -1; public void shoot(double spreadfactor) { if (reloading) { owner.sendMessage(ChatColor.DARK_RED + "You cant shoot while reloading!"); return; } if (bullets < getShotRate()) { return; } if (lastFire == -1 || (System.currentTimeMillis() - lastFire) >= getFireDelay()) { int fire = getShotRate(); bullets -= fire; updateGUI(); called = false; while (fire > 0) { onShoot(spreadfactor); if (!called) throw new RuntimeException("super.onShoot was not called! Try putting super.onShoot at the top of your method!"); fire--; } lastFire = System.currentTimeMillis(); } } @Override public PBPlayer getOwner() { return owner; } private boolean called; protected void onFire(final Snowball snowball, Player bukkitPlayer, double spread) { snowball.setShooter(bukkitPlayer); snowball.setTicksLived(2400); Vector vector; if (spread == 0) { vector = bukkitPlayer.getLocation().getDirection().multiply(strength()); } else { final Random random = new Random(); Location ploc = bukkitPlayer.getLocation(); double dir = -ploc.getYaw() - 90; double pitch = -ploc.getPitch(); double xwep = ((random.nextInt((int)(spread * 100)) - random.nextInt((int) (spread * 100))) + 0.5) / 100.0; //double ywep = ((random.nextInt((int) (spread * 100)) - random.nextInt((int) (spread * 100))) + 0.5) / 100.0; double zwep = ((random.nextInt((int) (spread * 100)) - random.nextInt((int) (spread * 100))) + 0.5) / 100.0; double xd = Math.cos(Math.toRadians(dir)) * Math.cos(Math.toRadians(pitch)) + xwep; double yd = Math.sin(Math.toRadians(pitch)); double zd = -Math.sin(Math.toRadians(dir)) * Math.cos(Math.toRadians(pitch)) + zwep; vector = new Vector(xd, yd, zd).multiply(strength()); } snowball.setVelocity(vector); Runnable task = new Runnable() { @Override public void run() { Location loc = snowball.getLocation(); for (int a = 1; a <= 2; a++) { snowball.getWorld().playEffect(loc, Effect.SMOKE, 10); } } }; for (int i = 1; i <= 10; i++) { Bukkit.getScheduler().scheduleSyncDelayedTask(Paintball.INSTANCE, task, 2L * i); } } protected void onShoot(double spread) { called = true; Player bukkitPlayer = owner.getBukkitPlayer(); bukkitPlayer.playEffect(bukkitPlayer.getLocation(), Effect.CLICK1, 10); final Snowball snowball = bukkitPlayer.getWorld().spawn(bukkitPlayer.getEyeLocation(), Snowball.class); onFire(snowball, bukkitPlayer, spread); } }
true
true
public void reload(ItemStack item) { if (!reloading) { int c = Weapon.WeaponUtils.getBulletCount(item); if (c == 0) return; int bneeded = clipeSize() - bullets; if (bneeded == 0) { owner.sendMessage(ChatColor.DARK_RED + "Reload failed! Your gun is full!"); return; } int take = 0; float reloadtime = (bneeded / clipeSize()) * (reloadDelay() * 2); if (bneeded == c) { take = c; } else if (bneeded < c) { take = bneeded; } else if (bneeded > c) { take = c; } bullets += take; reloading = true; if (c - take > 0) { Weapon.WeaponUtils.setBulletCount(item, c - take); } else { if (item.getAmount() > 1) { item.setAmount(item.getAmount() - 1); } else { owner.getBukkitPlayer().getInventory().clear(owner.getBukkitPlayer().getInventory().getHeldItemSlot()); final Inventory i = owner.getBukkitPlayer().getInventory(); while (true) { int first_index = i.first(getReloadItem()); if (first_index == -1) { reloading = false; owner.sendMessage(ChatColor.DARK_RED + "You're all out!"); return; } ItemStack item_to_move = i.getItem(first_index); if (!item_to_move.hasItemMeta() || !item_to_move.getItemMeta().hasDisplayName() || !item_to_move.getItemMeta().hasLore()) { i.remove(first_index); continue; } i.clear(first_index); int clear = i.firstEmpty(); i.setItem(clear, item_to_move); break; } owner.getBukkitPlayer().updateInventory(); } } updateGUI(); owner.getBukkitPlayer().sendMessage(Paintball.formatMessage("Reloading...")); displayReloadAnimation(reloadtime); Runnable stopReload = new Runnable() { @Override public void run() { reloading = false; owner.getBukkitPlayer().sendMessage(Paintball.formatMessage(ChatColor.GREEN + "Reloaded!")); updateGUI(); } }; Bukkit.getScheduler().scheduleSyncDelayedTask(Paintball.INSTANCE, stopReload, (long) Math.round(reloadtime * 20)); } }
public void reload(ItemStack item) { if (!reloading) { int c = Weapon.WeaponUtils.getBulletCount(item); if (c == 0) return; int bneeded = clipeSize() - bullets; if (bneeded == 0) { owner.sendMessage(ChatColor.DARK_RED + "Reload failed! Your gun is full!"); return; } int take = 0; float reloadtime = (bneeded / clipeSize()) * (reloadDelay() * 2); if (bneeded == c) { take = c; } else if (bneeded < c) { take = bneeded; } else if (bneeded > c) { take = c; } bullets += take; reloading = true; if (c - take > 0) { Weapon.WeaponUtils.setBulletCount(item, c - take); } else { if (item.getAmount() > 1) { item.setAmount(item.getAmount() - 1); } else { owner.getBukkitPlayer().getInventory().clear(owner.getBukkitPlayer().getInventory().getHeldItemSlot()); final Inventory i = owner.getBukkitPlayer().getInventory(); while (true) { int first_index = i.first(getReloadItem()); if (first_index == -1) { reloading = false; owner.sendMessage(ChatColor.DARK_RED + "You're all out!"); break; } ItemStack item_to_move = i.getItem(first_index); if (!item_to_move.hasItemMeta() || !item_to_move.getItemMeta().hasDisplayName() || !item_to_move.getItemMeta().hasLore()) { i.remove(first_index); continue; } i.clear(first_index); int clear = i.firstEmpty(); i.setItem(clear, item_to_move); break; } owner.getBukkitPlayer().updateInventory(); } } updateGUI(); owner.getBukkitPlayer().sendMessage(Paintball.formatMessage("Reloading...")); displayReloadAnimation(reloadtime); Runnable stopReload = new Runnable() { @Override public void run() { reloading = false; owner.getBukkitPlayer().sendMessage(Paintball.formatMessage(ChatColor.GREEN + "Reloaded!")); updateGUI(); } }; Bukkit.getScheduler().scheduleSyncDelayedTask(Paintball.INSTANCE, stopReload, (long) Math.round(reloadtime * 20)); } }
diff --git a/src/what/top/TopTenFragment.java b/src/what/top/TopTenFragment.java index 9a8eeee1..df00f4b1 100644 --- a/src/what/top/TopTenFragment.java +++ b/src/what/top/TopTenFragment.java @@ -1,148 +1,149 @@ package what.top; import java.util.List; import api.top.Results; import what.gui.BundleKeys; import what.gui.DownloadDialog; import what.gui.MyActivity2; import what.gui.MyScrollView; import what.gui.R; import what.torrents.torrents.TorrentGroupActivity; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnLongClickListener; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import api.son.MySon; import api.top.Response; import api.top.Top; import com.actionbarsherlock.app.SherlockFragment; import com.actionbarsherlock.view.MenuItem; /** * @author Gwindow * @since Jul 15, 2012 12:20:25 PM */ public class TopTenFragment extends SherlockFragment implements OnClickListener, OnLongClickListener { private static final int GROUP_TAG = 0; private Top top; private String tag; private LinearLayout scrollLayout; private MyScrollView scrollView; /** * @param * @param */ public TopTenFragment(Top top, String tag) { this.tag = tag; this.top = top; } public TopTenFragment() { super(); } public static SherlockFragment newInstance(Top top, String tag) { return new TopTenFragment(top, tag); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { //TODO: should we call super.onCreateView()? if ((savedInstanceState != null)) { top = (Top) MySon.toObjectFromString(savedInstanceState.getString(BundleKeys.SAVED_JSON), Top.class); tag = savedInstanceState.getString(BundleKeys.TAG); } View view = inflater.inflate(R.layout.generic_endless_scrollview, container, false); scrollView = (MyScrollView) view.findViewById(R.id.scrollView); scrollLayout = (LinearLayout) view.findViewById(R.id.scrollLayout); populateMusic(); return view; } private void populateMusic() { List<Response> response = top.getResponse(); for (Response resp : response){ if (resp.getTag().equals(tag)){ - //can't we break after this? for (Results res : resp.getResults()){ LinearLayout formats_torrent_layout = (LinearLayout) View.inflate(getSherlockActivity(), R.layout.formats_torrent, null); TextView format = (TextView) formats_torrent_layout.findViewById(R.id.format); String format_string = ""; if (res.getArtist() != null && !res.getArtist().equalsIgnoreCase("false")) { format_string += res.getArtist() + " - "; } format_string += res.getGroupName(); if (res.getGroupYear() != null && res.getGroupYear().intValue() != 0) { format_string += " [" + res.getGroupYear() + "]" + "[" + res.getEncoding() + "]"; } format.setText(format_string); format.setOnClickListener(this); format.setOnLongClickListener(this); format.setId(GROUP_TAG); Object[] array = new Object[7]; array[0] = res.getTorrentId(); array[1] = res.getDownloadLink(); //TODO: Data is not the size of the torrent, how can I get the size? - array[2] = res.getData(); + //Temp fix: data/snatched is within +/-5mb of the torrent size, or permanent fix if + //we can't get the torrent size added to the top 10 api response + array[2] = res.getData().doubleValue() / res.getSnatched().doubleValue(); array[3] = res.getSnatched(); array[4] = res.getSeeders(); array[5] = res.getLeechers(); array[6] = res.getGroupName(); format.setTag(array); scrollLayout.addView(formats_torrent_layout); } //We found the tag we're interested in and populated with it, so now we can break break; } } } @Override public void onClick(View v) { if (v.getId() == GROUP_TAG) { Object[] array = (Object[]) v.getTag(); Intent intent = new Intent(getActivity(), TorrentGroupActivity.class); Bundle bundle = new Bundle(); bundle.putInt(BundleKeys.TORRENT_GROUP_ID, ((Number) array[0]).intValue()); intent.putExtras(bundle); startActivity(intent); } } @Override public boolean onLongClick(View v) { Object[] array = (Object[]) v.getTag(); new DownloadDialog(getSherlockActivity(), (Number) array[0], (String) array[1], (Number) array[2], (Number) array[3], (Number) array[4], (Number) array[5], (String)array[6]); return false; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { return ((MyActivity2) getSherlockActivity()).homeIconJump(scrollView); } return super.onOptionsItemSelected(item); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(BundleKeys.SAVED_JSON, MySon.toJson(top, Top.class)); outState.putString(BundleKeys.TAG, tag); } }
false
true
private void populateMusic() { List<Response> response = top.getResponse(); for (Response resp : response){ if (resp.getTag().equals(tag)){ //can't we break after this? for (Results res : resp.getResults()){ LinearLayout formats_torrent_layout = (LinearLayout) View.inflate(getSherlockActivity(), R.layout.formats_torrent, null); TextView format = (TextView) formats_torrent_layout.findViewById(R.id.format); String format_string = ""; if (res.getArtist() != null && !res.getArtist().equalsIgnoreCase("false")) { format_string += res.getArtist() + " - "; } format_string += res.getGroupName(); if (res.getGroupYear() != null && res.getGroupYear().intValue() != 0) { format_string += " [" + res.getGroupYear() + "]" + "[" + res.getEncoding() + "]"; } format.setText(format_string); format.setOnClickListener(this); format.setOnLongClickListener(this); format.setId(GROUP_TAG); Object[] array = new Object[7]; array[0] = res.getTorrentId(); array[1] = res.getDownloadLink(); //TODO: Data is not the size of the torrent, how can I get the size? array[2] = res.getData(); array[3] = res.getSnatched(); array[4] = res.getSeeders(); array[5] = res.getLeechers(); array[6] = res.getGroupName(); format.setTag(array); scrollLayout.addView(formats_torrent_layout); } //We found the tag we're interested in and populated with it, so now we can break break; } } }
private void populateMusic() { List<Response> response = top.getResponse(); for (Response resp : response){ if (resp.getTag().equals(tag)){ for (Results res : resp.getResults()){ LinearLayout formats_torrent_layout = (LinearLayout) View.inflate(getSherlockActivity(), R.layout.formats_torrent, null); TextView format = (TextView) formats_torrent_layout.findViewById(R.id.format); String format_string = ""; if (res.getArtist() != null && !res.getArtist().equalsIgnoreCase("false")) { format_string += res.getArtist() + " - "; } format_string += res.getGroupName(); if (res.getGroupYear() != null && res.getGroupYear().intValue() != 0) { format_string += " [" + res.getGroupYear() + "]" + "[" + res.getEncoding() + "]"; } format.setText(format_string); format.setOnClickListener(this); format.setOnLongClickListener(this); format.setId(GROUP_TAG); Object[] array = new Object[7]; array[0] = res.getTorrentId(); array[1] = res.getDownloadLink(); //TODO: Data is not the size of the torrent, how can I get the size? //Temp fix: data/snatched is within +/-5mb of the torrent size, or permanent fix if //we can't get the torrent size added to the top 10 api response array[2] = res.getData().doubleValue() / res.getSnatched().doubleValue(); array[3] = res.getSnatched(); array[4] = res.getSeeders(); array[5] = res.getLeechers(); array[6] = res.getGroupName(); format.setTag(array); scrollLayout.addView(formats_torrent_layout); } //We found the tag we're interested in and populated with it, so now we can break break; } } }
diff --git a/src/rpiplanner/view/PlanOfStudyEditor.java b/src/rpiplanner/view/PlanOfStudyEditor.java index c4dfda6..90de65b 100644 --- a/src/rpiplanner/view/PlanOfStudyEditor.java +++ b/src/rpiplanner/view/PlanOfStudyEditor.java @@ -1,407 +1,406 @@ /* RPI Planner - Customized plans of study for RPI students. * * Copyright (C) 2008 Eric Allen [email protected] * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package rpiplanner.view; import java.awt.CardLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionAdapter; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.ListSelectionModel; import javax.swing.ScrollPaneConstants; import javax.swing.border.CompoundBorder; import javax.swing.border.EmptyBorder; import javax.swing.border.EtchedBorder; import javax.swing.border.TitledBorder; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.text.BadLocationException; import rpiplanner.POSController; import rpiplanner.SchoolInformation; import rpiplanner.model.Course; import rpiplanner.model.Degree; import com.jgoodies.forms.factories.FormFactory; import com.jgoodies.forms.layout.CellConstraints; import com.jgoodies.forms.layout.ColumnSpec; import com.jgoodies.forms.layout.FormLayout; import com.jgoodies.forms.layout.RowSpec; public class PlanOfStudyEditor extends JPanel { private JPanel planPanel; private JTextField creditTotalField; private JPanel detailsPanel; private JList problemsList; private JTextField nameField; private JButton removeDegreeButton; private JButton addDegreeButton; private JList degreeList; private JButton addCourseButton; private JPanel courseDetailsPanel; private JTextArea descriptionTextArea; private JList courseList; private JTextField searchField; private ArrayList<JPanel> semesterPanels = new ArrayList<JPanel>(8); public PlanOfStudyEditor(POSController controller){ super(); } public PlanOfStudyEditor() { super(); setLayout(new FormLayout( new ColumnSpec[] { ColumnSpec.decode("200px:grow(1.0)"), ColumnSpec.decode("300px:grow(3.5)"), ColumnSpec.decode("right:80px:grow(1.0)"), FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("80px:grow(1.0)"), FormFactory.RELATED_GAP_COLSPEC}, new RowSpec[] { FormFactory.MIN_ROWSPEC, RowSpec.decode("fill:0dlu:grow(1.0)"), FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC, RowSpec.decode("fill:70dlu")})); final JPanel titlePanel = new JPanel(); add(titlePanel, new CellConstraints("1, 1, 6, 1, fill, fill")); final JLabel rpiPlannerLabel = new JLabel(); rpiPlannerLabel.setFont(new Font("Lucida Grande", Font.BOLD, 18)); rpiPlannerLabel.setText("RPI Planner"); titlePanel.add(rpiPlannerLabel); planPanel = new JPanel(); planPanel.setLayout(new FormLayout("pref:grow(1.0), pref:grow(1.0)", "top:min, top:min, top:min, top:min, top:min")); add(planPanel, new CellConstraints("2, 2, 1, 1, fill, top")); planPanel.setName("semesters"); final JPanel apcreditPanel = new JPanel(); apcreditPanel.setBorder(new CompoundBorder(new EmptyBorder(5,5,5,5), new EtchedBorder())); apcreditPanel.setLayout(new BoxLayout(apcreditPanel, BoxLayout.Y_AXIS)); apcreditPanel.setName("apcredit"); planPanel.add(apcreditPanel, new CellConstraints(1, 1)); semesterPanels.add(apcreditPanel); for(int i = 0; i < SchoolInformation.getDefaultSemesterCount(); i++){ final JPanel semesterPanel = new JPanel(); semesterPanel.setBorder(new CompoundBorder(new EmptyBorder(5,5,5,5), new EtchedBorder())); semesterPanel.setLayout(new BoxLayout(semesterPanel, BoxLayout.Y_AXIS)); semesterPanel.setName("semesterPanel"+String.valueOf(i)); planPanel.add(semesterPanel, new CellConstraints(i%2+1, i/2+2)); semesterPanels.add(semesterPanel); } final JPanel searchPanel = new JPanel(); searchPanel.setLayout(new FormLayout( new ColumnSpec[] { ColumnSpec.decode("default:grow(1.0)")}, new RowSpec[] { FormFactory.MIN_ROWSPEC, RowSpec.decode("fill:0px:grow(1.0)"), FormFactory.DEFAULT_ROWSPEC})); searchPanel.setBorder(new TitledBorder(null, "Find Course", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null)); add(searchPanel, new CellConstraints("1, 2, 1, 4, fill, fill")); searchField = new JTextField(); searchField.setPreferredSize(new Dimension(150, 28)); searchPanel.add(searchField, new CellConstraints("1, 1, 1, 1, fill, fill")); final JScrollPane scrollPane = new JScrollPane(); - scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); searchPanel.add(scrollPane, new CellConstraints("1, 2, 1, 1, fill, fill")); courseList = new JList(); scrollPane.setViewportView(courseList); courseList.setBorder(new EtchedBorder(EtchedBorder.LOWERED)); courseList.setBackground(Color.WHITE); addCourseButton = new JButton(); addCourseButton.setText("Create New Course"); searchPanel.add(addCourseButton, new CellConstraints(1, 3)); detailsPanel = new JPanel(); detailsPanel.setLayout(new CardLayout()); add(detailsPanel, new CellConstraints(3, 2, 3, 1)); final JPanel degreeDetailsPanel = new JPanel(); degreeDetailsPanel.setBorder(new TitledBorder(null, "Degree details", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null)); degreeDetailsPanel.setLayout(new FormLayout( new ColumnSpec[] { ColumnSpec.decode("default:grow(1.0)"), FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("default:grow(1.0)")}, new RowSpec[] { FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC, RowSpec.decode("fill:default:grow(1.0)")})); degreeDetailsPanel.setName("degreeDetails"); detailsPanel.add(degreeDetailsPanel, degreeDetailsPanel.getName()); final JLabel nameLabel = new JLabel(); nameLabel.setText("Name:"); degreeDetailsPanel.add(nameLabel, new CellConstraints()); final JLabel problemsLabel = new JLabel(); problemsLabel.setText("Problems:"); degreeDetailsPanel.add(problemsLabel, new CellConstraints(1, 3)); nameField = new JTextField(); nameField.setName("name"); degreeDetailsPanel.add(nameField, new CellConstraints(3, 1)); final JScrollPane scrollPane_2 = new JScrollPane(); degreeDetailsPanel.add(scrollPane_2, new CellConstraints(1, 5, 3, 1)); problemsList = new JList(); scrollPane_2.setViewportView(problemsList); courseDetailsPanel = new JPanel(); courseDetailsPanel.setName("courseDetailsPanel"); detailsPanel.add(courseDetailsPanel, courseDetailsPanel.getName()); courseDetailsPanel.setLayout(new FormLayout( new ColumnSpec[] { FormFactory.DEFAULT_COLSPEC, FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("default:grow(1.0)")}, new RowSpec[] { FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC, RowSpec.decode("fill:default:grow(1.0)")})); courseDetailsPanel.setBorder(new TitledBorder(new EtchedBorder(), "Course details")); final JLabel titleLabel = new JLabel(); titleLabel.setText("Title:"); courseDetailsPanel.add(titleLabel, new CellConstraints(1, 3)); final JLabel departmentLabel = new JLabel(); departmentLabel.setText("Department:"); courseDetailsPanel.add(departmentLabel, new CellConstraints()); final JLabel descriptionLabel = new JLabel(); descriptionLabel.setText("Description:"); courseDetailsPanel.add(descriptionLabel, new CellConstraints(1, 7)); descriptionTextArea = new JTextArea(); descriptionTextArea.setLineWrap(true); descriptionTextArea.setWrapStyleWord(true); descriptionTextArea.setName("description"); descriptionTextArea.setEditable(false); courseDetailsPanel.add(descriptionTextArea, new CellConstraints(1, 9, 3, 1)); final JTextField departmentField = new JTextField(); departmentField.setEditable(false); departmentField.setName("department"); courseDetailsPanel.add(departmentField, new CellConstraints(3, 1)); final JTextField titleField = new JTextField(); titleField.setEditable(false); titleField.setName("title"); courseDetailsPanel.add(titleField, new CellConstraints(3, 3)); final JTextField catalogField = new JTextField(); catalogField.setEditable(false); catalogField.setName("catalogNumber"); courseDetailsPanel.add(catalogField, new CellConstraints(3, 5)); final JLabel catalogNumberLabel = new JLabel(); catalogNumberLabel.setText("Catalog number:"); courseDetailsPanel.add(catalogNumberLabel, new CellConstraints(1, 5)); final JPanel degreesPanel = new JPanel(); degreesPanel.setLayout(new FormLayout( new ColumnSpec[] { ColumnSpec.decode("default:grow(1.0)"), ColumnSpec.decode("default:grow(1.0)")}, new RowSpec[] { FormFactory.DEFAULT_ROWSPEC, FormFactory.DEFAULT_ROWSPEC})); degreesPanel.setBorder(new TitledBorder(null, "Degrees", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null)); add(degreesPanel, new CellConstraints(2, 4, 1, 2)); final JScrollPane scrollPane_1 = new JScrollPane(); degreesPanel.add(scrollPane_1, new CellConstraints(1, 1, 2, 1)); degreeList = new JList(); degreeList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); degreeList.setCellRenderer(new DegreeListCell()); scrollPane_1.setViewportView(degreeList); addDegreeButton = new JButton(); degreesPanel.add(addDegreeButton, new CellConstraints(1, 2)); addDegreeButton.setText("Add"); removeDegreeButton = new JButton(); removeDegreeButton.setText("Remove"); degreesPanel.add(removeDegreeButton, new CellConstraints(2, 2)); final JLabel creditTotalLabel = new JLabel(); creditTotalLabel.setText("Credit total:"); add(creditTotalLabel, new CellConstraints(3, 4)); creditTotalField = new JTextField(); add(creditTotalField, new CellConstraints(5, 4)); // } public void setController(final POSController controller){ controller.setSemesterPanels(semesterPanels); controller.setDetailsPanel(detailsPanel); controller.setDegreeList(degreeList); degreeList.setModel(controller.getDegreeListModel()); controller.addPropertyChangeListener("creditTotal", new PropertyChangeListener(){ public void propertyChange(PropertyChangeEvent evt) { creditTotalField.setText(String.valueOf(evt.getNewValue())); } }); addCourseButton.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { CourseEditDialog ncd = new CourseEditDialog(); ncd.setController(controller); ncd.setVisible(true); } }); addDegreeButton.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { DegreeSelector ds = new DegreeSelector(controller); ds.setVisible(true); } }); removeDegreeButton.addActionListener(new ActionListener(){ public void actionPerformed(final ActionEvent e) { controller.removeDegree((Degree)degreeList.getSelectedValue()); } }); degreeList.setModel(controller.getPlanDegreeListModel()); courseList.setModel(controller.getCourseListModel()); courseList.setTransferHandler(new CourseTransferHandler(controller)); courseList.setDragEnabled(true); courseList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); courseList.addMouseMotionListener(new MouseMotionAdapter() { public void mouseMoved(final MouseEvent e) { int index = courseList.locationToIndex(e.getPoint()); if(index != -1){ Course mouseOver = (Course)courseList.getModel().getElementAt(index); controller.setDetailDisplay(mouseOver); } else{ controller.setDetailDisplay((Course)null); } } }); courseList.addMouseListener(new MouseAdapter(){ @Override public void mouseExited(MouseEvent e) { controller.setDetailDisplay((Course)null); } @Override public void mousePressed(MouseEvent e) { if(e.getButton() == MouseEvent.BUTTON3){ // right click int idx = courseList.locationToIndex(e.getPoint()); courseList.setSelectedIndex(idx); JPopupMenu contextMenu = new JPopupMenu(); contextMenu.add("Edit").addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { CourseEditDialog d = new CourseEditDialog((Course)courseList.getSelectedValue()); d.setController(controller); d.setVisible(true); } }); contextMenu.show(courseList, e.getX(), e.getY()); } } }); degreeList.addMouseMotionListener(new MouseMotionAdapter() { public void mouseMoved(final MouseEvent e) { int index = degreeList.locationToIndex(e.getPoint()); if(index != -1){ Degree mouseOver = (Degree)degreeList.getModel().getElementAt(index); controller.setDetailDisplay(mouseOver); } else{ controller.setDetailDisplay((Course)null); } } }); degreeList.addMouseListener(new MouseAdapter(){ @Override public void mouseExited(MouseEvent e) { controller.setDetailDisplay((Course)null); } }); searchField.getDocument().addDocumentListener(new DocumentListener(){ public void changedUpdate(DocumentEvent e) { try { controller.searchTextChanged(e.getDocument().getText(0, e.getDocument().getLength())); } catch (BadLocationException e1) {} } public void insertUpdate(DocumentEvent e) { try { controller.searchTextChanged(e.getDocument().getText(0, e.getDocument().getLength())); } catch (BadLocationException e1) {} } public void removeUpdate(DocumentEvent e) { try { controller.searchTextChanged(e.getDocument().getText(0, e.getDocument().getLength())); } catch (BadLocationException e1) {} } }); } public JPanel getPlanPanel(){ return planPanel; } }
true
true
public PlanOfStudyEditor() { super(); setLayout(new FormLayout( new ColumnSpec[] { ColumnSpec.decode("200px:grow(1.0)"), ColumnSpec.decode("300px:grow(3.5)"), ColumnSpec.decode("right:80px:grow(1.0)"), FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("80px:grow(1.0)"), FormFactory.RELATED_GAP_COLSPEC}, new RowSpec[] { FormFactory.MIN_ROWSPEC, RowSpec.decode("fill:0dlu:grow(1.0)"), FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC, RowSpec.decode("fill:70dlu")})); final JPanel titlePanel = new JPanel(); add(titlePanel, new CellConstraints("1, 1, 6, 1, fill, fill")); final JLabel rpiPlannerLabel = new JLabel(); rpiPlannerLabel.setFont(new Font("Lucida Grande", Font.BOLD, 18)); rpiPlannerLabel.setText("RPI Planner"); titlePanel.add(rpiPlannerLabel); planPanel = new JPanel(); planPanel.setLayout(new FormLayout("pref:grow(1.0), pref:grow(1.0)", "top:min, top:min, top:min, top:min, top:min")); add(planPanel, new CellConstraints("2, 2, 1, 1, fill, top")); planPanel.setName("semesters"); final JPanel apcreditPanel = new JPanel(); apcreditPanel.setBorder(new CompoundBorder(new EmptyBorder(5,5,5,5), new EtchedBorder())); apcreditPanel.setLayout(new BoxLayout(apcreditPanel, BoxLayout.Y_AXIS)); apcreditPanel.setName("apcredit"); planPanel.add(apcreditPanel, new CellConstraints(1, 1)); semesterPanels.add(apcreditPanel); for(int i = 0; i < SchoolInformation.getDefaultSemesterCount(); i++){ final JPanel semesterPanel = new JPanel(); semesterPanel.setBorder(new CompoundBorder(new EmptyBorder(5,5,5,5), new EtchedBorder())); semesterPanel.setLayout(new BoxLayout(semesterPanel, BoxLayout.Y_AXIS)); semesterPanel.setName("semesterPanel"+String.valueOf(i)); planPanel.add(semesterPanel, new CellConstraints(i%2+1, i/2+2)); semesterPanels.add(semesterPanel); } final JPanel searchPanel = new JPanel(); searchPanel.setLayout(new FormLayout( new ColumnSpec[] { ColumnSpec.decode("default:grow(1.0)")}, new RowSpec[] { FormFactory.MIN_ROWSPEC, RowSpec.decode("fill:0px:grow(1.0)"), FormFactory.DEFAULT_ROWSPEC})); searchPanel.setBorder(new TitledBorder(null, "Find Course", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null)); add(searchPanel, new CellConstraints("1, 2, 1, 4, fill, fill")); searchField = new JTextField(); searchField.setPreferredSize(new Dimension(150, 28)); searchPanel.add(searchField, new CellConstraints("1, 1, 1, 1, fill, fill")); final JScrollPane scrollPane = new JScrollPane(); scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); searchPanel.add(scrollPane, new CellConstraints("1, 2, 1, 1, fill, fill")); courseList = new JList(); scrollPane.setViewportView(courseList); courseList.setBorder(new EtchedBorder(EtchedBorder.LOWERED)); courseList.setBackground(Color.WHITE); addCourseButton = new JButton(); addCourseButton.setText("Create New Course"); searchPanel.add(addCourseButton, new CellConstraints(1, 3)); detailsPanel = new JPanel(); detailsPanel.setLayout(new CardLayout()); add(detailsPanel, new CellConstraints(3, 2, 3, 1)); final JPanel degreeDetailsPanel = new JPanel(); degreeDetailsPanel.setBorder(new TitledBorder(null, "Degree details", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null)); degreeDetailsPanel.setLayout(new FormLayout( new ColumnSpec[] { ColumnSpec.decode("default:grow(1.0)"), FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("default:grow(1.0)")}, new RowSpec[] { FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC, RowSpec.decode("fill:default:grow(1.0)")})); degreeDetailsPanel.setName("degreeDetails"); detailsPanel.add(degreeDetailsPanel, degreeDetailsPanel.getName()); final JLabel nameLabel = new JLabel(); nameLabel.setText("Name:"); degreeDetailsPanel.add(nameLabel, new CellConstraints()); final JLabel problemsLabel = new JLabel(); problemsLabel.setText("Problems:"); degreeDetailsPanel.add(problemsLabel, new CellConstraints(1, 3)); nameField = new JTextField(); nameField.setName("name"); degreeDetailsPanel.add(nameField, new CellConstraints(3, 1)); final JScrollPane scrollPane_2 = new JScrollPane(); degreeDetailsPanel.add(scrollPane_2, new CellConstraints(1, 5, 3, 1)); problemsList = new JList(); scrollPane_2.setViewportView(problemsList); courseDetailsPanel = new JPanel(); courseDetailsPanel.setName("courseDetailsPanel"); detailsPanel.add(courseDetailsPanel, courseDetailsPanel.getName()); courseDetailsPanel.setLayout(new FormLayout( new ColumnSpec[] { FormFactory.DEFAULT_COLSPEC, FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("default:grow(1.0)")}, new RowSpec[] { FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC, RowSpec.decode("fill:default:grow(1.0)")})); courseDetailsPanel.setBorder(new TitledBorder(new EtchedBorder(), "Course details")); final JLabel titleLabel = new JLabel(); titleLabel.setText("Title:"); courseDetailsPanel.add(titleLabel, new CellConstraints(1, 3)); final JLabel departmentLabel = new JLabel(); departmentLabel.setText("Department:"); courseDetailsPanel.add(departmentLabel, new CellConstraints()); final JLabel descriptionLabel = new JLabel(); descriptionLabel.setText("Description:"); courseDetailsPanel.add(descriptionLabel, new CellConstraints(1, 7)); descriptionTextArea = new JTextArea(); descriptionTextArea.setLineWrap(true); descriptionTextArea.setWrapStyleWord(true); descriptionTextArea.setName("description"); descriptionTextArea.setEditable(false); courseDetailsPanel.add(descriptionTextArea, new CellConstraints(1, 9, 3, 1)); final JTextField departmentField = new JTextField(); departmentField.setEditable(false); departmentField.setName("department"); courseDetailsPanel.add(departmentField, new CellConstraints(3, 1)); final JTextField titleField = new JTextField(); titleField.setEditable(false); titleField.setName("title"); courseDetailsPanel.add(titleField, new CellConstraints(3, 3)); final JTextField catalogField = new JTextField(); catalogField.setEditable(false); catalogField.setName("catalogNumber"); courseDetailsPanel.add(catalogField, new CellConstraints(3, 5)); final JLabel catalogNumberLabel = new JLabel(); catalogNumberLabel.setText("Catalog number:"); courseDetailsPanel.add(catalogNumberLabel, new CellConstraints(1, 5)); final JPanel degreesPanel = new JPanel(); degreesPanel.setLayout(new FormLayout( new ColumnSpec[] { ColumnSpec.decode("default:grow(1.0)"), ColumnSpec.decode("default:grow(1.0)")}, new RowSpec[] { FormFactory.DEFAULT_ROWSPEC, FormFactory.DEFAULT_ROWSPEC})); degreesPanel.setBorder(new TitledBorder(null, "Degrees", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null)); add(degreesPanel, new CellConstraints(2, 4, 1, 2)); final JScrollPane scrollPane_1 = new JScrollPane(); degreesPanel.add(scrollPane_1, new CellConstraints(1, 1, 2, 1)); degreeList = new JList(); degreeList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); degreeList.setCellRenderer(new DegreeListCell()); scrollPane_1.setViewportView(degreeList); addDegreeButton = new JButton(); degreesPanel.add(addDegreeButton, new CellConstraints(1, 2)); addDegreeButton.setText("Add"); removeDegreeButton = new JButton(); removeDegreeButton.setText("Remove"); degreesPanel.add(removeDegreeButton, new CellConstraints(2, 2)); final JLabel creditTotalLabel = new JLabel(); creditTotalLabel.setText("Credit total:"); add(creditTotalLabel, new CellConstraints(3, 4)); creditTotalField = new JTextField(); add(creditTotalField, new CellConstraints(5, 4)); // }
public PlanOfStudyEditor() { super(); setLayout(new FormLayout( new ColumnSpec[] { ColumnSpec.decode("200px:grow(1.0)"), ColumnSpec.decode("300px:grow(3.5)"), ColumnSpec.decode("right:80px:grow(1.0)"), FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("80px:grow(1.0)"), FormFactory.RELATED_GAP_COLSPEC}, new RowSpec[] { FormFactory.MIN_ROWSPEC, RowSpec.decode("fill:0dlu:grow(1.0)"), FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC, RowSpec.decode("fill:70dlu")})); final JPanel titlePanel = new JPanel(); add(titlePanel, new CellConstraints("1, 1, 6, 1, fill, fill")); final JLabel rpiPlannerLabel = new JLabel(); rpiPlannerLabel.setFont(new Font("Lucida Grande", Font.BOLD, 18)); rpiPlannerLabel.setText("RPI Planner"); titlePanel.add(rpiPlannerLabel); planPanel = new JPanel(); planPanel.setLayout(new FormLayout("pref:grow(1.0), pref:grow(1.0)", "top:min, top:min, top:min, top:min, top:min")); add(planPanel, new CellConstraints("2, 2, 1, 1, fill, top")); planPanel.setName("semesters"); final JPanel apcreditPanel = new JPanel(); apcreditPanel.setBorder(new CompoundBorder(new EmptyBorder(5,5,5,5), new EtchedBorder())); apcreditPanel.setLayout(new BoxLayout(apcreditPanel, BoxLayout.Y_AXIS)); apcreditPanel.setName("apcredit"); planPanel.add(apcreditPanel, new CellConstraints(1, 1)); semesterPanels.add(apcreditPanel); for(int i = 0; i < SchoolInformation.getDefaultSemesterCount(); i++){ final JPanel semesterPanel = new JPanel(); semesterPanel.setBorder(new CompoundBorder(new EmptyBorder(5,5,5,5), new EtchedBorder())); semesterPanel.setLayout(new BoxLayout(semesterPanel, BoxLayout.Y_AXIS)); semesterPanel.setName("semesterPanel"+String.valueOf(i)); planPanel.add(semesterPanel, new CellConstraints(i%2+1, i/2+2)); semesterPanels.add(semesterPanel); } final JPanel searchPanel = new JPanel(); searchPanel.setLayout(new FormLayout( new ColumnSpec[] { ColumnSpec.decode("default:grow(1.0)")}, new RowSpec[] { FormFactory.MIN_ROWSPEC, RowSpec.decode("fill:0px:grow(1.0)"), FormFactory.DEFAULT_ROWSPEC})); searchPanel.setBorder(new TitledBorder(null, "Find Course", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null)); add(searchPanel, new CellConstraints("1, 2, 1, 4, fill, fill")); searchField = new JTextField(); searchField.setPreferredSize(new Dimension(150, 28)); searchPanel.add(searchField, new CellConstraints("1, 1, 1, 1, fill, fill")); final JScrollPane scrollPane = new JScrollPane(); searchPanel.add(scrollPane, new CellConstraints("1, 2, 1, 1, fill, fill")); courseList = new JList(); scrollPane.setViewportView(courseList); courseList.setBorder(new EtchedBorder(EtchedBorder.LOWERED)); courseList.setBackground(Color.WHITE); addCourseButton = new JButton(); addCourseButton.setText("Create New Course"); searchPanel.add(addCourseButton, new CellConstraints(1, 3)); detailsPanel = new JPanel(); detailsPanel.setLayout(new CardLayout()); add(detailsPanel, new CellConstraints(3, 2, 3, 1)); final JPanel degreeDetailsPanel = new JPanel(); degreeDetailsPanel.setBorder(new TitledBorder(null, "Degree details", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null)); degreeDetailsPanel.setLayout(new FormLayout( new ColumnSpec[] { ColumnSpec.decode("default:grow(1.0)"), FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("default:grow(1.0)")}, new RowSpec[] { FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC, RowSpec.decode("fill:default:grow(1.0)")})); degreeDetailsPanel.setName("degreeDetails"); detailsPanel.add(degreeDetailsPanel, degreeDetailsPanel.getName()); final JLabel nameLabel = new JLabel(); nameLabel.setText("Name:"); degreeDetailsPanel.add(nameLabel, new CellConstraints()); final JLabel problemsLabel = new JLabel(); problemsLabel.setText("Problems:"); degreeDetailsPanel.add(problemsLabel, new CellConstraints(1, 3)); nameField = new JTextField(); nameField.setName("name"); degreeDetailsPanel.add(nameField, new CellConstraints(3, 1)); final JScrollPane scrollPane_2 = new JScrollPane(); degreeDetailsPanel.add(scrollPane_2, new CellConstraints(1, 5, 3, 1)); problemsList = new JList(); scrollPane_2.setViewportView(problemsList); courseDetailsPanel = new JPanel(); courseDetailsPanel.setName("courseDetailsPanel"); detailsPanel.add(courseDetailsPanel, courseDetailsPanel.getName()); courseDetailsPanel.setLayout(new FormLayout( new ColumnSpec[] { FormFactory.DEFAULT_COLSPEC, FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("default:grow(1.0)")}, new RowSpec[] { FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC, RowSpec.decode("fill:default:grow(1.0)")})); courseDetailsPanel.setBorder(new TitledBorder(new EtchedBorder(), "Course details")); final JLabel titleLabel = new JLabel(); titleLabel.setText("Title:"); courseDetailsPanel.add(titleLabel, new CellConstraints(1, 3)); final JLabel departmentLabel = new JLabel(); departmentLabel.setText("Department:"); courseDetailsPanel.add(departmentLabel, new CellConstraints()); final JLabel descriptionLabel = new JLabel(); descriptionLabel.setText("Description:"); courseDetailsPanel.add(descriptionLabel, new CellConstraints(1, 7)); descriptionTextArea = new JTextArea(); descriptionTextArea.setLineWrap(true); descriptionTextArea.setWrapStyleWord(true); descriptionTextArea.setName("description"); descriptionTextArea.setEditable(false); courseDetailsPanel.add(descriptionTextArea, new CellConstraints(1, 9, 3, 1)); final JTextField departmentField = new JTextField(); departmentField.setEditable(false); departmentField.setName("department"); courseDetailsPanel.add(departmentField, new CellConstraints(3, 1)); final JTextField titleField = new JTextField(); titleField.setEditable(false); titleField.setName("title"); courseDetailsPanel.add(titleField, new CellConstraints(3, 3)); final JTextField catalogField = new JTextField(); catalogField.setEditable(false); catalogField.setName("catalogNumber"); courseDetailsPanel.add(catalogField, new CellConstraints(3, 5)); final JLabel catalogNumberLabel = new JLabel(); catalogNumberLabel.setText("Catalog number:"); courseDetailsPanel.add(catalogNumberLabel, new CellConstraints(1, 5)); final JPanel degreesPanel = new JPanel(); degreesPanel.setLayout(new FormLayout( new ColumnSpec[] { ColumnSpec.decode("default:grow(1.0)"), ColumnSpec.decode("default:grow(1.0)")}, new RowSpec[] { FormFactory.DEFAULT_ROWSPEC, FormFactory.DEFAULT_ROWSPEC})); degreesPanel.setBorder(new TitledBorder(null, "Degrees", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null)); add(degreesPanel, new CellConstraints(2, 4, 1, 2)); final JScrollPane scrollPane_1 = new JScrollPane(); degreesPanel.add(scrollPane_1, new CellConstraints(1, 1, 2, 1)); degreeList = new JList(); degreeList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); degreeList.setCellRenderer(new DegreeListCell()); scrollPane_1.setViewportView(degreeList); addDegreeButton = new JButton(); degreesPanel.add(addDegreeButton, new CellConstraints(1, 2)); addDegreeButton.setText("Add"); removeDegreeButton = new JButton(); removeDegreeButton.setText("Remove"); degreesPanel.add(removeDegreeButton, new CellConstraints(2, 2)); final JLabel creditTotalLabel = new JLabel(); creditTotalLabel.setText("Credit total:"); add(creditTotalLabel, new CellConstraints(3, 4)); creditTotalField = new JTextField(); add(creditTotalField, new CellConstraints(5, 4)); // }
diff --git a/src/edu/sc/seis/sod/subsetter/waveformArm/NullEventChannelSubsetter.java b/src/edu/sc/seis/sod/subsetter/waveformArm/NullEventChannelSubsetter.java index 3dd598d39..69c5fb352 100644 --- a/src/edu/sc/seis/sod/subsetter/waveformArm/NullEventChannelSubsetter.java +++ b/src/edu/sc/seis/sod/subsetter/waveformArm/NullEventChannelSubsetter.java @@ -1,35 +1,35 @@ package edu.sc.seis.sod.subsetter.waveFormArm; import edu.sc.seis.sod.*; import java.util.*; import org.w3c.dom.*; import edu.iris.Fissures.IfNetwork.*; import edu.iris.Fissures.network.*; import edu.iris.Fissures.IfEvent.*; import edu.iris.Fissures.network.*; import edu.iris.Fissures.*; /** * Describe class <code>NullEventChannelSubsetter</code> here. * * @author <a href="mailto:">Srinivasa Telukutla</a> * @version 1.0 */ public class NullEventChannelSubsetter implements EventChannelSubsetter { /** * Describe <code>accept</code> method here. * * @param o an <code>EventAccessOperations</code> value * @param networkAccess a <code>NetworkAccess</code> value * @param station a <code>Channel</code> value * @param cookies a <code>CookieJar</code> value * @return a <code>boolean</code> value */ - public boolean accept(EventAccessOperations o, NetworkAccess networkAccess, Channel station, CookieJar cookies) { + public boolean accept(EventAccessOperations o, NetworkAccess networkAccess, Channel channel, CookieJar cookies) { return true; } }// NullEventChannelSubsetter
true
true
public boolean accept(EventAccessOperations o, NetworkAccess networkAccess, Channel station, CookieJar cookies) { return true; }
public boolean accept(EventAccessOperations o, NetworkAccess networkAccess, Channel channel, CookieJar cookies) { return true; }
diff --git a/src/java-server-framework/org/xins/server/CallingConventionManager.java b/src/java-server-framework/org/xins/server/CallingConventionManager.java index 83ac05a39..da5e5775f 100644 --- a/src/java-server-framework/org/xins/server/CallingConventionManager.java +++ b/src/java-server-framework/org/xins/server/CallingConventionManager.java @@ -1,795 +1,795 @@ /* * $Id$ * * Copyright 2003-2007 Orange Nederland Breedband B.V. * See the COPYRIGHT file for redistribution and use restrictions. */ package org.xins.server; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.http.HttpServletRequest; import org.xins.common.Utils; import org.xins.common.collections.InvalidPropertyValueException; import org.xins.common.collections.MissingRequiredPropertyException; import org.xins.common.collections.PropertyReader; import org.xins.common.manageable.BootstrapException; import org.xins.common.manageable.InitializationException; import org.xins.common.manageable.Manageable; import org.xins.common.text.TextUtils; /** * Manages the <code>CallingConvention</code> instances for the API. * * @version $Revision$ $Date$ * @author <a href="mailto:[email protected]">Mees Witteman</a> * @author <a href="mailto:[email protected]">Anthony Goubard</a> * @author <a href="mailto:[email protected]">Ernst de Haan</a> * * @see CallingConvention */ class CallingConventionManager extends Manageable { /** * List of the names of the calling conventions currently included in * XINS. */ private final static List CONVENTIONS = Arrays.asList(new String[] { APIServlet.STANDARD_CALLING_CONVENTION, APIServlet.XML_CALLING_CONVENTION, APIServlet.XSLT_CALLING_CONVENTION, APIServlet.SOAP_CALLING_CONVENTION, APIServlet.XML_RPC_CALLING_CONVENTION, APIServlet.JSON_RPC_CALLING_CONVENTION, APIServlet.JSON_CALLING_CONVENTION }); /** * Array of type <code>Class</code> that is used when constructing a * <code>CallingConvention</code> instance via RMI. */ private final static Class[] CONSTRUCTOR_ARG_CLASSES = { API.class }; /** * Placeholder object used to indicate that the construction of a calling * convention object failed. Never <code>null</code>. */ private final static Object CREATION_FAILED = new Object(); /** * The API. Never <code>null</code>. */ private final API _api; /** * The name of the default calling convention. There is always a default * calling convention (at least after bootstrapping). * * <p>This field is initialized during bootstrapping. */ private String _defaultConventionName; /** * The names of the possible calling conventions. */ private List _conventionNames; /** * Map containing all calling conventions. The key is the name of the * calling convention, the value is the calling convention object, or * {@link #CREATION_FAILED} if the calling convention object could not be * constructed. */ private final HashMap _conventions; /** * Creates a <code>CallingConventionManager</code> for the specified API. * * @param api * the API, cannot be <code>null</code>. */ CallingConventionManager(API api) { // Store the reference to the API _api = api; // Fill the list of the convention names with the pre defined conventions _conventionNames = new ArrayList(); _conventionNames.addAll(CONVENTIONS); // Create a map to store the conventions in _conventions = new HashMap(12); } /** * Performs the bootstrap procedure (actual implementation). * * @param properties * the bootstrap properties, not <code>null</code>. * * @throws MissingRequiredPropertyException * if a required property is not given. * * @throws InvalidPropertyValueException * if the value of a certain property is invalid. * * @throws BootstrapException * if the bootstrapping failed for any other reason. */ protected void bootstrapImpl(PropertyReader properties) throws MissingRequiredPropertyException, InvalidPropertyValueException, BootstrapException { // Determine the name and class of the custom calling convention _defaultConventionName = determineDefaultConvention(properties); // Append the defined calling conventions Iterator itCustomCC = properties.getNames(); while (itCustomCC.hasNext()) { String nextProperty = (String) itCustomCC.next(); if (nextProperty.startsWith(APIServlet.API_CALLING_CONVENTION_PROPERTY + '.') && !nextProperty.equals(APIServlet.API_CALLING_CONVENTION_CLASS_PROPERTY)) { String conventionName = nextProperty.substring(32, nextProperty.length() - 6); _conventionNames.add(conventionName); } } // Construct and bootstrap the default calling convention CallingConvention cc = create(properties, _defaultConventionName); // If created, store the object and attempt bootstrapping if (cc != null) { _conventions.put(_defaultConventionName, cc); bootstrap(_defaultConventionName, cc, properties); if (cc.getState() != Manageable.BOOTSTRAPPED) { throw new BootstrapException("Failed to bootstrap the default calling convention."); } // Otherwise, if it's the default calling convention, fails } else { throw new BootstrapException("Failed to create the default calling convention."); } } /** * Determines the default calling convention. * * @param properties * the bootstrap properties, cannot be <code>null</code>. * * @return * the name of the default calling convention, never <code>null</code>. * * @throws MissingRequiredPropertyException * if a required property is not given. * * @throws InvalidPropertyValueException * if the value of a certain property is invalid. */ private String determineDefaultConvention(PropertyReader properties) throws MissingRequiredPropertyException, InvalidPropertyValueException { // Name of the default calling convention (if any) String name = TextUtils.trim(properties.get(APIServlet.API_CALLING_CONVENTION_PROPERTY), null); // No calling convention defined if (name == null) { // Log: No custom calling convention specified Log.log_3246(); // Fallback to the XINS-specified default calling convention name = APIServlet.STANDARD_CALLING_CONVENTION; } // Log: Determined default calling convention Log.log_3245(name); // Return the name of the default calling convention return name; } /** * Constructs the calling convention with the specified name, using the * specified bootstrap properties. This method is called for both * <em>regular</em> and <em>custom</em> calling conventions. * * <p>If the name does not identify a recognized calling convention, then * <code>null</code> is returned. * * @param properties * the bootstrap properties, cannot be <code>null</code>. * * @param name * the name of the calling convention to construct, cannot be * <code>null</code>. * * @return * a non-bootstrapped {@link CallingConvention} instance that matches * the specified name, or <code>null</code> if no match is found. */ private CallingConvention create(PropertyReader properties, String name) { // Determine the name of the CallingConvention class String className = null; if (name.charAt(0) == '_') { className = classNameForRegular(name); } else { className = properties.get(APIServlet.API_CALLING_CONVENTION_PROPERTY + '.' + name + ".class"); } // If the class could not be determined, then return null if (className == null) { Log.log_3239(null, name, null); return null; } Log.log_3237(name, className); // Construct a CallingConvention instance CallingConvention cc = construct(name, className); // NOTE: Logging of construction failures is done in construct(...) // Constructed successfully if (cc != null) { Log.log_3238(name, className); cc.setAPI(_api); } return cc; } /** * Determines the name of the class that represents the regular calling * convention with the specified name. A <em>regular</em> calling * convention is one that comes with the XINS framework. * * @param name * the name of the calling convention, should not be <code>null</code> * and should normally starts with an underscore character * (<code>'_'</code>). * * @return * the name of the {@link CallingConvention} class that matches the * specified calling convention name, or <code>null</code> if unknown. */ private String classNameForRegular(String name) { // XINS standard if (name.equals(APIServlet.STANDARD_CALLING_CONVENTION)) { return "org.xins.server.StandardCallingConvention"; // XINS XML } else if (name.equals(APIServlet.XML_CALLING_CONVENTION)) { return "org.xins.server.XMLCallingConvention"; // XSLT } else if (name.equals(APIServlet.XSLT_CALLING_CONVENTION)) { return "org.xins.server.XSLTCallingConvention"; // SOAP } else if (name.equals(APIServlet.SOAP_CALLING_CONVENTION)) { return "org.xins.server.SOAPCallingConvention"; // XML-RPC } else if (name.equals(APIServlet.XML_RPC_CALLING_CONVENTION)) { return "org.xins.server.XMLRPCCallingConvention"; // JSON-RPC } else if (name.equals(APIServlet.JSON_RPC_CALLING_CONVENTION)) { return "org.xins.server.JSONRPCCallingConvention"; // JSON } else if (name.equals(APIServlet.JSON_CALLING_CONVENTION)) { return "org.xins.server.JSONCallingConvention"; // Unrecognized } else { return null; } } /** * Constructs a new <code>CallingConvention</code> instance by class name. * * @param name * the name of the calling convention, cannot be <code>null</code>. * * @param className * the name of the class, cannot be <code>null</code>. * * @return * the constructed {@link CallingConvention} instance, or * <code>null</code> if the construction failed. */ private CallingConvention construct(String name, String className) { // Try to load the class Class clazz; try { clazz = Class.forName(className); } catch (Throwable exception) { Log.log_3239(exception, name, className); return null; } // Get the constructor that accepts an API argument Constructor con = null; try { con = clazz.getConstructor(CONSTRUCTOR_ARG_CLASSES); } catch (NoSuchMethodException exception) { // fall through, do not even log } // If there is such a constructor, invoke it if (con != null) { // Invoke it Object[] args = { _api }; try { return (CallingConvention) con.newInstance(args); // If the constructor exists but failed, then construction failed } catch (Throwable exception) { Utils.logIgnoredException(exception); return null; } } // Secondly try a constructor with no arguments try { return (CallingConvention) clazz.newInstance(); } catch (Throwable exception) { Log.log_3239(exception, name, className); return null; } } /** * Bootstraps the specified calling convention. * * @param name * the name of the calling convention, cannot be <code>null</code>. * * @param cc * the {@link CallingConvention} object to bootstrap, cannot be * <code>null</code>. * * @param properties * the bootstrap properties, cannot be <code>null</code>. */ private void bootstrap(String name, CallingConvention cc, PropertyReader properties) { // Bootstrapping calling convention Log.log_3240(name); try { cc.bootstrap(properties); Log.log_3241(name); // Missing property } catch (MissingRequiredPropertyException exception) { Log.log_3242(name, exception.getPropertyName(), exception.getDetail()); // Invalid property } catch (InvalidPropertyValueException exception) { Log.log_3243(name, exception.getPropertyName(), exception.getPropertyValue(), exception.getReason()); // Catch BootstrapException and any other exceptions not caught // by previous catch statements } catch (Throwable exception) { Log.log_3244(exception, name); } } /** * Performs the initialization procedure (actual implementation). * * @param properties * the initialization properties, not null. * * @throws MissingRequiredPropertyException * if a required property is not given. * * @throws InvalidPropertyValueException * if the value of a certain property is invalid. * * @throws InitializationException * if the initialization failed, for any other reason. */ protected void initImpl(PropertyReader properties) throws MissingRequiredPropertyException, InvalidPropertyValueException, InitializationException { // Loop through all CallingConvention instances Iterator iterator = _conventions.entrySet().iterator(); while (iterator.hasNext()) { // Determine the name and get the CallingConvention instance Map.Entry entry = (Map.Entry) iterator.next(); String name = (String) entry.getKey(); Object cc = entry.getValue(); // Process this CallingConvention only if it was created OK if (cc != CREATION_FAILED) { // Initialize the CallingConvention CallingConvention conv = (CallingConvention) cc; init(name, conv, properties); // Fail if the *default* calling convention fails to initialize if (!conv.isUsable() && name.equals(_defaultConventionName)) { throw new InitializationException("Failed to initialize the default calling convention \"" + name + "\"."); } } } } /** * Initializes the specified calling convention. * * <p>If the specified calling convention is not even bootstrapped, the * initialization is not even attempted. * * @param name * the name of the calling convention, cannot be <code>null</code>. * * @param cc * the {@link CallingConvention} object to initialize, cannot be * <code>null</code>. * * @param properties * the initialization properties, cannot be <code>null</code>. */ private void init(String name, CallingConvention cc, PropertyReader properties) { // If the CallingConvention is not even bootstrapped, then do not even // attempt to initialize it if (! cc.isBootstrapped()) { return; } // Initialize calling convention Log.log_3435(name); try { cc.init(properties); // Missing property } catch (MissingRequiredPropertyException exception) { Log.log_3437(name, exception.getPropertyName(), exception.getDetail()); // Invalid property } catch (InvalidPropertyValueException exception) { Log.log_3438(name, exception.getPropertyName(), exception.getPropertyValue(), exception.getReason()); // Catch InitializationException and any other exceptions not caught // by previous catch statements } catch (Throwable exception) { Log.log_3439(exception, name); } } /** * Determines the calling convention to use for the specified request. * * @param request * the incoming request, cannot be <code>null</code>. * * @return * the calling convention to use, never <code>null</code>. * * @throws InvalidRequestException * if the request is considered invalid, for example because the calling * convention specified in the request is unknown. */ CallingConvention getCallingConvention(HttpServletRequest request) throws InvalidRequestException { // Get the value of the input parameter that determines the convention String paramName = APIServlet.CALLING_CONVENTION_PARAMETER; String ccName = request.getParameter(paramName); // If a calling convention is specified then use that one if (! TextUtils.isEmpty(ccName)) { CallingConvention cc = getCallingConvention(ccName); if (! Arrays.asList(cc.getSupportedMethods(request)).contains(request.getMethod()) && !"OPTIONS".equals(request.getMethod())) { String detail = "Calling convention \"" + ccName + "\" does not support the \"" + request.getMethod() + "\" for this request."; Log.log_3507(ccName, detail); throw new InvalidRequestException(detail); } return cc; // Otherwise try to detect which one is appropriate } else { return detectCallingConvention(request); } } /** * Gets the calling convention for the given name. * * <p>The returned calling convention is bootstrapped and initialized. * * @param name * the name of the calling convention to retrieve, should not be * <code>null</code>. * * @return * the calling convention initialized, never <code>null</code>. * * @throws InvalidRequestException * if the calling convention name is unknown. */ private CallingConvention getCallingConvention(String name) throws InvalidRequestException { // Get the CallingConvention object Object o = _conventions.get(name); // Not found if (o == null && !_conventionNames.contains(name)) { String detail = "Calling convention \"" + name + "\" is unknown."; Log.log_3507(name, detail); throw new InvalidRequestException(detail); } else if (o == null) { // Create the asked calling convention and initiaze it CallingConvention cc = create(_api.getBootstrapProperties(), name); // If created, store the object and attempt bootstrapping if (cc != null) { o = cc; _conventions.put(name, cc); bootstrap(name, cc, _api.getBootstrapProperties()); init(name, cc, _api.getRuntimeProperties()); } else { o = CREATION_FAILED; _conventions.put(name, o); } } // Creation failed if (o == CREATION_FAILED) { String detail = "Calling convention \"" + name + "\" is known, but could not be created."; Log.log_3507(name, detail); throw new InvalidRequestException(detail); // Calling convention is recognized and was created OK } else { // Not usable (so not bootstrapped and initialized) CallingConvention cc = (CallingConvention) o; if (! cc.isUsable()) { String detail = "Calling convention \"" + name + "\" is known, but is uninitialized."; Log.log_3507(name, detail); throw new InvalidRequestException(detail); } return cc; } } /** * Gets the calling convention for the given name, or <code>null</code> if * the calling convention is not found or not usable. * * <p>The returned calling convention is bootstrapped and initialized. * * @param name * the name of the calling convention to retrieve, should not be * <code>null</code>. * * @return * the calling convention, or <code>null</code>. */ CallingConvention getCallingConvention2(String name) { try { return getCallingConvention(name); } catch (InvalidRequestException ex) { return null; } } /** * Attempts to detect which calling convention is the most appropriate for * an incoming request. This method is called when the calling convention * is not explicitly specified in the request. * * <p>The {@link CallingConvention#matchesRequest(HttpServletRequest)} * method is used to determine which calling conventions match. Then * the following algorithm is used to chose one: * * <ul> * <li>if the default calling convention matches, use that; * <li>otherwise if the {@link XSLTCallingConvention} matches and at * least one of the parameters specific for the this calling * convention is set, then use it; * <li>otherwise if the {@link StandardCallingConvention} matches, use * that; * <li>otherwise if there is exactly one other calling convention that * matches, use that one; * <li>if none of the calling conventions match, throw an * {@link InvalidRequestException}, indicating that no match could * be found; * <li>if multiple calling conventions match, throw an * {@link InvalidRequestException}, indicating that several matches * were found; * </ul> * * @param request * the incoming request, cannot be <code>null</code>. * * @return * the calling convention to use, never <code>null</code>. * * @throws InvalidRequestException * if the request is considered invalid, for example because the calling * convention specified in the request is unknown. */ CallingConvention detectCallingConvention(HttpServletRequest request) throws InvalidRequestException { // Log: Request does not specify any calling convention Log.log_3508(); // See if the default calling convention matches CallingConvention defCC = getCallingConvention2(_defaultConventionName); if (defCC != null && defCC.matchesRequest(request)) { Log.log_3509(defCC.getClass().getName()); return defCC; } // If not, see if XSLT-specific properties are set /and/ _xins-xslt matches CallingConvention xslCC = getCallingConvention2("_xins-xslt"); if (xslCC != null && xslCC != defCC && xslCC.matchesRequest(request)) { // Determine if one of the two XSLT-specific parameters is set String p1 = request.getParameter(XSLTCallingConvention.TEMPLATE_PARAMETER); String p2 = request.getParameter(XSLTCallingConvention.CLEAR_TEMPLATE_CACHE_PARAMETER); // Use the XSLT calling convention if and only if at least one of the // parameters is actually set if (! (TextUtils.isEmpty(p1) && TextUtils.isEmpty(p2))) { Log.log_3509(XSLTCallingConvention.class.getName()); return xslCC; } } // If not, see if _xins-std matches CallingConvention stdCC = getCallingConvention2("_xins-std"); if (stdCC != null && stdCC != defCC && stdCC.matchesRequest(request)) { Log.log_3509(StandardCallingConvention.class.getName()); return stdCC; } // Local variable to hold the first matching calling convention CallingConvention matching = null; // Determine which calling conventions match Iterator itConventionNames = _conventionNames.iterator(); while (itConventionNames.hasNext()) { String name = (String) itConventionNames.next(); Object value = getCallingConvention2(name); // if the value is null, that's maybe an initialization problem if (value == null) { value = _conventions.get(name); } // Skip all values that are not CallingConvention instances // Skip also the default and the standard calling conventions, we // already established that they cannot handle the request if (value == CREATION_FAILED || value == defCC || value == stdCC) { continue; } // Convert the value to a CallingConvention CallingConvention cc = (CallingConvention) value; // Determine whether this one can handle it if (cc.matchesRequest(request)) { // First match if (matching == null) { matching = cc; // Fail: Multiple matches } else { Log.log_3511(); String multipleMatches = "Request does not specify a calling " + "convention, it cannot be handled by the " + "default calling convention and multiple " + "calling conventions are able to handle it: \""; String message = multipleMatches + matching.getClass().getName() + "\", \"" + cc.getClass().getName() + "\"."; throw new InvalidRequestException(message); } } } // One match if (matching != null) { return matching; // Fail: No matches } else { Log.log_3510(); String noMatches = "Request does not specify a calling convention, it " - + "cannot be handled by the default calling convention and it was" + + "cannot be handled by the default calling convention and it was " + "not possible to find any calling convention that can handle it."; throw new InvalidRequestException(noMatches); } } /** * Returns the set of HTTP methods supported for function invocations. This * is the union of the methods supported by the individual calling * conventions for invoking functions, so excluding the <em>OPTIONS</em> * method. The latter cannot be used for function invocations, only to * determine which HTTP methods are available. See * {@link CallingConvention#getSupportedMethods()}. * * @return * the {@link Set} of supported HTTP methods, never <code>null</code>. * * @throws IllegalStateException * if this calling convention manager is not yet bootstrapped and * initialized, see {@link #isUsable()}. */ final Set getSupportedMethods() throws IllegalStateException { // Make sure this Manageable object is bootstrapped and initialized assertUsable(); HashSet supportedMethods = new HashSet(); Iterator itConventionNames = _conventionNames.iterator(); while (itConventionNames.hasNext()) { String name = (String) itConventionNames.next(); Object convention = getCallingConvention2(name); // if the value is null, that's maybe an initialization problem if (convention == null) { convention = _conventions.get(name); } // Add all methods supported by the calling convention if (convention instanceof CallingConvention) { CallingConvention cc = (CallingConvention) convention; supportedMethods.addAll(Arrays.asList(cc.getSupportedMethods())); } } return supportedMethods; } }
true
true
CallingConvention detectCallingConvention(HttpServletRequest request) throws InvalidRequestException { // Log: Request does not specify any calling convention Log.log_3508(); // See if the default calling convention matches CallingConvention defCC = getCallingConvention2(_defaultConventionName); if (defCC != null && defCC.matchesRequest(request)) { Log.log_3509(defCC.getClass().getName()); return defCC; } // If not, see if XSLT-specific properties are set /and/ _xins-xslt matches CallingConvention xslCC = getCallingConvention2("_xins-xslt"); if (xslCC != null && xslCC != defCC && xslCC.matchesRequest(request)) { // Determine if one of the two XSLT-specific parameters is set String p1 = request.getParameter(XSLTCallingConvention.TEMPLATE_PARAMETER); String p2 = request.getParameter(XSLTCallingConvention.CLEAR_TEMPLATE_CACHE_PARAMETER); // Use the XSLT calling convention if and only if at least one of the // parameters is actually set if (! (TextUtils.isEmpty(p1) && TextUtils.isEmpty(p2))) { Log.log_3509(XSLTCallingConvention.class.getName()); return xslCC; } } // If not, see if _xins-std matches CallingConvention stdCC = getCallingConvention2("_xins-std"); if (stdCC != null && stdCC != defCC && stdCC.matchesRequest(request)) { Log.log_3509(StandardCallingConvention.class.getName()); return stdCC; } // Local variable to hold the first matching calling convention CallingConvention matching = null; // Determine which calling conventions match Iterator itConventionNames = _conventionNames.iterator(); while (itConventionNames.hasNext()) { String name = (String) itConventionNames.next(); Object value = getCallingConvention2(name); // if the value is null, that's maybe an initialization problem if (value == null) { value = _conventions.get(name); } // Skip all values that are not CallingConvention instances // Skip also the default and the standard calling conventions, we // already established that they cannot handle the request if (value == CREATION_FAILED || value == defCC || value == stdCC) { continue; } // Convert the value to a CallingConvention CallingConvention cc = (CallingConvention) value; // Determine whether this one can handle it if (cc.matchesRequest(request)) { // First match if (matching == null) { matching = cc; // Fail: Multiple matches } else { Log.log_3511(); String multipleMatches = "Request does not specify a calling " + "convention, it cannot be handled by the " + "default calling convention and multiple " + "calling conventions are able to handle it: \""; String message = multipleMatches + matching.getClass().getName() + "\", \"" + cc.getClass().getName() + "\"."; throw new InvalidRequestException(message); } } } // One match if (matching != null) { return matching; // Fail: No matches } else { Log.log_3510(); String noMatches = "Request does not specify a calling convention, it " + "cannot be handled by the default calling convention and it was" + "not possible to find any calling convention that can handle it."; throw new InvalidRequestException(noMatches); } }
CallingConvention detectCallingConvention(HttpServletRequest request) throws InvalidRequestException { // Log: Request does not specify any calling convention Log.log_3508(); // See if the default calling convention matches CallingConvention defCC = getCallingConvention2(_defaultConventionName); if (defCC != null && defCC.matchesRequest(request)) { Log.log_3509(defCC.getClass().getName()); return defCC; } // If not, see if XSLT-specific properties are set /and/ _xins-xslt matches CallingConvention xslCC = getCallingConvention2("_xins-xslt"); if (xslCC != null && xslCC != defCC && xslCC.matchesRequest(request)) { // Determine if one of the two XSLT-specific parameters is set String p1 = request.getParameter(XSLTCallingConvention.TEMPLATE_PARAMETER); String p2 = request.getParameter(XSLTCallingConvention.CLEAR_TEMPLATE_CACHE_PARAMETER); // Use the XSLT calling convention if and only if at least one of the // parameters is actually set if (! (TextUtils.isEmpty(p1) && TextUtils.isEmpty(p2))) { Log.log_3509(XSLTCallingConvention.class.getName()); return xslCC; } } // If not, see if _xins-std matches CallingConvention stdCC = getCallingConvention2("_xins-std"); if (stdCC != null && stdCC != defCC && stdCC.matchesRequest(request)) { Log.log_3509(StandardCallingConvention.class.getName()); return stdCC; } // Local variable to hold the first matching calling convention CallingConvention matching = null; // Determine which calling conventions match Iterator itConventionNames = _conventionNames.iterator(); while (itConventionNames.hasNext()) { String name = (String) itConventionNames.next(); Object value = getCallingConvention2(name); // if the value is null, that's maybe an initialization problem if (value == null) { value = _conventions.get(name); } // Skip all values that are not CallingConvention instances // Skip also the default and the standard calling conventions, we // already established that they cannot handle the request if (value == CREATION_FAILED || value == defCC || value == stdCC) { continue; } // Convert the value to a CallingConvention CallingConvention cc = (CallingConvention) value; // Determine whether this one can handle it if (cc.matchesRequest(request)) { // First match if (matching == null) { matching = cc; // Fail: Multiple matches } else { Log.log_3511(); String multipleMatches = "Request does not specify a calling " + "convention, it cannot be handled by the " + "default calling convention and multiple " + "calling conventions are able to handle it: \""; String message = multipleMatches + matching.getClass().getName() + "\", \"" + cc.getClass().getName() + "\"."; throw new InvalidRequestException(message); } } } // One match if (matching != null) { return matching; // Fail: No matches } else { Log.log_3510(); String noMatches = "Request does not specify a calling convention, it " + "cannot be handled by the default calling convention and it was " + "not possible to find any calling convention that can handle it."; throw new InvalidRequestException(noMatches); } }
diff --git a/src/com/matburt/mobileorg/Synchronizers/UbuntuOneSynchronizer.java b/src/com/matburt/mobileorg/Synchronizers/UbuntuOneSynchronizer.java index 81e11d8..cce8419 100644 --- a/src/com/matburt/mobileorg/Synchronizers/UbuntuOneSynchronizer.java +++ b/src/com/matburt/mobileorg/Synchronizers/UbuntuOneSynchronizer.java @@ -1,409 +1,410 @@ package com.matburt.mobileorg.Synchronizers; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer; import oauth.signpost.exception.OAuthException; import oauth.signpost.signature.HmacSha1MessageSigner; import org.apache.http.HttpEntity; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Build; import android.preference.PreferenceManager; import android.util.Log; public class UbuntuOneSynchronizer implements SynchronizerInterface { private static final String BASE_TOKEN_NAME = "Ubuntu One @ MobileOrg:"; private static final String CONSUMER_KEY = "consumer_key"; private static final String CONSUMER_SECRET = "consumer_secret"; private static final String ACCESS_TOKEN = "token"; private static final String TOKEN_SECRET = "token_secret"; private static final String BASE_PATH = "root_node_path"; private static final String BYTES_USED = "used_bytes"; private static final String MAX_BYTES = "max_bytes"; private static final String LOGIN_HOST = "login.ubuntu.com"; private static final int LOGIN_PORT = 443; private static final String LOGIN_URL = "https://" + LOGIN_HOST + ":" + LOGIN_PORT + "/api/1.0/authentications" + "?ws.op=authenticate&token_name="; private static final String FILES_BASE = "https://files.one.ubuntu.com"; private static final String FILES_URL = "https://one.ubuntu.com/api/file_storage/v1"; private static final String PING_URL = "https://one.ubuntu.com/oauth/sso-finished-so-get-tokens/"; private static final String UTF8 = "UTF-8"; public String remoteIndexPath; public String remotePath; public String username; public String password; public String consumer_key; public String consumer_secret; public String access_token; public String token_secret; public String root_path; public long bytes_used; public long max_bytes; private CommonsHttpOAuthConsumer consumer; private Context context; public UbuntuOneSynchronizer(Context context) { this.context = context; SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); this.remoteIndexPath = sharedPreferences.getString("ubuntuOnePath", ""); // this.remotePath = getRootUrl(); this.username = sharedPreferences.getString("ubuntuOneUser", ""); this.password = ""; //we don't store this, it's just set to be populated by wizard consumer_key = sharedPreferences.getString("ubuntuConsumerKey", ""); consumer_secret = sharedPreferences.getString("ubuntuConsumerSecret", ""); access_token = sharedPreferences.getString("ubuntuAccessToken", ""); token_secret = sharedPreferences.getString("ubuntuTokenSecret", ""); } public void invalidate() { this.consumer = null; } public String testConnection(String user, String pass) { return ""; } public boolean isConfigured() { if (this.consumer_key.equals("")) return false; return true; } public void signRequest(HttpRequest request) { int retries = 3; if (consumer == null) { buildConsumer(); } while (retries-- > 0) { try { if (consumer != null) { // We need to remove the previous Authorization header // because signpost fails to sign a second time otherwise. request.removeHeaders("Authorization"); consumer.sign(request); return; } } catch (OAuthException e) { e.printStackTrace(); } login(); } } public void putRemoteFile(String filename, String contents) throws IOException { try { buildConsumer(); String latterPart = remoteIndexPath + filename; latterPart = latterPart.replaceAll("/{2,}", "/"); String files_url = FILES_URL + root_path + latterPart; URL url = new URL(files_url); URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef()); url = uri.toURL(); HttpPut request = new HttpPut(url.toString()); JSONObject createFile = new JSONObject(); createFile.put("kind", "file"); StringEntity se = new StringEntity(createFile.toString()); //se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); request.setEntity(se); DefaultHttpClient httpClient = new DefaultHttpClient(); signRequest(request); HttpResponse response = httpClient.execute(request); verifyResponse(response); JSONObject fileData = responseToJson(response); String content_path = fileData.getString("content_path"); String content_url = FILES_BASE + content_path; url = new URL(content_url); uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef()); url = uri.toURL(); request = new HttpPut(url.toString()); request.setEntity(new StringEntity(contents)); httpClient = new DefaultHttpClient(); signRequest(request); response = httpClient.execute(request); verifyResponse(response); } catch (Exception e) { Log.e("MobileOrg", "Exception in Ubuntu One Put File: " + e.toString()); + throw new IOException("Uploading: " + filename + ": " + e.toString()); } } public BufferedReader getRemoteFile(String filename) { try { buildConsumer(); String latterPart = remoteIndexPath + filename; latterPart = latterPart.replaceAll("/{2,}", "/"); String files_url = FILES_URL + root_path + latterPart; URL url = new URL(files_url); URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef()); url = uri.toURL(); HttpGet request = new HttpGet(url.toString()); DefaultHttpClient httpClient = new DefaultHttpClient(); signRequest(request); HttpResponse response = httpClient.execute(request); verifyResponse(response); JSONObject fileData = responseToJson(response); String content_path = fileData.getString("content_path"); String content_url = FILES_BASE + content_path; url = new URL(content_url); uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef()); url = uri.toURL(); request = new HttpGet(url.toString()); httpClient = new DefaultHttpClient(); signRequest(request); response = httpClient.execute(request); verifyResponse(response); return new BufferedReader(new InputStreamReader(response.getEntity().getContent())); } catch (Exception e) { Log.e("MobileOrg", "Exception in Ubuntu One Fetch File: " + e.toString()); } return null; } public ArrayList<String> getDirectoryList(String directory) { ArrayList<String> directories = new ArrayList<String>(); try { buildConsumer(); String latterPart = root_path + directory + "?include_children=true"; latterPart = latterPart.replaceAll("/{2,}", "/"); String files_url = FILES_URL + latterPart; URL url = new URL(files_url); URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef()); url = uri.toURL(); Log.d("MobileOrg", "Getting directory list for: " + url.toString()); HttpGet request = new HttpGet(url.toString()); DefaultHttpClient httpClient = new DefaultHttpClient(); signRequest(request); HttpResponse response = httpClient.execute(request); verifyResponse(response); JSONObject dirData = responseToJson(response); JSONArray jsA = dirData.getJSONArray("children"); if (jsA != null) { for (int i = 0; i < jsA.length(); i++){ JSONObject node = jsA.getJSONObject(i); if (node.getString("kind").equals("directory")) { directories.add(node.getString("path")); } } } } catch (Exception e) { Log.e("MobileOrg", "Exception in Ubuntu One Fetch Directories: " + e.toString()); } return directories; } public void getBaseUser() { try { buildConsumer(); String files_url = FILES_URL; HttpGet request = new HttpGet(files_url); DefaultHttpClient httpClient = new DefaultHttpClient(); signRequest(request); HttpResponse response = httpClient.execute(request); verifyResponse(response); JSONObject dirData = responseToJson(response); root_path = dirData.getString(BASE_PATH); max_bytes = dirData.getLong(MAX_BYTES); bytes_used = dirData.getLong(BYTES_USED); } catch (Exception e) { Log.e("MobileOrg", "Exception in Ubuntu One Fetch Directories: " + e.toString()); } } @Override public void postSynchronize() { } public boolean login() { invalidate(); try { Log.i("MobileOrg", "Logging into Ubuntu One"); DefaultHttpClient httpClient = new DefaultHttpClient(); httpClient.getCredentialsProvider().setCredentials( new AuthScope(LOGIN_HOST, LOGIN_PORT), new UsernamePasswordCredentials(this.username, this.password)); HttpUriRequest request = new HttpGet(buildLoginUrl()); HttpResponse response = httpClient.execute(request); verifyResponse(response); JSONObject loginData = responseToJson(response); consumer_key = loginData.getString(CONSUMER_KEY); consumer_secret = loginData.getString(CONSUMER_SECRET); access_token = loginData.getString(ACCESS_TOKEN); token_secret = loginData.getString(TOKEN_SECRET); SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); Editor edit = sharedPreferences.edit(); edit.putString("ubuntuConsumerKey", consumer_key); edit.putString("ubuntuConsumerSecret", consumer_secret); edit.putString("ubuntuAccessToken", access_token); edit.putString("ubuntuTokenSecret", token_secret); Log.i("MobileOrg", "Logged in to Ubuntu One: " + consumer_key); edit.commit(); buildConsumer(); ping_u1_url(this.username); return true; } catch (ClientProtocolException e) { Log.e("MobileOrg", "Protocol Exception: " + e.toString()); } catch (IOException e) { Log.e("MobileOrg", "IO Exception: " + e.toString()); } catch (JSONException e) { Log.e("MobileOrg", "JSONException: " + e.toString()); } return false; } private InputStream getUrl(String url) throws Exception { HttpGet request = new HttpGet(url); HttpResponse response = executeRequest(request); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); return instream; } return null; } private void putUrl(String url, String data) throws Exception { HttpPut put = new HttpPut(url); put.setEntity(new StringEntity(data)); HttpResponse response = executeRequest(put); } protected HttpResponse executeRequest(HttpUriRequest request) throws ClientProtocolException, IOException { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpResponse response = null; int retries = 3; while (retries-- > 0) { this.signRequest(request); response = httpClient.execute(request); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 400 || statusCode == 401) { invalidate(); } else { return response; } } return response; } private void buildConsumer() { if (consumer_key != null && consumer_secret != null && access_token != null && token_secret != null) { consumer = new CommonsHttpOAuthConsumer(consumer_key, consumer_secret); consumer.setMessageSigner(new HmacSha1MessageSigner()); consumer.setTokenWithSecret(access_token, token_secret); } } private void verifyResponse(HttpResponse response) throws IOException { int statusCode = response.getStatusLine().getStatusCode(); if (statusCode < 200 || statusCode > 299) { throw new IOException("Bad Auth Response: " + Integer.toString(statusCode)); } } private JSONObject responseToJson(HttpResponse response) throws UnsupportedEncodingException, IOException, JSONException { BufferedReader reader = new BufferedReader(new InputStreamReader( response.getEntity().getContent(), "UTF-8")); StringBuilder builder = new StringBuilder(); for (String line = null; (line = reader.readLine()) != null;) { builder.append(line).append("\n"); } return new JSONObject(builder.toString()); } private String buildLoginUrl() { String token_name = BASE_TOKEN_NAME + Build.MODEL; String login_url = LOGIN_URL; try { login_url += URLEncoder.encode(token_name, UTF8); } catch (UnsupportedEncodingException e) { login_url += "Android"; } return login_url; } private void ping_u1_url(String username) { try { String ping_url = PING_URL + username; HttpGet request = new HttpGet(ping_url); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpResponse response = null; int retries = 3; while (retries-- > 0) { signRequest(request); response = httpClient.execute(request); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 400 || statusCode == 401) { Log.e("MobileOrg", "Ping failed"); invalidate(); } else { return; } } } catch (Exception e) { Log.e("MobileOrg", "Exception in Ubuntu One Ping: " + e.toString()); } // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } catch (ClientProtocolException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } } }
true
true
public void putRemoteFile(String filename, String contents) throws IOException { try { buildConsumer(); String latterPart = remoteIndexPath + filename; latterPart = latterPart.replaceAll("/{2,}", "/"); String files_url = FILES_URL + root_path + latterPart; URL url = new URL(files_url); URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef()); url = uri.toURL(); HttpPut request = new HttpPut(url.toString()); JSONObject createFile = new JSONObject(); createFile.put("kind", "file"); StringEntity se = new StringEntity(createFile.toString()); //se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); request.setEntity(se); DefaultHttpClient httpClient = new DefaultHttpClient(); signRequest(request); HttpResponse response = httpClient.execute(request); verifyResponse(response); JSONObject fileData = responseToJson(response); String content_path = fileData.getString("content_path"); String content_url = FILES_BASE + content_path; url = new URL(content_url); uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef()); url = uri.toURL(); request = new HttpPut(url.toString()); request.setEntity(new StringEntity(contents)); httpClient = new DefaultHttpClient(); signRequest(request); response = httpClient.execute(request); verifyResponse(response); } catch (Exception e) { Log.e("MobileOrg", "Exception in Ubuntu One Put File: " + e.toString()); } }
public void putRemoteFile(String filename, String contents) throws IOException { try { buildConsumer(); String latterPart = remoteIndexPath + filename; latterPart = latterPart.replaceAll("/{2,}", "/"); String files_url = FILES_URL + root_path + latterPart; URL url = new URL(files_url); URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef()); url = uri.toURL(); HttpPut request = new HttpPut(url.toString()); JSONObject createFile = new JSONObject(); createFile.put("kind", "file"); StringEntity se = new StringEntity(createFile.toString()); //se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); request.setEntity(se); DefaultHttpClient httpClient = new DefaultHttpClient(); signRequest(request); HttpResponse response = httpClient.execute(request); verifyResponse(response); JSONObject fileData = responseToJson(response); String content_path = fileData.getString("content_path"); String content_url = FILES_BASE + content_path; url = new URL(content_url); uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef()); url = uri.toURL(); request = new HttpPut(url.toString()); request.setEntity(new StringEntity(contents)); httpClient = new DefaultHttpClient(); signRequest(request); response = httpClient.execute(request); verifyResponse(response); } catch (Exception e) { Log.e("MobileOrg", "Exception in Ubuntu One Put File: " + e.toString()); throw new IOException("Uploading: " + filename + ": " + e.toString()); } }
diff --git a/org.amanzi.awe.afp/src/org/amanzi/awe/afp/exporters/AfpExporter.java b/org.amanzi.awe.afp/src/org/amanzi/awe/afp/exporters/AfpExporter.java index 9adc73e87..c5058941e 100644 --- a/org.amanzi.awe.afp/src/org/amanzi/awe/afp/exporters/AfpExporter.java +++ b/org.amanzi.awe.afp/src/org/amanzi/awe/afp/exporters/AfpExporter.java @@ -1,815 +1,820 @@ package org.amanzi.awe.afp.exporters; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.HashMap; import org.amanzi.awe.afp.filters.AfpRowFilter; import org.amanzi.awe.afp.models.AfpFrequencyDomainModel; import org.amanzi.awe.afp.models.AfpModel; import org.amanzi.awe.afp.models.AfpModelUtils; import org.amanzi.awe.console.AweConsolePlugin; import org.amanzi.neo.services.INeoConstants; import org.amanzi.neo.services.enums.DatasetRelationshipTypes; import org.amanzi.neo.services.enums.NetworkRelationshipTypes; import org.amanzi.neo.services.enums.NodeTypes; import org.amanzi.neo.services.node2node.NodeToNodeTypes; import org.amanzi.neo.services.node2node.NodeToNodeRelationService.NodeToNodeRelationshipTypes; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.neo4j.graphdb.Direction; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Relationship; import org.neo4j.graphdb.RelationshipType; import org.neo4j.graphdb.ReturnableEvaluator; import org.neo4j.graphdb.StopEvaluator; import org.neo4j.graphdb.TraversalPosition; import org.neo4j.graphdb.Traverser; import org.neo4j.graphdb.Traverser.Order; /** * Writes the data from the neo4j database to external file * * @author Rahul * */ public class AfpExporter extends Job{ private Node afpRoot; private Node afpDataset; protected static final String AMANZI_STR = ".amanzi"; private static final String DATA_SAVER_DIR = "AfpTemp"; public static final String tmpAfpFolder = getTmpFolderPath(); public static final String PATH_SEPARATOR = "/"; public static final int CONTROL = 0; public static final int CELL = 1; public static final int INTERFERENCE = 2; public static final int NEIGHBOUR = 3; public static final int FORBIDDEN = 4; public static final int EXCEPTION = 5; public static final int CLIQUES = 6; /** The Control File*/ public final String[] fileNames = { "InputControlFile.awe" , "InputCellFile.awe" ,"InputInterferenceFile.awe" ,"InputNeighboursFile.awe" ,"InputForbiddenFile.awe" ,"InputExceptionFile.awe" ,"InputCliquesFile.awe" }; public String[] domainDirPaths; public final String logFileName = "logfile.awe"; public final String outputFileName = "outputFile.awe"; private int maxTRX = -1; private File[] files; private File[][] inputFiles; private AfpModel model; AfpFrequencyDomainModel models[]; public static final int NEIGH = 0; public static final int INTERFER = 1; public static final int TRIANGULATION = 2; public static final int SHADOWING = 3; public static final int CoA = 0; public static final int AdA = 1; public static final int CoT = 2; public static final int AdT = 3; public static final float CO_SITE_SCALING_FACTOR = 1; public static final float CO_SECTOR_SCALING_FACTOR = 1; // default values of the Control file int defaultGMaxRTperCell = 1; int defaultSiteSpacing = 2; int defaultCellSpacing = 0; int defaultRegNbrSpacing=1; int defaultMinNbrSpacing =0; int defaultSecondNbrSpacing = 1; int defaultRecalculateAll=1; int defaultUseTraffic=1; int defaultUseSONbrs=0; int defaultQuality=100; int defaultDecomposeInCliques=0; int defaultExistCliques=0; int defaultHoppingType=0; int defaultUseGrouping=0; int defaultNrOfGroups=1; static int count; public AfpExporter(Node afpRoot, Node afpDataset, AfpModel model){ super("Write Input files"); this.afpRoot = afpRoot; this.afpDataset = afpDataset; this.model = model; } @Override public IStatus run(IProgressMonitor monitor) { createFiles(); writeFilesNew(monitor); return Status.OK_STATUS; } private void createFiles(){ createTmpFolder(); models = model.getFreqDomains(false).toArray(new AfpFrequencyDomainModel[0]); inputFiles = new File[models.length][fileNames.length]; domainDirPaths = new String[models.length]; for(int i = 0; i < models.length; i++){ String dirName = models[i].getName(); try { File modelDir = new File(tmpAfpFolder + dirName); if (!modelDir.exists()) modelDir.mkdir(); domainDirPaths[i] = modelDir.getAbsolutePath() + PATH_SEPARATOR; for (int j = 0; j < fileNames.length; j++){ inputFiles[i][j] = new File(tmpAfpFolder + dirName + PATH_SEPARATOR + fileNames[j]); inputFiles[i][j].createNewFile(); } } catch (IOException e) { AweConsolePlugin.exception(e); } } } public void writeFilesNew(IProgressMonitor monitor){ monitor.beginTask("Write Files", model.getTotalTRX()); Traverser sectorTraverser = model.getTRXList(null); try { BufferedWriter[] cellWriters = new BufferedWriter[models.length]; BufferedWriter[] intWriters = new BufferedWriter[models.length]; for(int i = 0; i < models.length; i++){ cellWriters[i] = new BufferedWriter(new FileWriter(inputFiles[i][CELL])); intWriters[i] = new BufferedWriter(new FileWriter(inputFiles[i][INTERFERENCE])); } for (Node sectorNode : sectorTraverser) { HashMap<Node,String[][]> sectorIntValues = getSectorInterferenceValues(sectorNode); Traverser trxTraverser = AfpModelUtils.getTrxTraverser(sectorNode); for (Node trxNode: trxTraverser){ count++; monitor.worked(1); if (count %100 == 0) AweConsolePlugin.info(count + " trxs processed"); for (int i = 0; i < models.length; i++){ AfpFrequencyDomainModel mod = models[i]; String filterString = mod.getFilters(); if (filterString != null && !filterString.trim().isEmpty()){ AfpRowFilter rf = AfpRowFilter.getFilter(mod.getFilters()); if (rf != null){ if (rf.equal(trxNode)){ ArrayList<Integer> freq = new ArrayList<Integer>(); StringBuilder sb = new StringBuilder(); sb.append(Long.toString(trxNode.getId())); sb.append(" "); // String trxNo = (String)trxNode.getProperty(INeoConstants.PROPERTY_NAME_NAME, "0"); // if (Character.isLetter(trxNo.charAt(0))){ // trxNo = Integer.toString(Character.getNumericValue(trxNo.charAt(0)) - Character.getNumericValue('A')+ 1); // } for (Node plan : trxNode.traverse(Order.DEPTH_FIRST, StopEvaluator.DEPTH_ONE, new ReturnableEvaluator(){ @Override public boolean isReturnableNode(TraversalPosition pos) { if (pos.currentNode().getProperty(INeoConstants.PROPERTY_NAME_NAME, "").equals("original")) return true; if(pos.currentNode().getProperty(INeoConstants.AFP_PROPERTY_ORIGINAL_NAME, true).equals(true)) return true; return false; } }, DatasetRelationshipTypes.PLAN_ENTRY, Direction.OUTGOING)){ try{ Integer[] frequencies = (Integer[])plan.getProperty("arfcn", new Integer[0]); for(Integer f : frequencies) freq.add(f); }catch (ClassCastException e){ int[] frequencies = (int[])plan.getProperty("arfcn", new int[0]); for(int f : frequencies) freq.add(f); } } Integer[] freqArray = freq.toArray(new Integer[0]); if (freqArray.length > 1){ for (int j = 0; j < freqArray.length; j++){ sb.append(1 + "-");//add trxid as 1 always sb.append(j); sb.append(" "); sb.append(1);//non-relevant sb.append(" "); sb.append(1);//required sb.append(" "); sb.append(1);//given sb.append(" " + freqArray[i]);//required frequencies sb.append("\n"); cellWriters[i].write(sb.toString()); } } else{ sb.append(1); sb.append(" "); sb.append(1);//non-relevant sb.append(" "); sb.append(1);//required sb.append(" "); sb.append(1);//given sb.append(" " + freqArray[0]);//required frequencies sb.append("\n"); cellWriters[i].write(sb.toString()); } writeInterferenceForTrx(sectorNode, trxNode, intWriters[i], sectorIntValues, rf); } } } } } } //close the writers and create control files for (int i = 0; i < models.length; i++){ cellWriters[i].close(); intWriters[i].close(); createControlFile(i); } } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } private void writeInterferenceForTrx(Node sector, Node trx, BufferedWriter intWriter, HashMap<Node,String[][]> sectorIntValues, AfpRowFilter rf) throws IOException{ DecimalFormat df = new DecimalFormat("0.0000000000"); StringBuilder trxSb = new StringBuilder(); trxSb.append("SUBCELL 0 0 1 1 "); int numberofinterferers = 0; StringBuilder sbAllInt = new StringBuilder(); for(Node intSector : sectorIntValues.keySet()){ for (Node intTrx : intSector.traverse(Order.DEPTH_FIRST, StopEvaluator.DEPTH_ONE, new ReturnableEvaluator(){ @Override public boolean isReturnableNode(TraversalPosition pos) { if (pos.currentNode().getProperty(INeoConstants.PROPERTY_TYPE_NAME).equals(NodeTypes.TRX.getId())) return true; return false; } }, NetworkRelationshipTypes.CHILD, Direction.OUTGOING)){ String trxId = (String)trx.getProperty(INeoConstants.PROPERTY_NAME_NAME, "0"); if (sector.equals(intSector) && trxId.equals((String)trx.getProperty(INeoConstants.PROPERTY_NAME_NAME, "0"))) continue; if (rf != null){ if (!(rf.equal(intTrx))){ continue; } } // char c = trxId.charAt(0); // if (Character.isDigit(c)){ // c = (char)((c- '1') + 'A'); // } StringBuilder sbSubCell = new StringBuilder(); sbSubCell.append("INT 0\t0\t"); // String[] values = sectorIntValues.get(intSector)[1]; float[] trxValues = calculateInterference(trx, intTrx, sectorIntValues.get(intSector)); for (int i = 0; i < trxValues.length; i++){ sbSubCell.append(df.format(trxValues[i]) + " "); } sbSubCell.append(intTrx.getId()); sbSubCell.append("A"); sbAllInt.append(sbSubCell); sbAllInt.append("\n"); numberofinterferers++; } } String trxId = (String)trx.getProperty(INeoConstants.PROPERTY_NAME_NAME, "0"); // char c = trxId.charAt(0); // if (Character.isDigit(c)){ // c = (char)((c- '1') + 'A'); // } trxSb.append(numberofinterferers); trxSb.append(" "); trxSb.append(trx.getId()); trxSb.append("A"); trxSb.append("\n"); if(numberofinterferers >0) { intWriter.write(trxSb.toString()); intWriter.write(sbAllInt.toString()); } } private float[] calculateInterference(Node trx1, Node trx2, String[][] values){ Node sector1 = trx1.getSingleRelationship(NetworkRelationshipTypes.CHILD, Direction.INCOMING).getStartNode(); Node sector2 = trx2.getSingleRelationship(NetworkRelationshipTypes.CHILD, Direction.INCOMING).getStartNode(); Node site1 = sector1.getSingleRelationship(NetworkRelationshipTypes.CHILD, Direction.INCOMING).getStartNode(); Node site2 = sector2.getSingleRelationship(NetworkRelationshipTypes.CHILD, Direction.INCOMING).getStartNode(); float[] calculatedValues = new float[4]; boolean isBCCH1 = false; boolean isHopping1 = false; boolean isBCCH2 = false; boolean isHopping2 = false; int index = 0; if ((Boolean)trx1.getProperty(INeoConstants.PROPERTY_BCCH_NAME)) isBCCH1 = true; if ((Integer)trx1.getProperty(INeoConstants.PROPERTY_HOPPING_TYPE_NAME) >= 1) isHopping1 = true; if ((Boolean)trx2.getProperty(INeoConstants.PROPERTY_BCCH_NAME)) isBCCH2 = true; if ((Integer)trx2.getProperty(INeoConstants.PROPERTY_HOPPING_TYPE_NAME) >= 1) isHopping2 = true; if (isBCCH1){ if (isBCCH2) index = AfpModel.BCCHBCCH; else index = isHopping2 ? AfpModel.BCCHSFH : AfpModel.BCCHNHBB; } else if (isHopping1){ if (isBCCH2) index = AfpModel.SFHBCCH; else index = isHopping2 ? AfpModel.SFHSFH : AfpModel.SFHNHBB; } else{ if (isBCCH2) index = AfpModel.NHBBBCCH; else index = isHopping2 ? AfpModel.NHBBSFH : AfpModel.NHBBNHBB; } for (int j = 0; j < values[0].length; j++){ //CoA float val = 0; for (int i = 0; i < values.length; i++){ try{ val = Float.parseFloat(values[i][j]); } catch(Exception e){ val = 0; } float scalingFactor = 0; if (j ==CoA || j == CoT){ if (i == NEIGH){ scalingFactor = model.coNeighbor[index] / 100; } else if (i == INTERFER){ scalingFactor = model.coInterference[index] / 100; } else if (i == TRIANGULATION){ scalingFactor = model.coTriangulation[index] / 100; } else if (i == SHADOWING){ scalingFactor = model.coShadowing[index] / 100; } } else if (j ==AdA || j == AdT){ if (i == NEIGH){ scalingFactor = model.adjNeighbor[index] / 100; } else if (i == INTERFER){ scalingFactor = model.adjInterference[index] / 100; } else if (i == TRIANGULATION){ scalingFactor = model.adjTriangulation[index] / 100; } else if (i == SHADOWING){ scalingFactor = model.adjShadowing[index] / 100; } } calculatedValues[j] += val*scalingFactor; } //co-site if (site1.equals(site2)){ calculatedValues[j] += CO_SITE_SCALING_FACTOR * model.siteSeparation[index] / 100; } if (sector1.equals(sector2)){ calculatedValues[j] += CO_SECTOR_SCALING_FACTOR * model.sectorSeparation[index] / 100; } } return calculatedValues; } public HashMap<Node,String[][]> getSectorInterferenceValues(Node sector){ DecimalFormat df = new DecimalFormat("0.0000000000"); //values in 2-D array for each interfering node //array[neighbourArray, intArray, TriArray, shadowArray] //neighbourArray[CoA, AdjA, CoT, AdjT] HashMap<Node, String[][]> intValues = new HashMap<Node, String[][]>(); //Add this sector to calculate co-sector TRXs String[][] coSectorTrxValues = new String[][]{ {Float.toString(1),Float.toString(1),Float.toString(1),Float.toString(1)}, {},{},{}}; intValues.put(sector, coSectorTrxValues); for (Node proxySector : sector.traverse(Order.DEPTH_FIRST, StopEvaluator.DEPTH_ONE, new ReturnableEvaluator(){ @Override public boolean isReturnableNode(TraversalPosition pos) { if (pos.currentNode().getProperty(INeoConstants.PROPERTY_TYPE_NAME).equals(NodeTypes.SECTOR_SECTOR_RELATIONS.getId()) || pos.currentNode().getProperty(INeoConstants.PROPERTY_TYPE_NAME).equals(NodeTypes.PROXY.getId())) return true; return false; } }, NetworkRelationshipTypes.INTERFERENCE, Direction.OUTGOING, NetworkRelationshipTypes.NEIGHBOURS, Direction.OUTGOING, DatasetRelationshipTypes.PROXY, Direction.OUTGOING)){ for (Relationship relation : proxySector.getRelationships(NetworkRelationshipTypes.INTERFERS, NetworkRelationshipTypes.NEIGHBOUR, NodeToNodeRelationshipTypes.PROXYS)){ if (relation.getEndNode().equals(proxySector)) continue; - Node intSector = null; Node intProxySector = relation.getEndNode(); - intSector = intProxySector.getSingleRelationship(DatasetRelationshipTypes.PROXY, Direction.INCOMING).getStartNode(); - if(intSector == null){ - intSector = intProxySector.getSingleRelationship(NetworkRelationshipTypes.INTERFERENCE, Direction.INCOMING).getStartNode(); + Relationship relationship = null; + relationship = intProxySector.getSingleRelationship(DatasetRelationshipTypes.PROXY, Direction.INCOMING); + if(relationship == null){ + relationship = intProxySector.getSingleRelationship(NetworkRelationshipTypes.INTERFERENCE, Direction.INCOMING); + } + if(relationship == null){ + relationship = intProxySector.getSingleRelationship(NetworkRelationshipTypes.NEIGHBOURS, Direction.INCOMING); } - if(intSector == null){ - intSector = intProxySector.getSingleRelationship(NetworkRelationshipTypes.NEIGHBOURS, Direction.INCOMING).getStartNode(); + if(relationship == null) { + continue; } + Node intSector = null; + intSector = relationship.getStartNode(); RelationshipType type = relation.getType(); boolean isProxy = false; int typeIndex = NEIGH; if (type.equals(NodeToNodeRelationshipTypes.PROXYS)){ isProxy = true; Node fileNode = intProxySector.getSingleRelationship(NetworkRelationshipTypes.CHILD, Direction.INCOMING).getStartNode(); if (fileNode.getProperty("node2node", "").equals(NodeToNodeTypes.NEIGHBOURS)) typeIndex = NEIGH; else if (fileNode.getProperty("node2node", "").equals(NodeToNodeTypes.INTERFERENCE_MATRIX)) typeIndex = INTERFER; else if (fileNode.getProperty("node2node", "").equals(NodeToNodeTypes.TRIANGULATION)) typeIndex = TRIANGULATION; else if (fileNode.getProperty("node2node", "").equals(NodeToNodeTypes.SHADOWING)) typeIndex = SHADOWING; } else if (type.equals(NetworkRelationshipTypes.NEIGHBOUR)) typeIndex = NEIGH; else if (type.equals(NetworkRelationshipTypes.INTERFERS)) typeIndex = INTERFER; String[][] prevValue = new String[4][4]; if (intValues.containsKey(intSector)) prevValue = intValues.get(intSector); String[] value = new String[4]; if (isProxy){ try { value[CoA] = df.format(relation.getProperty("co", "0")).toString(); } catch (Exception e) { value[CoA] = (String)relation.getProperty("co", "0"); } try { value[AdA] = df.format(relation.getProperty("adj", "0")).toString(); } catch (Exception e) { value[AdA] = (String)relation.getProperty("adj", "0"); } try { value[CoT] = df.format(relation.getProperty("coT", "0")).toString(); } catch (Exception e) { value[CoT] = (String)relation.getProperty("coT", "0"); } try { value[AdT] = df.format(relation.getProperty("adjT", "0")).toString(); } catch (Exception e) { value[AdT] = (String)relation.getProperty("adjT", "0"); } } else if (typeIndex == INTERFER){ try { value[CoA] = df.format(relation.getProperty("CoA", "0")).toString(); } catch (Exception e) { value[CoA] = (String)relation.getProperty("CoA", "0"); } try { value[AdA] = df.format(relation.getProperty("AdA", "0")).toString(); } catch (Exception e) { value[AdA] = (String)relation.getProperty("AdA", "0"); } try { value[CoT] = df.format(relation.getProperty("CoT", "0")).toString(); } catch (Exception e) { value[CoT] = (String)relation.getProperty("CoT", "0"); } try { value[AdT] = df.format(relation.getProperty("AdT", "0")).toString(); } catch (Exception e) { value[AdT] = (String)relation.getProperty("AdT", "0"); } }//end if else if(typeIndex == NEIGH){ value[CoA] = Double.toString(0.5); value[AdA] = Double.toString(0.05); value[CoT] = Double.toString(0.5); value[AdT] = Double.toString(0.05); } prevValue[typeIndex] = value; intValues.put(intSector, prevValue); } } return intValues; } /** * Creates the Control file to be given as input to the C++ engine */ public void createControlFile(int domainIndex){ if (maxTRX < 0) { maxTRX = defaultGMaxRTperCell; } try { BufferedWriter writer = new BufferedWriter(new FileWriter( inputFiles[domainIndex][CONTROL])); writer.write("SiteSpacing " + defaultSiteSpacing); writer.newLine(); writer.write("CellSpacing " + defaultCellSpacing); writer.newLine(); writer.write("RegNbrSpacing " + defaultRegNbrSpacing); writer.newLine(); writer.write("MinNbrSpacing " + defaultMinNbrSpacing); writer.newLine(); writer.write("SecondNbrSpacing " + defaultSecondNbrSpacing); writer.newLine(); writer.write("RecalculateAll " + defaultRecalculateAll); writer.newLine(); writer.write("UseTraffic " + defaultUseTraffic); writer.newLine(); writer.write("UseSONbrs " + defaultUseSONbrs); writer.newLine(); writer.write("Quality " + defaultQuality); writer.newLine(); writer.write("DecomposeInCliques " + defaultDecomposeInCliques); writer.newLine(); writer.write("ExistCliques " + defaultExistCliques); writer.newLine(); writer.write("GMaxRTperCell " + maxTRX); writer.newLine(); writer.write("GMaxRTperSite " + maxTRX); writer.newLine(); writer.write("HoppingType " + defaultHoppingType); writer.newLine(); writer.write("UseGrouping " + defaultUseGrouping); writer.newLine(); writer.write("NrOfGroups " + defaultNrOfGroups); writer.newLine(); writer.write("LogFile " + "\"" + this.domainDirPaths[domainIndex] + this.logFileName + "\""); writer.newLine(); // TBD count TRXs writer.write("CellCardinality " + "0"); writer.newLine(); writer.write("CellFile " + "\"" + this.inputFiles[domainIndex][CELL].getAbsolutePath() + "\""); writer.newLine(); writer.write("NeighboursFile " + "\"" + this.inputFiles[domainIndex][NEIGHBOUR].getAbsolutePath() + "\""); writer.newLine(); writer.write("InterferenceFile " + "\"" + this.inputFiles[domainIndex][INTERFERENCE].getAbsolutePath() + "\""); writer.newLine(); writer.write("OutputFile " + "\"" + this.domainDirPaths[domainIndex] + this.outputFileName + "\""); writer.newLine(); writer.write("CliquesFile " + "\"" + this.inputFiles[domainIndex][CLIQUES].getAbsolutePath() + "\""); writer.newLine(); writer.write("ForbiddenFile " + "\"" + this.inputFiles[domainIndex][FORBIDDEN].getAbsolutePath() + "\""); writer.newLine(); writer.write("ExceptionFile " + "\"" + this.inputFiles[domainIndex][EXCEPTION].getAbsolutePath() + "\""); writer.newLine(); writer.write("Carriers " + parseCarriers(getFrequencies(domainIndex))); writer.newLine(); writer.close(); }catch (Exception e){ AweConsolePlugin.exception(e); } } private String getFrequencies(int domainIndex) { StringBuffer carriers = new StringBuffer(); int cnt =0; boolean first = true; String[] franges = models[domainIndex].getFrequencies(); String[] freqList = AfpModel.rangeArraytoArray(franges); for(String f: freqList) { if(!first) { carriers.append(","); } carriers.append(f); cnt++; first = false; } return carriers.toString(); } private String parseCarriers(String commaSeparated){ int numCarriers = commaSeparated.split("\\,").length; String spaceSeparated = commaSeparated.replaceAll(",", " "); spaceSeparated = numCarriers + " " + spaceSeparated; return spaceSeparated; } /** * Gets the site name and sector no of the sector * @param sector the sector node * @return string array containg site name and sector no */ public String[] parseSectorName(Node sector){ Node site = sector.getSingleRelationship(NetworkRelationshipTypes.CHILD, Direction.INCOMING).getOtherNode(sector); String siteName = site.getProperty(INeoConstants.PROPERTY_NAME_NAME).toString(); String sectorValues[] = new String[2]; sectorValues[0] = siteName; String sectorName = sector.getProperty(INeoConstants.PROPERTY_NAME_NAME).toString(); if (sectorName.length() > siteName.length() && sectorName.substring(0, siteName.length()).equals(siteName)){ sectorValues[1] = sector.getProperty(INeoConstants.PROPERTY_NAME_NAME).toString().substring(siteName.length()); } else sectorValues[1] = sectorName; char sectorNo = sectorValues[1].charAt(sectorValues[1].length() - 1); if (Character.isLetter(sectorNo)) sectorValues[1] = //sectorValues[1].substring(0, sectorValues[1].length() - 1) + Integer.toString(Character.getNumericValue(sectorNo) - Character.getNumericValue('A')+ 1); return sectorValues; } public String getSectorNameForInterList(Node sector){ Node site = sector.getSingleRelationship(NetworkRelationshipTypes.CHILD, Direction.INCOMING).getOtherNode(sector); String siteName = site.getProperty(INeoConstants.PROPERTY_NAME_NAME).toString(); String sectorName = sector.getProperty(INeoConstants.PROPERTY_NAME_NAME).toString(); if (sectorName.length() > siteName.length() && sectorName.substring(0, siteName.length()).equals(siteName)){ sectorName = sector.getProperty(INeoConstants.PROPERTY_NAME_NAME).toString().substring(siteName.length()); } char sectorNo = sectorName.charAt(sectorName.length() - 1); if (Character.isDigit(sectorNo)) sectorName = siteName + sectorNo; else sectorName = siteName + (Character.getNumericValue(sectorNo) - Character.getNumericValue('A')+ 1); return sectorName; } public String[] getAllTrxNames(Node sector){ ArrayList<String> names = new ArrayList<String>(); for (Node trx : sector.traverse(Order.DEPTH_FIRST, StopEvaluator.END_OF_GRAPH, new ReturnableEvaluator(){ @Override public boolean isReturnableNode(TraversalPosition pos) { if (pos.currentNode().getProperty(INeoConstants.PROPERTY_TYPE_NAME).equals(NodeTypes.TRX.getId())) return true; return false; } }, NetworkRelationshipTypes.CHILD, Direction.OUTGOING)){ String name = (String)trx.getProperty(INeoConstants.PROPERTY_NAME_NAME, ""); if (Character.isDigit(name.charAt(0))){ // name = Integer.toString(Character.getNumericValue(name.charAt(0)) - Character.getNumericValue('A')+ 1); name = Character.toString((char)(name.charAt(0) + 'A' - '1')); // name = Integer.toString(); } names.add(name); } return names.toArray(new String[0]); } private void createTmpFolder(){ File file = new File(this.tmpAfpFolder); if (!file.exists()) file.mkdir(); } public static String getTmpFolderPath(){ File dir = new File(System.getProperty("user.home")); if (!dir.exists()) { dir.mkdir(); } dir = new File(dir, AMANZI_STR); if (!dir.exists()) { dir.mkdir(); } dir = new File(dir, DATA_SAVER_DIR); if (!dir.exists()) { dir.mkdir(); } return dir.getPath() + PATH_SEPARATOR; } }
false
true
public HashMap<Node,String[][]> getSectorInterferenceValues(Node sector){ DecimalFormat df = new DecimalFormat("0.0000000000"); //values in 2-D array for each interfering node //array[neighbourArray, intArray, TriArray, shadowArray] //neighbourArray[CoA, AdjA, CoT, AdjT] HashMap<Node, String[][]> intValues = new HashMap<Node, String[][]>(); //Add this sector to calculate co-sector TRXs String[][] coSectorTrxValues = new String[][]{ {Float.toString(1),Float.toString(1),Float.toString(1),Float.toString(1)}, {},{},{}}; intValues.put(sector, coSectorTrxValues); for (Node proxySector : sector.traverse(Order.DEPTH_FIRST, StopEvaluator.DEPTH_ONE, new ReturnableEvaluator(){ @Override public boolean isReturnableNode(TraversalPosition pos) { if (pos.currentNode().getProperty(INeoConstants.PROPERTY_TYPE_NAME).equals(NodeTypes.SECTOR_SECTOR_RELATIONS.getId()) || pos.currentNode().getProperty(INeoConstants.PROPERTY_TYPE_NAME).equals(NodeTypes.PROXY.getId())) return true; return false; } }, NetworkRelationshipTypes.INTERFERENCE, Direction.OUTGOING, NetworkRelationshipTypes.NEIGHBOURS, Direction.OUTGOING, DatasetRelationshipTypes.PROXY, Direction.OUTGOING)){ for (Relationship relation : proxySector.getRelationships(NetworkRelationshipTypes.INTERFERS, NetworkRelationshipTypes.NEIGHBOUR, NodeToNodeRelationshipTypes.PROXYS)){ if (relation.getEndNode().equals(proxySector)) continue; Node intSector = null; Node intProxySector = relation.getEndNode(); intSector = intProxySector.getSingleRelationship(DatasetRelationshipTypes.PROXY, Direction.INCOMING).getStartNode(); if(intSector == null){ intSector = intProxySector.getSingleRelationship(NetworkRelationshipTypes.INTERFERENCE, Direction.INCOMING).getStartNode(); } if(intSector == null){ intSector = intProxySector.getSingleRelationship(NetworkRelationshipTypes.NEIGHBOURS, Direction.INCOMING).getStartNode(); } RelationshipType type = relation.getType(); boolean isProxy = false; int typeIndex = NEIGH; if (type.equals(NodeToNodeRelationshipTypes.PROXYS)){ isProxy = true; Node fileNode = intProxySector.getSingleRelationship(NetworkRelationshipTypes.CHILD, Direction.INCOMING).getStartNode(); if (fileNode.getProperty("node2node", "").equals(NodeToNodeTypes.NEIGHBOURS)) typeIndex = NEIGH; else if (fileNode.getProperty("node2node", "").equals(NodeToNodeTypes.INTERFERENCE_MATRIX)) typeIndex = INTERFER; else if (fileNode.getProperty("node2node", "").equals(NodeToNodeTypes.TRIANGULATION)) typeIndex = TRIANGULATION; else if (fileNode.getProperty("node2node", "").equals(NodeToNodeTypes.SHADOWING)) typeIndex = SHADOWING; } else if (type.equals(NetworkRelationshipTypes.NEIGHBOUR)) typeIndex = NEIGH; else if (type.equals(NetworkRelationshipTypes.INTERFERS)) typeIndex = INTERFER; String[][] prevValue = new String[4][4]; if (intValues.containsKey(intSector)) prevValue = intValues.get(intSector); String[] value = new String[4]; if (isProxy){ try { value[CoA] = df.format(relation.getProperty("co", "0")).toString(); } catch (Exception e) { value[CoA] = (String)relation.getProperty("co", "0"); } try { value[AdA] = df.format(relation.getProperty("adj", "0")).toString(); } catch (Exception e) { value[AdA] = (String)relation.getProperty("adj", "0"); } try { value[CoT] = df.format(relation.getProperty("coT", "0")).toString(); } catch (Exception e) { value[CoT] = (String)relation.getProperty("coT", "0"); } try { value[AdT] = df.format(relation.getProperty("adjT", "0")).toString(); } catch (Exception e) { value[AdT] = (String)relation.getProperty("adjT", "0"); } } else if (typeIndex == INTERFER){ try { value[CoA] = df.format(relation.getProperty("CoA", "0")).toString(); } catch (Exception e) { value[CoA] = (String)relation.getProperty("CoA", "0"); } try { value[AdA] = df.format(relation.getProperty("AdA", "0")).toString(); } catch (Exception e) { value[AdA] = (String)relation.getProperty("AdA", "0"); } try { value[CoT] = df.format(relation.getProperty("CoT", "0")).toString(); } catch (Exception e) { value[CoT] = (String)relation.getProperty("CoT", "0"); } try { value[AdT] = df.format(relation.getProperty("AdT", "0")).toString(); } catch (Exception e) { value[AdT] = (String)relation.getProperty("AdT", "0"); } }//end if else if(typeIndex == NEIGH){ value[CoA] = Double.toString(0.5); value[AdA] = Double.toString(0.05); value[CoT] = Double.toString(0.5); value[AdT] = Double.toString(0.05); } prevValue[typeIndex] = value; intValues.put(intSector, prevValue); } } return intValues; }
public HashMap<Node,String[][]> getSectorInterferenceValues(Node sector){ DecimalFormat df = new DecimalFormat("0.0000000000"); //values in 2-D array for each interfering node //array[neighbourArray, intArray, TriArray, shadowArray] //neighbourArray[CoA, AdjA, CoT, AdjT] HashMap<Node, String[][]> intValues = new HashMap<Node, String[][]>(); //Add this sector to calculate co-sector TRXs String[][] coSectorTrxValues = new String[][]{ {Float.toString(1),Float.toString(1),Float.toString(1),Float.toString(1)}, {},{},{}}; intValues.put(sector, coSectorTrxValues); for (Node proxySector : sector.traverse(Order.DEPTH_FIRST, StopEvaluator.DEPTH_ONE, new ReturnableEvaluator(){ @Override public boolean isReturnableNode(TraversalPosition pos) { if (pos.currentNode().getProperty(INeoConstants.PROPERTY_TYPE_NAME).equals(NodeTypes.SECTOR_SECTOR_RELATIONS.getId()) || pos.currentNode().getProperty(INeoConstants.PROPERTY_TYPE_NAME).equals(NodeTypes.PROXY.getId())) return true; return false; } }, NetworkRelationshipTypes.INTERFERENCE, Direction.OUTGOING, NetworkRelationshipTypes.NEIGHBOURS, Direction.OUTGOING, DatasetRelationshipTypes.PROXY, Direction.OUTGOING)){ for (Relationship relation : proxySector.getRelationships(NetworkRelationshipTypes.INTERFERS, NetworkRelationshipTypes.NEIGHBOUR, NodeToNodeRelationshipTypes.PROXYS)){ if (relation.getEndNode().equals(proxySector)) continue; Node intProxySector = relation.getEndNode(); Relationship relationship = null; relationship = intProxySector.getSingleRelationship(DatasetRelationshipTypes.PROXY, Direction.INCOMING); if(relationship == null){ relationship = intProxySector.getSingleRelationship(NetworkRelationshipTypes.INTERFERENCE, Direction.INCOMING); } if(relationship == null){ relationship = intProxySector.getSingleRelationship(NetworkRelationshipTypes.NEIGHBOURS, Direction.INCOMING); } if(relationship == null) { continue; } Node intSector = null; intSector = relationship.getStartNode(); RelationshipType type = relation.getType(); boolean isProxy = false; int typeIndex = NEIGH; if (type.equals(NodeToNodeRelationshipTypes.PROXYS)){ isProxy = true; Node fileNode = intProxySector.getSingleRelationship(NetworkRelationshipTypes.CHILD, Direction.INCOMING).getStartNode(); if (fileNode.getProperty("node2node", "").equals(NodeToNodeTypes.NEIGHBOURS)) typeIndex = NEIGH; else if (fileNode.getProperty("node2node", "").equals(NodeToNodeTypes.INTERFERENCE_MATRIX)) typeIndex = INTERFER; else if (fileNode.getProperty("node2node", "").equals(NodeToNodeTypes.TRIANGULATION)) typeIndex = TRIANGULATION; else if (fileNode.getProperty("node2node", "").equals(NodeToNodeTypes.SHADOWING)) typeIndex = SHADOWING; } else if (type.equals(NetworkRelationshipTypes.NEIGHBOUR)) typeIndex = NEIGH; else if (type.equals(NetworkRelationshipTypes.INTERFERS)) typeIndex = INTERFER; String[][] prevValue = new String[4][4]; if (intValues.containsKey(intSector)) prevValue = intValues.get(intSector); String[] value = new String[4]; if (isProxy){ try { value[CoA] = df.format(relation.getProperty("co", "0")).toString(); } catch (Exception e) { value[CoA] = (String)relation.getProperty("co", "0"); } try { value[AdA] = df.format(relation.getProperty("adj", "0")).toString(); } catch (Exception e) { value[AdA] = (String)relation.getProperty("adj", "0"); } try { value[CoT] = df.format(relation.getProperty("coT", "0")).toString(); } catch (Exception e) { value[CoT] = (String)relation.getProperty("coT", "0"); } try { value[AdT] = df.format(relation.getProperty("adjT", "0")).toString(); } catch (Exception e) { value[AdT] = (String)relation.getProperty("adjT", "0"); } } else if (typeIndex == INTERFER){ try { value[CoA] = df.format(relation.getProperty("CoA", "0")).toString(); } catch (Exception e) { value[CoA] = (String)relation.getProperty("CoA", "0"); } try { value[AdA] = df.format(relation.getProperty("AdA", "0")).toString(); } catch (Exception e) { value[AdA] = (String)relation.getProperty("AdA", "0"); } try { value[CoT] = df.format(relation.getProperty("CoT", "0")).toString(); } catch (Exception e) { value[CoT] = (String)relation.getProperty("CoT", "0"); } try { value[AdT] = df.format(relation.getProperty("AdT", "0")).toString(); } catch (Exception e) { value[AdT] = (String)relation.getProperty("AdT", "0"); } }//end if else if(typeIndex == NEIGH){ value[CoA] = Double.toString(0.5); value[AdA] = Double.toString(0.05); value[CoT] = Double.toString(0.5); value[AdT] = Double.toString(0.05); } prevValue[typeIndex] = value; intValues.put(intSector, prevValue); } } return intValues; }
diff --git a/ExportPlugin/src/org/gephi/io/exporter/plugin/ExporterGEXF2.java b/ExportPlugin/src/org/gephi/io/exporter/plugin/ExporterGEXF2.java index aae313190..43e072e54 100644 --- a/ExportPlugin/src/org/gephi/io/exporter/plugin/ExporterGEXF2.java +++ b/ExportPlugin/src/org/gephi/io/exporter/plugin/ExporterGEXF2.java @@ -1,685 +1,686 @@ /* Copyright 2008-2010 Gephi Authors : Mathieu Bastian <[email protected]> Website : http://www.gephi.org This file is part of Gephi. Gephi is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Gephi is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Gephi. If not, see <http://www.gnu.org/licenses/>. */ package org.gephi.io.exporter.plugin; import java.io.Writer; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import javanet.staxutils.IndentingXMLStreamWriter; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamWriter; import org.gephi.data.attributes.api.AttributeColumn; import org.gephi.data.attributes.api.AttributeModel; import org.gephi.data.attributes.api.AttributeOrigin; import org.gephi.data.attributes.api.AttributeRow; import org.gephi.data.attributes.api.AttributeTable; import org.gephi.data.attributes.api.AttributeType; import org.gephi.data.attributes.api.AttributeValue; import org.gephi.data.attributes.type.DynamicType; import org.gephi.data.attributes.type.Interval; import org.gephi.data.attributes.type.TimeInterval; import org.gephi.data.attributes.type.TypeConvertor; import org.gephi.dynamic.api.DynamicController; import org.gephi.dynamic.api.DynamicModel; import org.gephi.graph.api.DirectedGraph; import org.gephi.graph.api.Edge; import org.gephi.graph.api.EdgeIterable; import org.gephi.graph.api.Graph; import org.gephi.graph.api.GraphModel; import org.gephi.graph.api.HierarchicalGraph; import org.gephi.graph.api.Node; import org.gephi.graph.api.NodeData; import org.gephi.graph.api.NodeIterable; import org.gephi.graph.api.UndirectedGraph; import org.gephi.io.exporter.api.FileType; import org.gephi.io.exporter.spi.CharacterExporter; import org.gephi.io.exporter.spi.GraphExporter; import org.gephi.project.api.Workspace; import org.gephi.utils.longtask.spi.LongTask; import org.gephi.utils.progress.Progress; import org.gephi.utils.progress.ProgressTicket; import org.openide.util.Lookup; import org.openide.util.NbBundle; /** * * @author Mathieu Bastian */ public class ExporterGEXF2 implements GraphExporter, CharacterExporter, LongTask { //GEXF private static final String GEXF = "gexf"; private static final String GEXF_NAMESPACE = "http://www.gexf.net/1.1draft"; private static final String GEXF_NAMESPACE_LOCATION = "http://www.gexf.net/1.1draft http://www.gexf.net/1.1draft/gexf.xsd"; private static final String VIZ = "viz"; private static final String VIZ_NAMESPACE = "http://www.gexf.net/1.1draft/viz"; private static final String GEXF_VERSION = "version"; private static final String GRAPH = "graph"; private static final String GRAPH_DEFAULT_EDGETYPE = "defaultedgetype"; private static final String GRAPH_START = "start"; private static final String GRAPH_END = "end"; private static final String META = "meta"; private static final String META_LASTMODIFIEDDATE = "lastmodifieddate"; private static final String META_CREATOR = "creator"; private static final String META_DESCRIPTION = "description"; private static final String NODES = "nodes"; private static final String NODE = "node"; private static final String NODE_ID = "id"; private static final String NODE_LABEL = "label"; private static final String NODE_PID = "pid"; private static final String NODE_POSITION = "position"; private static final String NODE_COLOR = "color"; private static final String NODE_SIZE = "size"; private static final String EDGES = "edges"; private static final String EDGE = "edge"; private static final String EDGE_ID = "id"; private static final String EDGE_SOURCE = "source"; private static final String EDGE_TARGET = "target"; private static final String EDGE_LABEL = "label"; private static final String EDGE_TYPE = "type"; private static final String EDGE_WEIGHT = "weight"; private static final String EDGE_COLOR = "color"; private static final String START = "start"; private static final String END = "end"; private static final String SLICES = "slices"; private static final String SLICE = "slice"; private static final String ATTRIBUTE = "attribute"; private static final String ATTRIBUTE_ID = "id"; private static final String ATTRIBUTE_TITLE = "title"; private static final String ATTRIBUTE_TYPE = "type"; private static final String ATTRIBUTE_DEFAULT = "default"; private static final String ATTRIBUTES = "attributes"; private static final String ATTRIBUTES_CLASS = "class"; private static final String ATTRIBUTES_MODE = "mode"; private static final String ATTVALUE = "attvalue"; private static final String ATTVALUE_FOR = "for"; private static final String ATTVALUE_VALUE = "value"; //Architecture private boolean cancel = false; private ProgressTicket progress; private Workspace workspace; private boolean exportVisible; private Writer writer; private GraphModel graphModel; private AttributeModel attributeModel; private TimeInterval visibleInterval; //Settings private boolean normalize = false; private boolean exportColors = true; private boolean exportPosition = true; private boolean exportSize = true; private boolean exportAttributes = true; private boolean exportHierarchy = false; private boolean exportDynamic = true; //Settings Helper private float minSize; private float maxSize; private float minX; private float maxX; private float minY; private float maxY; private float minZ; private float maxZ; public boolean execute() { attributeModel = workspace.getLookup().lookup(AttributeModel.class); graphModel = workspace.getLookup().lookup(GraphModel.class); HierarchicalGraph graph = null; if (exportVisible) { graph = graphModel.getHierarchicalGraphVisible(); } else { graph = graphModel.getHierarchicalGraph(); } Progress.start(progress); graph.readLock(); //Options if (normalize) { calculateMinMax(graph); } //Calculate progress units count int max = 0; if (exportHierarchy) { for (Node n : graph.getNodesTree()) { max++; } for (Edge e : graph.getEdgesTree()) { max++; } } else { max = graph.getNodeCount(); for (Edge e : graph.getEdgesAndMetaEdges()) { max++; } } Progress.switchToDeterminate(progress, max); try { XMLOutputFactory outputFactory = XMLOutputFactory.newInstance(); outputFactory.setProperty("javax.xml.stream.isRepairingNamespaces", Boolean.FALSE); XMLStreamWriter xmlWriter = outputFactory.createXMLStreamWriter(writer); xmlWriter = new IndentingXMLStreamWriter(xmlWriter); xmlWriter.writeStartDocument("UTF-8", "1.0"); xmlWriter.setPrefix("", GEXF_NAMESPACE); xmlWriter.writeStartElement(GEXF_NAMESPACE, GEXF); xmlWriter.writeNamespace("", GEXF_NAMESPACE); xmlWriter.writeAttribute(GEXF_VERSION, "1.1"); if (exportColors || exportPosition || exportSize) { xmlWriter.writeNamespace(VIZ, VIZ_NAMESPACE); } + xmlWriter.writeAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); xmlWriter.writeAttribute("xsi:schemaLocation", GEXF_NAMESPACE_LOCATION); if (exportDynamic) { DynamicController dynamicController = Lookup.getDefault().lookup(DynamicController.class); DynamicModel dynamicModel = dynamicController != null ? dynamicController.getModel(workspace) : null; visibleInterval = dynamicModel == null ? null : exportVisible ? dynamicModel.getVisibleInterval() : new TimeInterval(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY); } writeMeta(xmlWriter); writeGraph(xmlWriter, graph); xmlWriter.writeEndElement(); xmlWriter.writeEndDocument(); xmlWriter.close(); } catch (Exception e) { if (e instanceof RuntimeException) { throw (RuntimeException) e; } throw new RuntimeException(e); } Progress.finish(progress); return !cancel; } private void writeGraph(XMLStreamWriter xmlWriter, HierarchicalGraph graph) throws Exception { xmlWriter.writeStartElement(GRAPH); xmlWriter.writeAttribute(GRAPH_DEFAULT_EDGETYPE, graph instanceof DirectedGraph ? "directed" : graph instanceof UndirectedGraph ? "undirected" : "mixed"); if (exportDynamic) { if (!Double.isInfinite(visibleInterval.getLow())) { String intervalLow = "" + visibleInterval.getLow(); xmlWriter.writeAttribute(START, intervalLow); } if (!Double.isInfinite(visibleInterval.getHigh())) { String intervalHigh = "" + visibleInterval.getHigh(); xmlWriter.writeAttribute(END, intervalHigh); } } writeAttributes(xmlWriter, attributeModel.getNodeTable()); writeAttributes(xmlWriter, attributeModel.getEdgeTable()); writeNodes(xmlWriter, graph); writeEdges(xmlWriter, graph); xmlWriter.writeEndElement(); } private void writeMeta(XMLStreamWriter xmlWriter) throws Exception { xmlWriter.writeStartElement(META); xmlWriter.writeAttribute(META_LASTMODIFIEDDATE, getDateTime()); xmlWriter.writeStartElement(META_CREATOR); xmlWriter.writeCharacters("Gephi 0.7"); xmlWriter.writeEndElement(); xmlWriter.writeStartElement(META_DESCRIPTION); xmlWriter.writeCharacters(""); xmlWriter.writeEndElement(); xmlWriter.writeEndElement(); } private void writeAttributes(XMLStreamWriter xmlWriter, AttributeTable table) throws Exception { boolean dataColumns = false; boolean dynamicColumns = false; for (AttributeColumn col : table.getColumns()) { if (!col.getOrigin().equals(AttributeOrigin.PROPERTY)) { dataColumns = true; } if (col.getType().isDynamicType()) { dynamicColumns = true; } } if (dataColumns) { xmlWriter.writeStartElement(ATTRIBUTES); xmlWriter.writeAttribute(ATTRIBUTES_CLASS, table == attributeModel.getNodeTable() ? "node" : "edge"); xmlWriter.writeAttribute(ATTRIBUTES_MODE, dynamicColumns ? "dynamic" : "static"); for (AttributeColumn col : table.getColumns()) { if (!col.getOrigin().equals(AttributeOrigin.PROPERTY)) { xmlWriter.writeStartElement(ATTRIBUTE); xmlWriter.writeAttribute(ATTRIBUTE_ID, col.getId()); xmlWriter.writeAttribute(ATTRIBUTE_TITLE, col.getTitle()); if (col.getType().equals(AttributeType.INT)) { xmlWriter.writeAttribute(ATTRIBUTE_TYPE, "integer"); } else if (col.getType().isListType()) { if (col.getType().equals(AttributeType.LIST_INTEGER)) { xmlWriter.writeAttribute(ATTRIBUTE_TYPE, "listint"); } else if (col.getType().equals(AttributeType.LIST_CHARACTER)) { xmlWriter.writeAttribute(ATTRIBUTE_TYPE, "listchar"); } else { xmlWriter.writeAttribute(ATTRIBUTE_TYPE, col.getType().getTypeString().toLowerCase().replace("_", "")); } } else if (col.getType().isDynamicType()) { AttributeType staticType = TypeConvertor.getStaticType(col.getType()); if (staticType.equals(AttributeType.INT)) { xmlWriter.writeAttribute(ATTRIBUTE_TYPE, "integer"); } else { xmlWriter.writeAttribute(ATTRIBUTE_TYPE, staticType.getTypeString().toLowerCase()); } } else { xmlWriter.writeAttribute(ATTRIBUTE_TYPE, col.getType().getTypeString().toLowerCase()); } if (col.getDefaultValue() != null) { xmlWriter.writeStartElement(ATTRIBUTE_DEFAULT); xmlWriter.writeCharacters(col.getDefaultValue().toString()); xmlWriter.writeEndElement(); } xmlWriter.writeEndElement(); } } xmlWriter.writeEndElement(); } } private void writeNodes(XMLStreamWriter xmlWriter, HierarchicalGraph graph) throws Exception { if (cancel) { return; } xmlWriter.writeStartElement(NODES); AttributeColumn dynamicCol = dynamicCol = attributeModel.getNodeTable().getColumn(DynamicModel.TIMEINTERVAL_COLUMN); NodeIterable nodeIterable = exportHierarchy ? graph.getNodesTree() : graph.getNodes(); for (Node node : nodeIterable) { xmlWriter.writeStartElement(NODE); String id = node.getNodeData().getId(); xmlWriter.writeAttribute(NODE_ID, id); if (node.getNodeData().getLabel() != null && !node.getNodeData().getLabel().isEmpty() && !node.getNodeData().getLabel().equals(id)) { xmlWriter.writeAttribute(NODE_LABEL, node.getNodeData().getLabel()); } if (exportHierarchy) { Node parent = graph.getParent(node); if (parent != null) { xmlWriter.writeAttribute(NODE_PID, parent.getNodeData().getId()); } } if (exportDynamic && dynamicCol != null && visibleInterval != null) { TimeInterval timeInterval = (TimeInterval) node.getNodeData().getAttributes().getValue(dynamicCol.getIndex()); if (timeInterval != null) { writeTimeInterval(xmlWriter, timeInterval); } } if (exportAttributes && node.getNodeData().getAttributes() != null) { AttributeRow attributeRow = (AttributeRow) node.getNodeData().getAttributes(); writeAttValue(xmlWriter, attributeRow, visibleInterval); } if (exportSize) { writeNodeSize(xmlWriter, node); } if (exportPosition) { writeNodePosition(xmlWriter, node); } if (exportColors) { writeNodeColor(xmlWriter, node); } xmlWriter.writeEndElement(); Progress.progress(progress); if (cancel) { break; } } xmlWriter.writeEndElement(); } private void writeAttValue(XMLStreamWriter xmlWriter, AttributeRow row, TimeInterval visibleInterval) throws Exception { for (AttributeValue val : row.getValues()) { if (!val.getColumn().getOrigin().equals(AttributeOrigin.PROPERTY)) { AttributeType type = val.getColumn().getType(); if (type.isDynamicType()) { DynamicType dynamicValue = (DynamicType) val.getValue(); if (dynamicValue != null && visibleInterval != null) { List<Interval<?>> intervals = dynamicValue.getIntervals(visibleInterval.getLow(), visibleInterval.getHigh()); for (Interval<?> interval : intervals) { Object value = interval.getValue(); if (value != null) { xmlWriter.writeStartElement(ATTVALUE); xmlWriter.writeAttribute(ATTVALUE_FOR, val.getColumn().getId()); xmlWriter.writeAttribute(ATTVALUE_VALUE, value.toString()); if (!Double.isInfinite(interval.getLow())) { String intervalLow = "" + interval.getLow(); xmlWriter.writeAttribute(START, intervalLow); } if (!Double.isInfinite(interval.getHigh())) { String intervalHigh = "" + interval.getHigh(); xmlWriter.writeAttribute(END, intervalHigh); } xmlWriter.writeEndElement(); } } } } else { if (val.getValue() != null) { xmlWriter.writeStartElement(ATTVALUE); xmlWriter.writeAttribute(ATTVALUE_FOR, val.getColumn().getId()); xmlWriter.writeAttribute(ATTVALUE_VALUE, val.getValue().toString()); xmlWriter.writeEndElement(); } } } } } private void writeNodePosition(XMLStreamWriter xmlWriter, Node node) throws Exception { float x = node.getNodeData().x(); if (normalize && x != 0.0) { x = (x - minX) / (maxX - minX); } float y = node.getNodeData().y(); if (normalize && y != 0.0) { y = (y - minY) / (maxY - minY); } float z = node.getNodeData().z(); if (normalize && z != 0.0) { z = (z - minZ) / (maxZ - minZ); } if (!(x == 0 && y == 0 && z == 0)) { xmlWriter.writeStartElement(VIZ, NODE_POSITION, VIZ_NAMESPACE); xmlWriter.writeAttribute("x", "" + x); xmlWriter.writeAttribute("y", "" + y); if (z != 0) { xmlWriter.writeAttribute("z", "" + z); } xmlWriter.writeEndElement(); } } private void writeNodeSize(XMLStreamWriter xmlWriter, Node node) throws Exception { xmlWriter.writeStartElement(VIZ, NODE_SIZE, VIZ_NAMESPACE); float size = node.getNodeData().getSize(); if (normalize) { size = (size - minSize) / (maxSize - minSize); } xmlWriter.writeAttribute("value", "" + size); xmlWriter.writeEndElement(); } private void writeNodeColor(XMLStreamWriter xmlWriter, Node node) throws Exception { int r = Math.round(node.getNodeData().r() * 255f); int g = Math.round(node.getNodeData().g() * 255f); int b = Math.round(node.getNodeData().b() * 255f); if (r != 0 || g != 0 || b != 0) { xmlWriter.writeStartElement(VIZ, NODE_COLOR, VIZ_NAMESPACE); xmlWriter.writeAttribute("r", "" + r); xmlWriter.writeAttribute("g", "" + g); xmlWriter.writeAttribute("b", "" + b); xmlWriter.writeEndElement(); } } private void writeTimeInterval(XMLStreamWriter xmlWriter, TimeInterval timeInterval) throws Exception { List<Interval<Double[]>> intervals = timeInterval.getIntervals(visibleInterval.getLow(), visibleInterval.getHigh()); if (intervals.size() > 1) { xmlWriter.writeStartElement(SLICES); for (Interval<Double[]> interval : intervals) { xmlWriter.writeStartElement(SLICE); if (!Double.isInfinite(interval.getLow())) { String intervalLow = "" + interval.getLow(); xmlWriter.writeAttribute(START, intervalLow); } if (!Double.isInfinite(interval.getHigh())) { String intervalHigh = "" + interval.getHigh(); xmlWriter.writeAttribute(END, intervalHigh); } xmlWriter.writeEndElement(); } xmlWriter.writeEndElement(); } else if (intervals.size() == 1) { Interval<Double[]> interval = intervals.get(0); if (!Double.isInfinite(interval.getLow())) { String intervalLow = "" + interval.getLow(); xmlWriter.writeAttribute(START, intervalLow); } if (!Double.isInfinite(interval.getHigh())) { String intervalHigh = "" + interval.getHigh(); xmlWriter.writeAttribute(END, intervalHigh); } } } private void writeEdges(XMLStreamWriter xmlWriter, HierarchicalGraph graph) throws Exception { if (cancel) { return; } xmlWriter.writeStartElement(EDGES); AttributeColumn dynamicCol = dynamicCol = attributeModel.getEdgeTable().getColumn(DynamicModel.TIMEINTERVAL_COLUMN); EdgeIterable edgeIterable = exportHierarchy ? graph.getEdgesTree() : graph.getEdgesAndMetaEdges(); for (Edge edge : edgeIterable) { xmlWriter.writeStartElement(EDGE); if (edge.getEdgeData().getId() != null && !edge.getEdgeData().getId().equals(Integer.toString(edge.getId()))) { xmlWriter.writeAttribute(EDGE_ID, edge.getEdgeData().getId()); } xmlWriter.writeAttribute(EDGE_SOURCE, edge.getSource().getNodeData().getId()); xmlWriter.writeAttribute(EDGE_TARGET, edge.getTarget().getNodeData().getId()); if (edge.isDirected() && graphModel.isMixed()) { xmlWriter.writeAttribute(EDGE_TYPE, "directed"); } else if (!edge.isDirected() && graphModel.isMixed()) { xmlWriter.writeAttribute(EDGE_TYPE, "undirected"); } String label = edge.getEdgeData().getLabel(); if (label != null && !label.isEmpty() && !label.equals(edge.getEdgeData().getId())) { xmlWriter.writeAttribute(EDGE_LABEL, label); } float weight = edge.getWeight(); if (weight != 1f) { xmlWriter.writeAttribute(EDGE_WEIGHT, "" + weight); } if (exportDynamic && dynamicCol != null && visibleInterval != null) { TimeInterval timeInterval = (TimeInterval) edge.getEdgeData().getAttributes().getValue(dynamicCol.getIndex()); if (timeInterval != null) { writeTimeInterval(xmlWriter, timeInterval); } } writeEdgeColor(xmlWriter, edge); if (exportAttributes && edge.getEdgeData().getAttributes() != null) { AttributeRow attributeRow = (AttributeRow) edge.getEdgeData().getAttributes(); writeAttValue(xmlWriter, attributeRow, visibleInterval); } xmlWriter.writeEndElement(); Progress.progress(progress); if (cancel) { break; } } xmlWriter.writeEndElement(); } private void writeEdgeColor(XMLStreamWriter xmlWriter, Edge edge) throws Exception { if (edge.getEdgeData().r() != -1) { //Edge has custom color int r = Math.round(edge.getEdgeData().r() * 255f); int g = Math.round(edge.getEdgeData().g() * 255f); int b = Math.round(edge.getEdgeData().b() * 255f); if (r != 0 || g != 0 || b != 0) { xmlWriter.writeStartElement(VIZ, EDGE_COLOR, VIZ_NAMESPACE); xmlWriter.writeAttribute("r", "" + r); xmlWriter.writeAttribute("g", "" + g); xmlWriter.writeAttribute("b", "" + b); if (edge.getEdgeData().alpha() != 1f) { xmlWriter.writeAttribute("a", "" + b); } xmlWriter.writeEndElement(); } } } private void calculateMinMax(Graph graph) { minX = Float.POSITIVE_INFINITY; maxX = Float.NEGATIVE_INFINITY; minY = Float.POSITIVE_INFINITY; maxY = Float.NEGATIVE_INFINITY; minZ = Float.POSITIVE_INFINITY; maxZ = Float.NEGATIVE_INFINITY; minSize = Float.POSITIVE_INFINITY; maxSize = Float.NEGATIVE_INFINITY; for (Node node : graph.getNodes()) { NodeData nodeData = node.getNodeData(); minX = Math.min(minX, nodeData.x()); maxX = Math.max(maxX, nodeData.x()); minY = Math.min(minY, nodeData.y()); maxY = Math.max(maxY, nodeData.y()); minZ = Math.min(minZ, nodeData.z()); maxZ = Math.max(maxZ, nodeData.z()); minSize = Math.min(minSize, nodeData.getSize()); maxSize = Math.max(maxSize, nodeData.getSize()); } } public boolean cancel() { cancel = true; return true; } public void setProgressTicket(ProgressTicket progressTicket) { this.progress = progressTicket; } public String getName() { return NbBundle.getMessage(getClass(), "ExporterGEXF_name"); } public FileType[] getFileTypes() { FileType ft = new FileType(".gexf", NbBundle.getMessage(getClass(), "fileType_GEXF_Name")); return new FileType[]{ft}; } private String getDateTime() { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date date = new Date(); return dateFormat.format(date); } public void setExportAttributes(boolean exportAttributes) { this.exportAttributes = exportAttributes; } public void setExportColors(boolean exportColors) { this.exportColors = exportColors; } public void setExportPosition(boolean exportPosition) { this.exportPosition = exportPosition; } public void setExportSize(boolean exportSize) { this.exportSize = exportSize; } public void setNormalize(boolean normalize) { this.normalize = normalize; } public void setExportDynamic(boolean exportDynamic) { this.exportDynamic = exportDynamic; } public void setExportHierarchy(boolean exportHierarchy) { this.exportHierarchy = exportHierarchy; } public boolean isExportAttributes() { return exportAttributes; } public boolean isExportColors() { return exportColors; } public boolean isExportPosition() { return exportPosition; } public boolean isExportSize() { return exportSize; } public boolean isNormalize() { return normalize; } public boolean isExportVisible() { return exportVisible; } public boolean isExportDynamic() { return exportDynamic; } public boolean isExportHierarchy() { return exportHierarchy; } public void setExportVisible(boolean exportVisible) { this.exportVisible = exportVisible; } public void setWriter(Writer writer) { this.writer = writer; } public Workspace getWorkspace() { return workspace; } public void setWorkspace(Workspace workspace) { this.workspace = workspace; } }
true
true
public boolean execute() { attributeModel = workspace.getLookup().lookup(AttributeModel.class); graphModel = workspace.getLookup().lookup(GraphModel.class); HierarchicalGraph graph = null; if (exportVisible) { graph = graphModel.getHierarchicalGraphVisible(); } else { graph = graphModel.getHierarchicalGraph(); } Progress.start(progress); graph.readLock(); //Options if (normalize) { calculateMinMax(graph); } //Calculate progress units count int max = 0; if (exportHierarchy) { for (Node n : graph.getNodesTree()) { max++; } for (Edge e : graph.getEdgesTree()) { max++; } } else { max = graph.getNodeCount(); for (Edge e : graph.getEdgesAndMetaEdges()) { max++; } } Progress.switchToDeterminate(progress, max); try { XMLOutputFactory outputFactory = XMLOutputFactory.newInstance(); outputFactory.setProperty("javax.xml.stream.isRepairingNamespaces", Boolean.FALSE); XMLStreamWriter xmlWriter = outputFactory.createXMLStreamWriter(writer); xmlWriter = new IndentingXMLStreamWriter(xmlWriter); xmlWriter.writeStartDocument("UTF-8", "1.0"); xmlWriter.setPrefix("", GEXF_NAMESPACE); xmlWriter.writeStartElement(GEXF_NAMESPACE, GEXF); xmlWriter.writeNamespace("", GEXF_NAMESPACE); xmlWriter.writeAttribute(GEXF_VERSION, "1.1"); if (exportColors || exportPosition || exportSize) { xmlWriter.writeNamespace(VIZ, VIZ_NAMESPACE); } xmlWriter.writeAttribute("xsi:schemaLocation", GEXF_NAMESPACE_LOCATION); if (exportDynamic) { DynamicController dynamicController = Lookup.getDefault().lookup(DynamicController.class); DynamicModel dynamicModel = dynamicController != null ? dynamicController.getModel(workspace) : null; visibleInterval = dynamicModel == null ? null : exportVisible ? dynamicModel.getVisibleInterval() : new TimeInterval(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY); } writeMeta(xmlWriter); writeGraph(xmlWriter, graph); xmlWriter.writeEndElement(); xmlWriter.writeEndDocument(); xmlWriter.close(); } catch (Exception e) { if (e instanceof RuntimeException) { throw (RuntimeException) e; } throw new RuntimeException(e); } Progress.finish(progress); return !cancel; }
public boolean execute() { attributeModel = workspace.getLookup().lookup(AttributeModel.class); graphModel = workspace.getLookup().lookup(GraphModel.class); HierarchicalGraph graph = null; if (exportVisible) { graph = graphModel.getHierarchicalGraphVisible(); } else { graph = graphModel.getHierarchicalGraph(); } Progress.start(progress); graph.readLock(); //Options if (normalize) { calculateMinMax(graph); } //Calculate progress units count int max = 0; if (exportHierarchy) { for (Node n : graph.getNodesTree()) { max++; } for (Edge e : graph.getEdgesTree()) { max++; } } else { max = graph.getNodeCount(); for (Edge e : graph.getEdgesAndMetaEdges()) { max++; } } Progress.switchToDeterminate(progress, max); try { XMLOutputFactory outputFactory = XMLOutputFactory.newInstance(); outputFactory.setProperty("javax.xml.stream.isRepairingNamespaces", Boolean.FALSE); XMLStreamWriter xmlWriter = outputFactory.createXMLStreamWriter(writer); xmlWriter = new IndentingXMLStreamWriter(xmlWriter); xmlWriter.writeStartDocument("UTF-8", "1.0"); xmlWriter.setPrefix("", GEXF_NAMESPACE); xmlWriter.writeStartElement(GEXF_NAMESPACE, GEXF); xmlWriter.writeNamespace("", GEXF_NAMESPACE); xmlWriter.writeAttribute(GEXF_VERSION, "1.1"); if (exportColors || exportPosition || exportSize) { xmlWriter.writeNamespace(VIZ, VIZ_NAMESPACE); } xmlWriter.writeAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); xmlWriter.writeAttribute("xsi:schemaLocation", GEXF_NAMESPACE_LOCATION); if (exportDynamic) { DynamicController dynamicController = Lookup.getDefault().lookup(DynamicController.class); DynamicModel dynamicModel = dynamicController != null ? dynamicController.getModel(workspace) : null; visibleInterval = dynamicModel == null ? null : exportVisible ? dynamicModel.getVisibleInterval() : new TimeInterval(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY); } writeMeta(xmlWriter); writeGraph(xmlWriter, graph); xmlWriter.writeEndElement(); xmlWriter.writeEndDocument(); xmlWriter.close(); } catch (Exception e) { if (e instanceof RuntimeException) { throw (RuntimeException) e; } throw new RuntimeException(e); } Progress.finish(progress); return !cancel; }
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/dashboard/ListDashboards.java b/gerrit-server/src/main/java/com/google/gerrit/server/dashboard/ListDashboards.java index b2f6593f3..d74f0287e 100644 --- a/gerrit-server/src/main/java/com/google/gerrit/server/dashboard/ListDashboards.java +++ b/gerrit-server/src/main/java/com/google/gerrit/server/dashboard/ListDashboards.java @@ -1,328 +1,328 @@ // Copyright (C) 2012 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.server.dashboard; import com.google.common.collect.Maps; import com.google.gerrit.reviewdb.client.Project; import com.google.gerrit.server.CurrentUser; import com.google.gerrit.server.OutputFormat; import com.google.gerrit.server.git.GitRepositoryManager; import com.google.gerrit.server.project.ProjectCache; import com.google.gerrit.server.project.ProjectControl; import com.google.gerrit.server.project.ProjectState; import com.google.gson.reflect.TypeToken; import com.google.inject.Inject; import org.eclipse.jgit.errors.ConfigInvalidException; import org.eclipse.jgit.lib.Config; import org.eclipse.jgit.lib.ObjectLoader; import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevTree; import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.jgit.treewalk.TreeWalk; import org.eclipse.jgit.treewalk.filter.PathFilter; import org.kohsuke.args4j.Option; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; /** List projects visible to the calling user. */ public class ListDashboards { private static final Logger log = LoggerFactory.getLogger(ListDashboards.class); private static String REFS_DASHBOARDS = "refs/meta/dashboards/"; public static enum Level { PROJECT }; private final CurrentUser currentUser; private final ProjectCache projectCache; private final GitRepositoryManager repoManager; @Option(name = "--format", metaVar = "FMT", usage = "Output display format") private OutputFormat format = OutputFormat.JSON; @Option(name = "--default", usage = "only the projects default dashboard is returned") private boolean defaultDashboard; private Level level; private String entityName; @Inject protected ListDashboards(CurrentUser currentUser, ProjectCache projectCache, GitRepositoryManager repoManager) { this.currentUser = currentUser; this.projectCache = projectCache; this.repoManager = repoManager; } public OutputFormat getFormat() { return format; } public ListDashboards setFormat(OutputFormat fmt) { if (!format.isJson()) { throw new IllegalArgumentException(format.name() + " not supported"); } this.format = fmt; return this; } public ListDashboards setLevel(Level level) { this.level = level; return this; } public ListDashboards setEntityName(String entityName) { this.entityName = entityName; return this; } public void display(OutputStream out) { final PrintWriter stdout; try { stdout = new PrintWriter(new BufferedWriter(new OutputStreamWriter(out, "UTF-8"))); } catch (UnsupportedEncodingException e) { // Our encoding is required by the specifications for the runtime. throw new RuntimeException("JVM lacks UTF-8 encoding", e); } try { final Map<String, DashboardInfo> dashboards; if (level != null) { switch (level) { case PROJECT: final Project.NameKey projectName = new Project.NameKey(entityName); if (defaultDashboard) { dashboards = Maps.newTreeMap(); final DashboardInfo info = loadProjectDefaultDashboard(projectName); dashboards.put(info.id, info); } else { dashboards = projectDashboards(projectName); } break; default: throw new IllegalStateException("unsupported dashboard level: " + level); } } else { dashboards = Maps.newTreeMap(); } format.newGson().toJson(dashboards, new TypeToken<Map<String, DashboardInfo>>() {}.getType(), stdout); stdout.print('\n'); } finally { stdout.flush(); } } private Map<String, DashboardInfo> projectDashboards(final Project.NameKey projectName) { final Map<String, DashboardInfo> dashboards = Maps.newTreeMap(); final ProjectState projectState = projectCache.get(projectName); final ProjectControl projectControl = projectState.controlFor(currentUser); if (projectState == null || !projectControl.isVisible()) { return dashboards; } Repository repo = null; RevWalk revWalk = null; try { repo = repoManager.openRepository(projectName); revWalk = new RevWalk(repo); final Map<String, Ref> refs = repo.getRefDatabase().getRefs(REFS_DASHBOARDS); for (final Ref ref : refs.values()) { if (projectControl.controlForRef(ref.getName()).canRead()) { dashboards.putAll(loadDashboards(projectControl.getProject(), repo, revWalk, ref)); } } } catch (IOException e) { log.warn("Failed to load dashboards of project " + projectName.get(), e); } finally { if (revWalk != null) { revWalk.release(); } if (repo != null) { repo.close(); } } return dashboards; } private Map<String, DashboardInfo> loadDashboards( final Project project, final Repository repo, final RevWalk revWalk, final Ref ref) throws IOException { final Map<String, DashboardInfo> dashboards = Maps.newTreeMap(); TreeWalk treeWalk = new TreeWalk(repo); try { final RevCommit commit = revWalk.parseCommit(ref.getObjectId()); final RevTree tree = commit.getTree(); treeWalk.addTree(tree); treeWalk.setRecursive(true); while (treeWalk.next()) { final ObjectLoader loader = repo.open(treeWalk.getObjectId(0)); final DashboardInfo info = loadDashboard(project, ref.getName(), treeWalk.getPathString(), loader); dashboards.put(info.id, info); } } catch (ConfigInvalidException e) { log.warn("Failed to load dashboards of project " + project.getName() + " from ref " + ref.getName(), e); } catch (IOException e) { log.warn("Failed to load dashboards of project " + project.getName() + " from ref " + ref.getName(), e); } finally { treeWalk.release(); } return dashboards; } private DashboardInfo loadProjectDefaultDashboard(final Project.NameKey projectName) { final ProjectState projectState = projectCache.get(projectName); final ProjectControl projectControl = projectState.controlFor(currentUser); if (projectState == null || !projectControl.isVisible()) { return null; } final Project project = projectControl.getProject(); final String defaultDashboardId = project.getLocalDefaultDashboard() != null ? project .getLocalDefaultDashboard() : project.getDefaultDashboard(); return loadDashboard(projectControl, defaultDashboardId); } private DashboardInfo loadDashboard(final ProjectControl projectControl, final String dashboardId) { - StringTokenizer t = new StringTokenizer(dashboardId); + StringTokenizer t = new StringTokenizer(dashboardId, ":"); if (t.countTokens() != 2) { throw new IllegalStateException("failed to load dashboard, invalid dashboard id: " + dashboardId); } final String refName = t.nextToken(); final String path = t.nextToken(); Repository repo = null; RevWalk revWalk = null; TreeWalk treeWalk = null; try { repo = repoManager.openRepository(projectControl.getProject().getNameKey()); final Ref ref = repo.getRef(refName); if (ref == null) { return null; } if (!projectControl.controlForRef(ref.getName()).canRead()) { return null; } revWalk = new RevWalk(repo); final RevCommit commit = revWalk.parseCommit(ref.getObjectId()); treeWalk = new TreeWalk(repo); treeWalk.addTree(commit.getTree()); treeWalk.setRecursive(true); treeWalk.setFilter(PathFilter.create(path)); if (!treeWalk.next()) { return null; } final ObjectLoader loader = repo.open(treeWalk.getObjectId(0)); return loadDashboard(projectControl.getProject(), refName, path, loader); } catch (IOException e) { log.warn("Failed to load default dashboard", e); } catch (ConfigInvalidException e) { log.warn("Failed to load dashboards of project " + projectControl.getProject().getName() + " from ref " + refName, e); } finally { if (treeWalk != null) { treeWalk.release(); } if (revWalk != null) { revWalk.release(); } if (repo != null) { repo.close(); } } return null; } private DashboardInfo loadDashboard(final Project project, final String refName, final String path, final ObjectLoader loader) throws IOException, ConfigInvalidException { DashboardInfo info = new DashboardInfo(); info.dashboardName = path; info.refName = refName; info.projectName = project.getName(); info.id = createId(info.refName, info.dashboardName); final String defaultDashboardId = project.getLocalDefaultDashboard() != null ? project .getLocalDefaultDashboard() : project.getDefaultDashboard(); info.isDefault = info.id.equals(defaultDashboardId); ByteArrayOutputStream out = new ByteArrayOutputStream(); loader.copyTo(out); Config dashboardConfig = new Config(); dashboardConfig.fromText(new String(out.toByteArray(), "UTF-8")); info.description = dashboardConfig.getString("main", null, "description"); final StringBuilder query = new StringBuilder(); query.append("title="); query.append(info.dashboardName.replaceAll(" ", "+")); final Set<String> sections = dashboardConfig.getSubsections("section"); for (final String section : sections) { query.append("&"); query.append(section.replaceAll(" ", "+")); query.append("="); query.append(dashboardConfig.getString("section", section, "query")); } info.parameters = query.toString(); return info; } private static String createId(final String refName, final String dashboardName) { return refName + ":" + dashboardName; } @SuppressWarnings("unused") private static class DashboardInfo { final String kind = "gerritcodereview#dashboard"; String id; String dashboardName; String refName; String projectName; String description; String parameters; boolean isDefault; } }
true
true
private DashboardInfo loadDashboard(final ProjectControl projectControl, final String dashboardId) { StringTokenizer t = new StringTokenizer(dashboardId); if (t.countTokens() != 2) { throw new IllegalStateException("failed to load dashboard, invalid dashboard id: " + dashboardId); } final String refName = t.nextToken(); final String path = t.nextToken(); Repository repo = null; RevWalk revWalk = null; TreeWalk treeWalk = null; try { repo = repoManager.openRepository(projectControl.getProject().getNameKey()); final Ref ref = repo.getRef(refName); if (ref == null) { return null; } if (!projectControl.controlForRef(ref.getName()).canRead()) { return null; } revWalk = new RevWalk(repo); final RevCommit commit = revWalk.parseCommit(ref.getObjectId()); treeWalk = new TreeWalk(repo); treeWalk.addTree(commit.getTree()); treeWalk.setRecursive(true); treeWalk.setFilter(PathFilter.create(path)); if (!treeWalk.next()) { return null; } final ObjectLoader loader = repo.open(treeWalk.getObjectId(0)); return loadDashboard(projectControl.getProject(), refName, path, loader); } catch (IOException e) { log.warn("Failed to load default dashboard", e); } catch (ConfigInvalidException e) { log.warn("Failed to load dashboards of project " + projectControl.getProject().getName() + " from ref " + refName, e); } finally { if (treeWalk != null) { treeWalk.release(); } if (revWalk != null) { revWalk.release(); } if (repo != null) { repo.close(); } } return null; }
private DashboardInfo loadDashboard(final ProjectControl projectControl, final String dashboardId) { StringTokenizer t = new StringTokenizer(dashboardId, ":"); if (t.countTokens() != 2) { throw new IllegalStateException("failed to load dashboard, invalid dashboard id: " + dashboardId); } final String refName = t.nextToken(); final String path = t.nextToken(); Repository repo = null; RevWalk revWalk = null; TreeWalk treeWalk = null; try { repo = repoManager.openRepository(projectControl.getProject().getNameKey()); final Ref ref = repo.getRef(refName); if (ref == null) { return null; } if (!projectControl.controlForRef(ref.getName()).canRead()) { return null; } revWalk = new RevWalk(repo); final RevCommit commit = revWalk.parseCommit(ref.getObjectId()); treeWalk = new TreeWalk(repo); treeWalk.addTree(commit.getTree()); treeWalk.setRecursive(true); treeWalk.setFilter(PathFilter.create(path)); if (!treeWalk.next()) { return null; } final ObjectLoader loader = repo.open(treeWalk.getObjectId(0)); return loadDashboard(projectControl.getProject(), refName, path, loader); } catch (IOException e) { log.warn("Failed to load default dashboard", e); } catch (ConfigInvalidException e) { log.warn("Failed to load dashboards of project " + projectControl.getProject().getName() + " from ref " + refName, e); } finally { if (treeWalk != null) { treeWalk.release(); } if (revWalk != null) { revWalk.release(); } if (repo != null) { repo.close(); } } return null; }
diff --git a/src/driver/GUIDriver.java b/src/driver/GUIDriver.java index fe4ec6b..f746e6f 100644 --- a/src/driver/GUIDriver.java +++ b/src/driver/GUIDriver.java @@ -1,390 +1,390 @@ package driver; import java.awt.Canvas; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.Point; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.image.BufferStrategy; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.ConcurrentModificationException; import java.util.HashMap; import java.util.Random; import javax.swing.JFrame; import world.Character; import world.Enemy; import world.Grid; import world.GridSpace; import world.LivingThing; import world.Magic; import world.RangedWeapon; import world.Terrain; import world.Thing; import world.World; public class GUIDriver { private static Grid g; private static long gravityRate; private static int lastKey; private static long hangTime; private static long value; private static int stage = 1; private static boolean keepGoing; public static void main(String[] args) { // Create game window... JFrame app = new JFrame(); app.setIgnoreRepaint(true); app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Create canvas for painting... Canvas canvas = new Canvas(); canvas.setIgnoreRepaint(true); canvas.setSize(1200, 480); // Add canvas to game window... app.add(canvas); app.pack(); app.setVisible(true); // Create BackBuffer... canvas.createBufferStrategy(2); BufferStrategy buffer = canvas.getBufferStrategy(); // Get graphics configuration... GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice gd = ge.getDefaultScreenDevice(); GraphicsConfiguration gc = gd.getDefaultConfiguration(); // Create off-screen drawing surface BufferedImage bi = gc.createCompatibleImage(1200, 480); // Objects needed for rendering... Graphics graphics = null; Graphics2D g2d = null; Color background = Color.BLACK; // Variables for counting frames per seconds int fps = 0; int frames = 0; long totalTime = 0; long gravityTime = 0; long enemyDamageTime = 0; hangTime = 500; gravityRate = 300; value = gravityRate + hangTime; long curTime = System.currentTimeMillis(); long lastTime = curTime; keepGoing = true; g = new Grid(0); g.makeDefaultGrid(); Character casdfasdfasd = g.getGrid().get(g.getCharacterLocation()).returnCharacter(); System.out.println(casdfasdfasd.getRangedStore()); System.out.println(casdfasdfasd.getCloseStore()); stage = 1; app.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { int keyCode = e.getKeyCode(); if (keyCode == KeyEvent.VK_UP) { g.retractWeapon(KeyEvent.VK_A); g.retractWeapon(KeyEvent.VK_D); if (g.getGrid() .get(new Point((int) g.getCharacterLocation().getX(), (int) g.getCharacterLocation().getY() + 1)).hasSolid()) { g.moveCharacter(0, -1, lastKey); g.moveCharacter(0, -1, lastKey); g.moveCharacter(0, -1, lastKey); g.moveCharacter(0, -1, lastKey); value = gravityRate + hangTime; } } else if (keyCode == KeyEvent.VK_LEFT) { g.moveCharacter(-1, 0, lastKey); lastKey = KeyEvent.VK_LEFT; } else if (keyCode == KeyEvent.VK_DOWN) { g.moveCharacter(0, 1, lastKey); } else if (keyCode == KeyEvent.VK_RIGHT) { g.moveCharacter(1, 0, lastKey); lastKey = KeyEvent.VK_RIGHT; } else if (keyCode == KeyEvent.VK_A) { lastKey = KeyEvent.VK_A; g.useWeapon(lastKey); } else if (keyCode == KeyEvent.VK_D) { lastKey = KeyEvent.VK_D; g.useWeapon(lastKey); } else if (keyCode == KeyEvent.VK_P) { String name = "Yo Mama"; Color c = Color.ORANGE; Point p = g.findValidEnemyLocation(); if (p != null) { g.spawnNewEnemy(p, new Enemy(true, c, name, 10, 10, 10)); } else { System.out.println("Could not spawn a new enemy."); } } else if (keyCode == KeyEvent.VK_Q || keyCode == KeyEvent.VK_E) { g.retractWeapon(KeyEvent.VK_A); g.retractWeapon(KeyEvent.VK_D); Character c = g.getGrid().get(g.getCharacterLocation()).returnCharacter(); System.out.println(c.getMagicStore()); System.out.println(c.getRangedStore()); System.out.println(c.getCloseStore()); if (c.getWeapon() instanceof RangedWeapon && !(c.getWeapon() instanceof Magic)) { c.setWeapon((Magic) c.getMagicStore().get(0)); } else if (c.getWeapon() instanceof Magic) { c.setWeapon(c.getCloseStore().get(0)); } else { c.setWeapon((RangedWeapon) c.getRangedStore().get(0)); } } else if (keyCode == KeyEvent.VK_SLASH) { g.killAllEnemies(); } else if (keyCode == KeyEvent.VK_SEMICOLON) { g.placeTerrain(keyCode); } else if (keyCode == KeyEvent.VK_PERIOD) { g.placeTerrain(keyCode); } } public void keyReleased(KeyEvent e) { int keyCode = e.getKeyCode(); if (keyCode == KeyEvent.VK_A || keyCode == KeyEvent.VK_D) { g.retractWeapon(KeyEvent.VK_A); g.retractWeapon(KeyEvent.VK_D); } } }); while (keepGoing) { try { lastTime = curTime; curTime = System.currentTimeMillis(); totalTime += curTime - lastTime; gravityTime += curTime - lastTime; enemyDamageTime += curTime - lastTime; if (keepGoing) { if (gravityTime > value) { value += gravityRate; g.moveCharacter(0, 1, lastKey); g.applyDot(); for (int a = 0; a < 2; a++) { g.moveRangedWeapon(); } Point charLoc = g.getCharacterLocation(); ArrayList<Point> enemyLocs = g.getEnemyLocation(); for (int j = 0; j < enemyLocs.size(); j++) { if (charLoc.distance(enemyLocs.get(j)) <= 1) { keepGoing = g.characterDamage(g.getGrid().get(enemyLocs.get(j)).returnEnemy()); if (!keepGoing) { g.gameOver(); } } } if (keepGoing) { // check every instance of p for (int i = 0; i < g.getEnemyLocation().size(); i++) { Point p = g.getEnemyLocation().get(i); Point q = new Point((int) p.getX(), (int) p.getY() + 1); GridSpace gs = g.getGrid().get(q); if (p.getX() - g.getCharacterLocation().getX() > 0) { g.moveEnemy(-1, 0, p); } else { g.moveEnemy(1, 0, p); } if (g.getCharacterLocation().getX() > g.getEnemyLocation().get(i).getX()) { Point check = new Point((int) (p.getX() + 1), (int) (p.getY())); GridSpace more = g.getGrid().get(check); if (more.hasSolid()) { for (Terrain t : more.returnTerrain()) { if (t.getSolid()) { g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); } } for (LivingThing e : more.returnLivingThings()) { if (e.getSolid() && !(e instanceof Character)) { g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); } } } } else if (g.getCharacterLocation().getX() < g.getEnemyLocation().get(i).getX()) { Point check = new Point((int) (p.getX() - 1), (int) (p.getY())); GridSpace more = g.getGrid().get(check); if (more.hasSolid()) { for (Terrain t : more.returnTerrain()) { if (t.getSolid()) { g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); } } for (LivingThing e : more.returnLivingThings()) { if (e.getSolid() && !(e instanceof Character)) { g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); } } } } g.moveEnemy(0, 1, p); } if (gravityTime > 4 * gravityRate + hangTime) { gravityTime = 0; value = gravityRate + hangTime; } if (enemyDamageTime > 500) { } // clear back buffer... if (g.getCharacterLocation().getX() >= 100) { HashMap<Point, GridSpace> grid = g.getGrid(); Point oldLocation = g.getCharacterLocation(); Character c = grid.get(oldLocation).returnCharacter(); c.setHp(c.getMaxHp()); World w = new World(); int killed = g.getNumKilled(); g = w.drawWorld(1, killed); stage++; grid = g.getGrid(); g.setNumKilled(killed); ArrayList<Thing> t = new ArrayList<Thing>(); t.add(c); GridSpace gs = new GridSpace(t); gs.sortArrayOfThings(); - grid.put(new Point(0, (int) oldLocation.getY()), gs); - g.setCharacterLocation(new Point(0, (int) oldLocation.getY() - 1)); + grid.put(new Point(1, (int) oldLocation.getY()-1), gs); + g.setCharacterLocation(new Point(1, (int) oldLocation.getY() - 1)); Random r = new Random(); int numEnemies = r.nextInt(20) + 1; for (int i = 0; i < numEnemies; i++) { String name = "Yo Mama"; Color d = Color.ORANGE; Point p = g.findValidEnemyLocation(); if (p != null) { g.spawnNewEnemy(p, new Enemy(true, d, name, 10, 10, 10)); } } } } } } if (totalTime > 1000) { totalTime -= 1000; fps = frames; frames = 0; } ++frames; g2d = bi.createGraphics(); g2d.setColor(background); g2d.fillRect(0, 0, 639, 479); HashMap<Point, GridSpace> grid = g.getGrid(); for (int i = 0; i < 100; i++) { for (int j = 0; j < 25; j++) { g2d.setColor(grid.get(new Point(i, j)).getColor()); g2d.fillRect(i * 10, j * 10, 10, 10); } } // display frames per second... g2d.setFont(new Font("Courier New", Font.PLAIN, 12)); g2d.setColor(Color.GREEN); g2d.drawString(String.format("FPS: %s", fps), 20, 20); g2d.drawString(String.format("Stage: %s", stage), 100, 20); g2d.drawString(String.format("Enemies killed: %s", g.getNumKilled()), 180, 20); if (keepGoing) { try { g2d.drawString("Current weapon: " + g.getGrid().get(g.getCharacterLocation()).returnCharacter().getWeapon().toString(), 570, 20); } catch (NullPointerException e) { System.out.println("Caught null pointer error on HUD for weapon."); } catch (ConcurrentModificationException c) { System.out.println("Caught concurrent modification exception."); } try { Character c = g.getGrid().get(g.getCharacterLocation()).returnCharacter(); g2d.drawString("Current level: " + c.getLevel(), 840, 20); String healthString = ""; for (int i = 0; i < c.getMaxHp(); i += 5) { if (c.getHp() > i) { healthString += "* "; } else { healthString += "_ "; } } g2d.drawString("Health: " + healthString, 320, 20); } catch (NullPointerException e) { System.out.println("Caught that error"); g2d.drawString("Health: Dead", 320, 20); } } // Blit image and flip... graphics = buffer.getDrawGraphics(); graphics.drawImage(bi, 0, 0, null); if (!buffer.contentsLost()) { buffer.show(); } // Let the OS have a little time... Thread.yield(); } finally { // release resources if (graphics != null) graphics.dispose(); if (g2d != null) g2d.dispose(); } } } }
true
true
public static void main(String[] args) { // Create game window... JFrame app = new JFrame(); app.setIgnoreRepaint(true); app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Create canvas for painting... Canvas canvas = new Canvas(); canvas.setIgnoreRepaint(true); canvas.setSize(1200, 480); // Add canvas to game window... app.add(canvas); app.pack(); app.setVisible(true); // Create BackBuffer... canvas.createBufferStrategy(2); BufferStrategy buffer = canvas.getBufferStrategy(); // Get graphics configuration... GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice gd = ge.getDefaultScreenDevice(); GraphicsConfiguration gc = gd.getDefaultConfiguration(); // Create off-screen drawing surface BufferedImage bi = gc.createCompatibleImage(1200, 480); // Objects needed for rendering... Graphics graphics = null; Graphics2D g2d = null; Color background = Color.BLACK; // Variables for counting frames per seconds int fps = 0; int frames = 0; long totalTime = 0; long gravityTime = 0; long enemyDamageTime = 0; hangTime = 500; gravityRate = 300; value = gravityRate + hangTime; long curTime = System.currentTimeMillis(); long lastTime = curTime; keepGoing = true; g = new Grid(0); g.makeDefaultGrid(); Character casdfasdfasd = g.getGrid().get(g.getCharacterLocation()).returnCharacter(); System.out.println(casdfasdfasd.getRangedStore()); System.out.println(casdfasdfasd.getCloseStore()); stage = 1; app.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { int keyCode = e.getKeyCode(); if (keyCode == KeyEvent.VK_UP) { g.retractWeapon(KeyEvent.VK_A); g.retractWeapon(KeyEvent.VK_D); if (g.getGrid() .get(new Point((int) g.getCharacterLocation().getX(), (int) g.getCharacterLocation().getY() + 1)).hasSolid()) { g.moveCharacter(0, -1, lastKey); g.moveCharacter(0, -1, lastKey); g.moveCharacter(0, -1, lastKey); g.moveCharacter(0, -1, lastKey); value = gravityRate + hangTime; } } else if (keyCode == KeyEvent.VK_LEFT) { g.moveCharacter(-1, 0, lastKey); lastKey = KeyEvent.VK_LEFT; } else if (keyCode == KeyEvent.VK_DOWN) { g.moveCharacter(0, 1, lastKey); } else if (keyCode == KeyEvent.VK_RIGHT) { g.moveCharacter(1, 0, lastKey); lastKey = KeyEvent.VK_RIGHT; } else if (keyCode == KeyEvent.VK_A) { lastKey = KeyEvent.VK_A; g.useWeapon(lastKey); } else if (keyCode == KeyEvent.VK_D) { lastKey = KeyEvent.VK_D; g.useWeapon(lastKey); } else if (keyCode == KeyEvent.VK_P) { String name = "Yo Mama"; Color c = Color.ORANGE; Point p = g.findValidEnemyLocation(); if (p != null) { g.spawnNewEnemy(p, new Enemy(true, c, name, 10, 10, 10)); } else { System.out.println("Could not spawn a new enemy."); } } else if (keyCode == KeyEvent.VK_Q || keyCode == KeyEvent.VK_E) { g.retractWeapon(KeyEvent.VK_A); g.retractWeapon(KeyEvent.VK_D); Character c = g.getGrid().get(g.getCharacterLocation()).returnCharacter(); System.out.println(c.getMagicStore()); System.out.println(c.getRangedStore()); System.out.println(c.getCloseStore()); if (c.getWeapon() instanceof RangedWeapon && !(c.getWeapon() instanceof Magic)) { c.setWeapon((Magic) c.getMagicStore().get(0)); } else if (c.getWeapon() instanceof Magic) { c.setWeapon(c.getCloseStore().get(0)); } else { c.setWeapon((RangedWeapon) c.getRangedStore().get(0)); } } else if (keyCode == KeyEvent.VK_SLASH) { g.killAllEnemies(); } else if (keyCode == KeyEvent.VK_SEMICOLON) { g.placeTerrain(keyCode); } else if (keyCode == KeyEvent.VK_PERIOD) { g.placeTerrain(keyCode); } } public void keyReleased(KeyEvent e) { int keyCode = e.getKeyCode(); if (keyCode == KeyEvent.VK_A || keyCode == KeyEvent.VK_D) { g.retractWeapon(KeyEvent.VK_A); g.retractWeapon(KeyEvent.VK_D); } } }); while (keepGoing) { try { lastTime = curTime; curTime = System.currentTimeMillis(); totalTime += curTime - lastTime; gravityTime += curTime - lastTime; enemyDamageTime += curTime - lastTime; if (keepGoing) { if (gravityTime > value) { value += gravityRate; g.moveCharacter(0, 1, lastKey); g.applyDot(); for (int a = 0; a < 2; a++) { g.moveRangedWeapon(); } Point charLoc = g.getCharacterLocation(); ArrayList<Point> enemyLocs = g.getEnemyLocation(); for (int j = 0; j < enemyLocs.size(); j++) { if (charLoc.distance(enemyLocs.get(j)) <= 1) { keepGoing = g.characterDamage(g.getGrid().get(enemyLocs.get(j)).returnEnemy()); if (!keepGoing) { g.gameOver(); } } } if (keepGoing) { // check every instance of p for (int i = 0; i < g.getEnemyLocation().size(); i++) { Point p = g.getEnemyLocation().get(i); Point q = new Point((int) p.getX(), (int) p.getY() + 1); GridSpace gs = g.getGrid().get(q); if (p.getX() - g.getCharacterLocation().getX() > 0) { g.moveEnemy(-1, 0, p); } else { g.moveEnemy(1, 0, p); } if (g.getCharacterLocation().getX() > g.getEnemyLocation().get(i).getX()) { Point check = new Point((int) (p.getX() + 1), (int) (p.getY())); GridSpace more = g.getGrid().get(check); if (more.hasSolid()) { for (Terrain t : more.returnTerrain()) { if (t.getSolid()) { g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); } } for (LivingThing e : more.returnLivingThings()) { if (e.getSolid() && !(e instanceof Character)) { g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); } } } } else if (g.getCharacterLocation().getX() < g.getEnemyLocation().get(i).getX()) { Point check = new Point((int) (p.getX() - 1), (int) (p.getY())); GridSpace more = g.getGrid().get(check); if (more.hasSolid()) { for (Terrain t : more.returnTerrain()) { if (t.getSolid()) { g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); } } for (LivingThing e : more.returnLivingThings()) { if (e.getSolid() && !(e instanceof Character)) { g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); } } } } g.moveEnemy(0, 1, p); } if (gravityTime > 4 * gravityRate + hangTime) { gravityTime = 0; value = gravityRate + hangTime; } if (enemyDamageTime > 500) { } // clear back buffer... if (g.getCharacterLocation().getX() >= 100) { HashMap<Point, GridSpace> grid = g.getGrid(); Point oldLocation = g.getCharacterLocation(); Character c = grid.get(oldLocation).returnCharacter(); c.setHp(c.getMaxHp()); World w = new World(); int killed = g.getNumKilled(); g = w.drawWorld(1, killed); stage++; grid = g.getGrid(); g.setNumKilled(killed); ArrayList<Thing> t = new ArrayList<Thing>(); t.add(c); GridSpace gs = new GridSpace(t); gs.sortArrayOfThings(); grid.put(new Point(0, (int) oldLocation.getY()), gs); g.setCharacterLocation(new Point(0, (int) oldLocation.getY() - 1)); Random r = new Random(); int numEnemies = r.nextInt(20) + 1; for (int i = 0; i < numEnemies; i++) { String name = "Yo Mama"; Color d = Color.ORANGE; Point p = g.findValidEnemyLocation(); if (p != null) { g.spawnNewEnemy(p, new Enemy(true, d, name, 10, 10, 10)); } } } } } } if (totalTime > 1000) { totalTime -= 1000; fps = frames; frames = 0; } ++frames; g2d = bi.createGraphics(); g2d.setColor(background); g2d.fillRect(0, 0, 639, 479); HashMap<Point, GridSpace> grid = g.getGrid(); for (int i = 0; i < 100; i++) { for (int j = 0; j < 25; j++) { g2d.setColor(grid.get(new Point(i, j)).getColor()); g2d.fillRect(i * 10, j * 10, 10, 10); } } // display frames per second... g2d.setFont(new Font("Courier New", Font.PLAIN, 12)); g2d.setColor(Color.GREEN); g2d.drawString(String.format("FPS: %s", fps), 20, 20); g2d.drawString(String.format("Stage: %s", stage), 100, 20); g2d.drawString(String.format("Enemies killed: %s", g.getNumKilled()), 180, 20); if (keepGoing) { try { g2d.drawString("Current weapon: " + g.getGrid().get(g.getCharacterLocation()).returnCharacter().getWeapon().toString(), 570, 20); } catch (NullPointerException e) { System.out.println("Caught null pointer error on HUD for weapon."); } catch (ConcurrentModificationException c) { System.out.println("Caught concurrent modification exception."); } try { Character c = g.getGrid().get(g.getCharacterLocation()).returnCharacter(); g2d.drawString("Current level: " + c.getLevel(), 840, 20); String healthString = ""; for (int i = 0; i < c.getMaxHp(); i += 5) { if (c.getHp() > i) { healthString += "* "; } else { healthString += "_ "; } } g2d.drawString("Health: " + healthString, 320, 20); } catch (NullPointerException e) { System.out.println("Caught that error"); g2d.drawString("Health: Dead", 320, 20); } } // Blit image and flip... graphics = buffer.getDrawGraphics(); graphics.drawImage(bi, 0, 0, null); if (!buffer.contentsLost()) { buffer.show(); } // Let the OS have a little time... Thread.yield(); } finally { // release resources if (graphics != null) graphics.dispose(); if (g2d != null) g2d.dispose(); } } }
public static void main(String[] args) { // Create game window... JFrame app = new JFrame(); app.setIgnoreRepaint(true); app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Create canvas for painting... Canvas canvas = new Canvas(); canvas.setIgnoreRepaint(true); canvas.setSize(1200, 480); // Add canvas to game window... app.add(canvas); app.pack(); app.setVisible(true); // Create BackBuffer... canvas.createBufferStrategy(2); BufferStrategy buffer = canvas.getBufferStrategy(); // Get graphics configuration... GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice gd = ge.getDefaultScreenDevice(); GraphicsConfiguration gc = gd.getDefaultConfiguration(); // Create off-screen drawing surface BufferedImage bi = gc.createCompatibleImage(1200, 480); // Objects needed for rendering... Graphics graphics = null; Graphics2D g2d = null; Color background = Color.BLACK; // Variables for counting frames per seconds int fps = 0; int frames = 0; long totalTime = 0; long gravityTime = 0; long enemyDamageTime = 0; hangTime = 500; gravityRate = 300; value = gravityRate + hangTime; long curTime = System.currentTimeMillis(); long lastTime = curTime; keepGoing = true; g = new Grid(0); g.makeDefaultGrid(); Character casdfasdfasd = g.getGrid().get(g.getCharacterLocation()).returnCharacter(); System.out.println(casdfasdfasd.getRangedStore()); System.out.println(casdfasdfasd.getCloseStore()); stage = 1; app.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { int keyCode = e.getKeyCode(); if (keyCode == KeyEvent.VK_UP) { g.retractWeapon(KeyEvent.VK_A); g.retractWeapon(KeyEvent.VK_D); if (g.getGrid() .get(new Point((int) g.getCharacterLocation().getX(), (int) g.getCharacterLocation().getY() + 1)).hasSolid()) { g.moveCharacter(0, -1, lastKey); g.moveCharacter(0, -1, lastKey); g.moveCharacter(0, -1, lastKey); g.moveCharacter(0, -1, lastKey); value = gravityRate + hangTime; } } else if (keyCode == KeyEvent.VK_LEFT) { g.moveCharacter(-1, 0, lastKey); lastKey = KeyEvent.VK_LEFT; } else if (keyCode == KeyEvent.VK_DOWN) { g.moveCharacter(0, 1, lastKey); } else if (keyCode == KeyEvent.VK_RIGHT) { g.moveCharacter(1, 0, lastKey); lastKey = KeyEvent.VK_RIGHT; } else if (keyCode == KeyEvent.VK_A) { lastKey = KeyEvent.VK_A; g.useWeapon(lastKey); } else if (keyCode == KeyEvent.VK_D) { lastKey = KeyEvent.VK_D; g.useWeapon(lastKey); } else if (keyCode == KeyEvent.VK_P) { String name = "Yo Mama"; Color c = Color.ORANGE; Point p = g.findValidEnemyLocation(); if (p != null) { g.spawnNewEnemy(p, new Enemy(true, c, name, 10, 10, 10)); } else { System.out.println("Could not spawn a new enemy."); } } else if (keyCode == KeyEvent.VK_Q || keyCode == KeyEvent.VK_E) { g.retractWeapon(KeyEvent.VK_A); g.retractWeapon(KeyEvent.VK_D); Character c = g.getGrid().get(g.getCharacterLocation()).returnCharacter(); System.out.println(c.getMagicStore()); System.out.println(c.getRangedStore()); System.out.println(c.getCloseStore()); if (c.getWeapon() instanceof RangedWeapon && !(c.getWeapon() instanceof Magic)) { c.setWeapon((Magic) c.getMagicStore().get(0)); } else if (c.getWeapon() instanceof Magic) { c.setWeapon(c.getCloseStore().get(0)); } else { c.setWeapon((RangedWeapon) c.getRangedStore().get(0)); } } else if (keyCode == KeyEvent.VK_SLASH) { g.killAllEnemies(); } else if (keyCode == KeyEvent.VK_SEMICOLON) { g.placeTerrain(keyCode); } else if (keyCode == KeyEvent.VK_PERIOD) { g.placeTerrain(keyCode); } } public void keyReleased(KeyEvent e) { int keyCode = e.getKeyCode(); if (keyCode == KeyEvent.VK_A || keyCode == KeyEvent.VK_D) { g.retractWeapon(KeyEvent.VK_A); g.retractWeapon(KeyEvent.VK_D); } } }); while (keepGoing) { try { lastTime = curTime; curTime = System.currentTimeMillis(); totalTime += curTime - lastTime; gravityTime += curTime - lastTime; enemyDamageTime += curTime - lastTime; if (keepGoing) { if (gravityTime > value) { value += gravityRate; g.moveCharacter(0, 1, lastKey); g.applyDot(); for (int a = 0; a < 2; a++) { g.moveRangedWeapon(); } Point charLoc = g.getCharacterLocation(); ArrayList<Point> enemyLocs = g.getEnemyLocation(); for (int j = 0; j < enemyLocs.size(); j++) { if (charLoc.distance(enemyLocs.get(j)) <= 1) { keepGoing = g.characterDamage(g.getGrid().get(enemyLocs.get(j)).returnEnemy()); if (!keepGoing) { g.gameOver(); } } } if (keepGoing) { // check every instance of p for (int i = 0; i < g.getEnemyLocation().size(); i++) { Point p = g.getEnemyLocation().get(i); Point q = new Point((int) p.getX(), (int) p.getY() + 1); GridSpace gs = g.getGrid().get(q); if (p.getX() - g.getCharacterLocation().getX() > 0) { g.moveEnemy(-1, 0, p); } else { g.moveEnemy(1, 0, p); } if (g.getCharacterLocation().getX() > g.getEnemyLocation().get(i).getX()) { Point check = new Point((int) (p.getX() + 1), (int) (p.getY())); GridSpace more = g.getGrid().get(check); if (more.hasSolid()) { for (Terrain t : more.returnTerrain()) { if (t.getSolid()) { g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); } } for (LivingThing e : more.returnLivingThings()) { if (e.getSolid() && !(e instanceof Character)) { g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); } } } } else if (g.getCharacterLocation().getX() < g.getEnemyLocation().get(i).getX()) { Point check = new Point((int) (p.getX() - 1), (int) (p.getY())); GridSpace more = g.getGrid().get(check); if (more.hasSolid()) { for (Terrain t : more.returnTerrain()) { if (t.getSolid()) { g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); } } for (LivingThing e : more.returnLivingThings()) { if (e.getSolid() && !(e instanceof Character)) { g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); } } } } g.moveEnemy(0, 1, p); } if (gravityTime > 4 * gravityRate + hangTime) { gravityTime = 0; value = gravityRate + hangTime; } if (enemyDamageTime > 500) { } // clear back buffer... if (g.getCharacterLocation().getX() >= 100) { HashMap<Point, GridSpace> grid = g.getGrid(); Point oldLocation = g.getCharacterLocation(); Character c = grid.get(oldLocation).returnCharacter(); c.setHp(c.getMaxHp()); World w = new World(); int killed = g.getNumKilled(); g = w.drawWorld(1, killed); stage++; grid = g.getGrid(); g.setNumKilled(killed); ArrayList<Thing> t = new ArrayList<Thing>(); t.add(c); GridSpace gs = new GridSpace(t); gs.sortArrayOfThings(); grid.put(new Point(1, (int) oldLocation.getY()-1), gs); g.setCharacterLocation(new Point(1, (int) oldLocation.getY() - 1)); Random r = new Random(); int numEnemies = r.nextInt(20) + 1; for (int i = 0; i < numEnemies; i++) { String name = "Yo Mama"; Color d = Color.ORANGE; Point p = g.findValidEnemyLocation(); if (p != null) { g.spawnNewEnemy(p, new Enemy(true, d, name, 10, 10, 10)); } } } } } } if (totalTime > 1000) { totalTime -= 1000; fps = frames; frames = 0; } ++frames; g2d = bi.createGraphics(); g2d.setColor(background); g2d.fillRect(0, 0, 639, 479); HashMap<Point, GridSpace> grid = g.getGrid(); for (int i = 0; i < 100; i++) { for (int j = 0; j < 25; j++) { g2d.setColor(grid.get(new Point(i, j)).getColor()); g2d.fillRect(i * 10, j * 10, 10, 10); } } // display frames per second... g2d.setFont(new Font("Courier New", Font.PLAIN, 12)); g2d.setColor(Color.GREEN); g2d.drawString(String.format("FPS: %s", fps), 20, 20); g2d.drawString(String.format("Stage: %s", stage), 100, 20); g2d.drawString(String.format("Enemies killed: %s", g.getNumKilled()), 180, 20); if (keepGoing) { try { g2d.drawString("Current weapon: " + g.getGrid().get(g.getCharacterLocation()).returnCharacter().getWeapon().toString(), 570, 20); } catch (NullPointerException e) { System.out.println("Caught null pointer error on HUD for weapon."); } catch (ConcurrentModificationException c) { System.out.println("Caught concurrent modification exception."); } try { Character c = g.getGrid().get(g.getCharacterLocation()).returnCharacter(); g2d.drawString("Current level: " + c.getLevel(), 840, 20); String healthString = ""; for (int i = 0; i < c.getMaxHp(); i += 5) { if (c.getHp() > i) { healthString += "* "; } else { healthString += "_ "; } } g2d.drawString("Health: " + healthString, 320, 20); } catch (NullPointerException e) { System.out.println("Caught that error"); g2d.drawString("Health: Dead", 320, 20); } } // Blit image and flip... graphics = buffer.getDrawGraphics(); graphics.drawImage(bi, 0, 0, null); if (!buffer.contentsLost()) { buffer.show(); } // Let the OS have a little time... Thread.yield(); } finally { // release resources if (graphics != null) graphics.dispose(); if (g2d != null) g2d.dispose(); } } }
diff --git a/lucene/core/src/java/org/apache/lucene/search/payloads/PayloadTermQuery.java b/lucene/core/src/java/org/apache/lucene/search/payloads/PayloadTermQuery.java index 4d07328c7..30d5bacfb 100644 --- a/lucene/core/src/java/org/apache/lucene/search/payloads/PayloadTermQuery.java +++ b/lucene/core/src/java/org/apache/lucene/search/payloads/PayloadTermQuery.java @@ -1,244 +1,244 @@ package org.apache.lucene.search.payloads; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.apache.lucene.index.AtomicReaderContext; import org.apache.lucene.index.Term; import org.apache.lucene.index.DocsAndPositionsEnum; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Scorer; import org.apache.lucene.search.Weight; import org.apache.lucene.search.Explanation; import org.apache.lucene.search.ComplexExplanation; import org.apache.lucene.search.similarities.DefaultSimilarity; import org.apache.lucene.search.similarities.Similarity; import org.apache.lucene.search.similarities.Similarity.SloppySimScorer; import org.apache.lucene.search.spans.TermSpans; import org.apache.lucene.search.spans.SpanTermQuery; import org.apache.lucene.search.spans.SpanWeight; import org.apache.lucene.search.spans.SpanScorer; import org.apache.lucene.util.Bits; import org.apache.lucene.util.BytesRef; import java.io.IOException; /** * This class is very similar to * {@link org.apache.lucene.search.spans.SpanTermQuery} except that it factors * in the value of the payload located at each of the positions where the * {@link org.apache.lucene.index.Term} occurs. * <p/> * NOTE: In order to take advantage of this with the default scoring implementation * ({@link DefaultSimilarity}), you must override {@link DefaultSimilarity#scorePayload(int, int, int, BytesRef)}, * which returns 1 by default. * <p/> * Payload scores are aggregated using a pluggable {@link PayloadFunction}. * @see org.apache.lucene.search.similarities.Similarity.SloppySimScorer#computePayloadFactor(int, int, int, BytesRef) **/ public class PayloadTermQuery extends SpanTermQuery { protected PayloadFunction function; private boolean includeSpanScore; public PayloadTermQuery(Term term, PayloadFunction function) { this(term, function, true); } public PayloadTermQuery(Term term, PayloadFunction function, boolean includeSpanScore) { super(term); this.function = function; this.includeSpanScore = includeSpanScore; } @Override public Weight createWeight(IndexSearcher searcher) throws IOException { return new PayloadTermWeight(this, searcher); } protected class PayloadTermWeight extends SpanWeight { public PayloadTermWeight(PayloadTermQuery query, IndexSearcher searcher) throws IOException { super(query, searcher); } @Override public Scorer scorer(AtomicReaderContext context, boolean scoreDocsInOrder, boolean topScorer, Bits acceptDocs) throws IOException { return new PayloadTermSpanScorer((TermSpans) query.getSpans(context, acceptDocs, termContexts), this, similarity.sloppySimScorer(stats, context)); } protected class PayloadTermSpanScorer extends SpanScorer { protected BytesRef payload; protected float payloadScore; protected int payloadsSeen; private final TermSpans termSpans; public PayloadTermSpanScorer(TermSpans spans, Weight weight, Similarity.SloppySimScorer docScorer) throws IOException { super(spans, weight, docScorer); termSpans = spans; } @Override protected boolean setFreqCurrentDoc() throws IOException { if (!more) { return false; } doc = spans.doc(); freq = 0.0f; payloadScore = 0; payloadsSeen = 0; while (more && doc == spans.doc()) { int matchLength = spans.end() - spans.start(); freq += docScorer.computeSlopFactor(matchLength); processPayload(similarity); more = spans.next();// this moves positions to the next match in this // document } return more || (freq != 0); } protected void processPayload(Similarity similarity) throws IOException { final DocsAndPositionsEnum postings = termSpans.getPostings(); if (postings.hasPayload()) { payload = postings.getPayload(); if (payload != null) { payloadScore = function.currentScore(doc, term.field(), spans.start(), spans.end(), payloadsSeen, payloadScore, docScorer.computePayloadFactor(doc, spans.start(), spans.end(), payload)); } else { payloadScore = function.currentScore(doc, term.field(), spans.start(), spans.end(), payloadsSeen, payloadScore, 1F); } payloadsSeen++; } else { // zero out the payload? } } /** * * @return {@link #getSpanScore()} * {@link #getPayloadScore()} * @throws IOException */ @Override public float score() throws IOException { return includeSpanScore ? getSpanScore() * getPayloadScore() : getPayloadScore(); } /** * Returns the SpanScorer score only. * <p/> * Should not be overridden without good cause! * * @return the score for just the Span part w/o the payload * @throws IOException * * @see #score() */ protected float getSpanScore() throws IOException { return super.score(); } /** * The score for the payload * * @return The score, as calculated by * {@link PayloadFunction#docScore(int, String, int, float)} */ protected float getPayloadScore() { return function.docScore(doc, term.field(), payloadsSeen, payloadScore); } } @Override public Explanation explain(AtomicReaderContext context, int doc) throws IOException { PayloadTermSpanScorer scorer = (PayloadTermSpanScorer) scorer(context, true, false, context.reader().getLiveDocs()); if (scorer != null) { int newDoc = scorer.advance(doc); if (newDoc == doc) { float freq = scorer.freq(); SloppySimScorer docScorer = similarity.sloppySimScorer(stats, context); Explanation expl = new Explanation(); expl.setDescription("weight("+getQuery()+" in "+doc+") [" + similarity.getClass().getSimpleName() + "], result of:"); Explanation scoreExplanation = docScorer.explain(doc, new Explanation(freq, "phraseFreq=" + freq)); expl.addDetail(scoreExplanation); expl.setValue(scoreExplanation.getValue()); // now the payloads part // QUESTION: Is there a way to avoid this skipTo call? We need to know // whether to load the payload or not // GSI: I suppose we could toString the payload, but I don't think that // would be a good idea - Explanation payloadExpl = new Explanation(scorer.getPayloadScore(), "scorePayload(...)"); + Explanation payloadExpl = function.explain(doc, scorer.payloadsSeen, scorer.payloadScore); payloadExpl.setValue(scorer.getPayloadScore()); // combined ComplexExplanation result = new ComplexExplanation(); if (includeSpanScore) { result.addDetail(expl); result.addDetail(payloadExpl); result.setValue(expl.getValue() * payloadExpl.getValue()); result.setDescription("btq, product of:"); } else { result.addDetail(payloadExpl); result.setValue(payloadExpl.getValue()); result.setDescription("btq(includeSpanScore=false), result of:"); } result.setMatch(true); // LUCENE-1303 return result; } } return new ComplexExplanation(false, 0.0f, "no matching term"); } } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((function == null) ? 0 : function.hashCode()); result = prime * result + (includeSpanScore ? 1231 : 1237); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; PayloadTermQuery other = (PayloadTermQuery) obj; if (function == null) { if (other.function != null) return false; } else if (!function.equals(other.function)) return false; if (includeSpanScore != other.includeSpanScore) return false; return true; } }
true
true
public Explanation explain(AtomicReaderContext context, int doc) throws IOException { PayloadTermSpanScorer scorer = (PayloadTermSpanScorer) scorer(context, true, false, context.reader().getLiveDocs()); if (scorer != null) { int newDoc = scorer.advance(doc); if (newDoc == doc) { float freq = scorer.freq(); SloppySimScorer docScorer = similarity.sloppySimScorer(stats, context); Explanation expl = new Explanation(); expl.setDescription("weight("+getQuery()+" in "+doc+") [" + similarity.getClass().getSimpleName() + "], result of:"); Explanation scoreExplanation = docScorer.explain(doc, new Explanation(freq, "phraseFreq=" + freq)); expl.addDetail(scoreExplanation); expl.setValue(scoreExplanation.getValue()); // now the payloads part // QUESTION: Is there a way to avoid this skipTo call? We need to know // whether to load the payload or not // GSI: I suppose we could toString the payload, but I don't think that // would be a good idea Explanation payloadExpl = new Explanation(scorer.getPayloadScore(), "scorePayload(...)"); payloadExpl.setValue(scorer.getPayloadScore()); // combined ComplexExplanation result = new ComplexExplanation(); if (includeSpanScore) { result.addDetail(expl); result.addDetail(payloadExpl); result.setValue(expl.getValue() * payloadExpl.getValue()); result.setDescription("btq, product of:"); } else { result.addDetail(payloadExpl); result.setValue(payloadExpl.getValue()); result.setDescription("btq(includeSpanScore=false), result of:"); } result.setMatch(true); // LUCENE-1303 return result; } } return new ComplexExplanation(false, 0.0f, "no matching term"); }
public Explanation explain(AtomicReaderContext context, int doc) throws IOException { PayloadTermSpanScorer scorer = (PayloadTermSpanScorer) scorer(context, true, false, context.reader().getLiveDocs()); if (scorer != null) { int newDoc = scorer.advance(doc); if (newDoc == doc) { float freq = scorer.freq(); SloppySimScorer docScorer = similarity.sloppySimScorer(stats, context); Explanation expl = new Explanation(); expl.setDescription("weight("+getQuery()+" in "+doc+") [" + similarity.getClass().getSimpleName() + "], result of:"); Explanation scoreExplanation = docScorer.explain(doc, new Explanation(freq, "phraseFreq=" + freq)); expl.addDetail(scoreExplanation); expl.setValue(scoreExplanation.getValue()); // now the payloads part // QUESTION: Is there a way to avoid this skipTo call? We need to know // whether to load the payload or not // GSI: I suppose we could toString the payload, but I don't think that // would be a good idea Explanation payloadExpl = function.explain(doc, scorer.payloadsSeen, scorer.payloadScore); payloadExpl.setValue(scorer.getPayloadScore()); // combined ComplexExplanation result = new ComplexExplanation(); if (includeSpanScore) { result.addDetail(expl); result.addDetail(payloadExpl); result.setValue(expl.getValue() * payloadExpl.getValue()); result.setDescription("btq, product of:"); } else { result.addDetail(payloadExpl); result.setValue(payloadExpl.getValue()); result.setDescription("btq(includeSpanScore=false), result of:"); } result.setMatch(true); // LUCENE-1303 return result; } } return new ComplexExplanation(false, 0.0f, "no matching term"); }
diff --git a/src/uk/org/ponder/rsf/componentprocessor/ValueFixer.java b/src/uk/org/ponder/rsf/componentprocessor/ValueFixer.java index fe954a3..00bf28b 100644 --- a/src/uk/org/ponder/rsf/componentprocessor/ValueFixer.java +++ b/src/uk/org/ponder/rsf/componentprocessor/ValueFixer.java @@ -1,257 +1,257 @@ /* * Created on Nov 1, 2005 */ package uk.org.ponder.rsf.componentprocessor; import uk.org.ponder.beanutil.BeanLocator; import uk.org.ponder.beanutil.BeanModelAlterer; import uk.org.ponder.beanutil.BeanResolver; import uk.org.ponder.mapping.ShellInfo; import uk.org.ponder.mapping.support.ConverterConverter; import uk.org.ponder.mapping.support.DataConverterRegistry; import uk.org.ponder.messageutil.MessageLocator; import uk.org.ponder.rsf.components.ELReference; import uk.org.ponder.rsf.components.UIBound; import uk.org.ponder.rsf.components.UIComponent; import uk.org.ponder.rsf.components.UIForm; import uk.org.ponder.rsf.components.UIMessage; import uk.org.ponder.rsf.components.UIParameter; import uk.org.ponder.rsf.components.UIVerbatim; import uk.org.ponder.rsf.request.EarlyRequestParser; import uk.org.ponder.rsf.request.FossilizedConverter; import uk.org.ponder.rsf.request.RequestSubmittedValueCache; import uk.org.ponder.rsf.request.SubmittedValueEntry; import uk.org.ponder.rsf.state.support.ErrorStateManager; import uk.org.ponder.rsf.uitype.UITypes; import uk.org.ponder.util.Logger; import uk.org.ponder.util.UniversalRuntimeException; /** * Fetches values from the request bean model that are referenced via EL value * bindings, if such have not already been set. Will also compute the fossilized * binding for this component (not a completely cohesively coupled set of * functions, but we are accumulating quite a lot of little processors). * * @author Antranig Basman ([email protected]) */ public class ValueFixer implements ComponentProcessor { private BeanLocator beanlocator; private BeanModelAlterer alterer; private RequestSubmittedValueCache rsvc; private boolean renderfossilized; private DataConverterRegistry dataConverterRegistry; private MessageLocator messagelocator; public void setMessageLocator(MessageLocator messagelocator) { this.messagelocator = messagelocator; } public void setBeanLocator(BeanLocator beanlocator) { this.beanlocator = beanlocator; } public void setModelAlterer(BeanModelAlterer alterer) { this.alterer = alterer; } public void setRenderFossilizedForms(boolean renderfossilized) { this.renderfossilized = renderfossilized; } public void setDataConverterRegistry( DataConverterRegistry dataConverterRegistry) { this.dataConverterRegistry = dataConverterRegistry; } private FormModel formModel; public void setFormModel(FormModel formModel) { this.formModel = formModel; } public void setErrorStateManager(ErrorStateManager errorStateManager) { // this.errorStateManager = errorStateManager; if (errorStateManager.errorstate.rsvc != null) { rsvc = errorStateManager.errorstate.rsvc; } else rsvc = new RequestSubmittedValueCache(); } // This dependency is here so we can free FC from instance wiring cycle on // RenderSystem. A slight loss of efficiency since this component may never // be rendered - we might think about "lazy processors" at some point... private FossilizedConverter fossilizedconverter; public void setFossilizedConverter(FossilizedConverter fossilizedconverter) { this.fossilizedconverter = fossilizedconverter; } public void processComponent(UIComponent toprocesso) { if (toprocesso instanceof UIMessage) { UIMessage toprocess = (UIMessage) toprocesso; if (toprocess.arguments != null) { for (int i = 0; i < toprocess.arguments.length; ++ i) { if (toprocess.arguments[i] instanceof ELReference) { ELReference elref = (ELReference) toprocess.arguments[i]; String flatvalue = (String) alterer.getFlattenedValue(elref.value, beanlocator, String.class, null); toprocess.arguments[i] = flatvalue; } } - toprocess.setValue(messagelocator.getMessage(toprocess.messagekeys, - toprocess.arguments)); } + toprocess.setValue(messagelocator.getMessage(toprocess.messagekeys, + toprocess.arguments)); } if (toprocesso instanceof UIBound) { UIBound toprocess = (UIBound) toprocesso; // If there is a value in the SVE, return it to the control. SubmittedValueEntry sve = rsvc.byID(toprocess.getFullID()); boolean hadcached = false; Object modelvalue = null; if (sve != null && sve.newvalue != null) { toprocess.updateValue(sve.newvalue); hadcached = true; } UIForm form = formModel.formForComponent(toprocess); boolean getform = form == null ? false : form.type.equals(EarlyRequestParser.RENDER_REQUEST); Object root = getform ? (Object) form.viewparams : beanlocator; if (toprocess.valuebinding != null && (toprocess.acquireValue() == null || UITypes.isPlaceholder(toprocess.acquireValue()) || hadcached)) { // a bound component ALWAYS contains a value of the correct type. Object oldvalue = toprocess.acquireValue(); String stripbinding = toprocess.valuebinding.value; BeanResolver resolver = computeResolver(toprocess, root); Object flatvalue = null; try { flatvalue = alterer.getFlattenedValue(stripbinding, root, oldvalue .getClass(), resolver); } catch (Exception e) { // don't let a bad bean model prevent the correct reference being // encoded Logger.log.info("Error resolving EL reference " + stripbinding + " for component with full ID " + toprocess.getFullID(), e); } // If it was cached, we want to propagate the old "oldvalue" to the next // request if (hadcached) { modelvalue = sve.oldvalue; } else if (flatvalue != null) { modelvalue = flatvalue; toprocess.updateValue(flatvalue); } } else if (toprocess.resolver != null) { Object oldvalue = toprocess.acquireValue(); // User may have directly supplied raw value + resolver, for example // MessageKeys. Note that this function of ValueFixer is non-idempotent. BeanResolver resolver = computeResolver(toprocess, root); Object flatvalue = alterer.getFlattenedValue(null, oldvalue, oldvalue .getClass(), resolver); if (flatvalue != null) { toprocess.updateValue(flatvalue); } } if (toprocess.submittingname == null) { toprocess.submittingname = toprocess.getFullID(); } if (toprocess.valuebinding != null && !getform) { // TODO: Think carefully whether we want these "encoded" bindings to // EVER appear in the component tree. Tradeoffs - we would need to // create // more classes that renderer could recognise to compute bindings, and // increase its knowledge about the rest of RSF. if (toprocess.fossilize && toprocess.fossilizedbinding == null && renderfossilized) { UIParameter fossilized = fossilizedconverter .computeFossilizedBinding(toprocess, modelvalue); toprocess.fossilizedbinding = fossilized; } if (toprocess.darreshaper != null) { toprocess.fossilizedshaper = fossilizedconverter .computeReshaperBinding(toprocess); } } if (toprocess.acquireValue() == null) { throw new IllegalArgumentException( "Error following value fixup: null bound value found in component " + toprocess + " with full ID " + toprocess.getFullID()); } } else if (toprocesso instanceof UIVerbatim) { UIVerbatim toprocess = (UIVerbatim) toprocesso; if (toprocess.markup instanceof ELReference) { ELReference ref = (ELReference) toprocess.markup; toprocess.markup = alterer.getBeanValue(ref.value, beanlocator, null); } if (toprocess.resolver != null) { // User may have directly supplied raw value + resolver, for example // MessageKeys. Note that this function of ValueFixer is non-idempotent. BeanResolver resolver = computeResolver(toprocess, beanlocator); Object flatvalue = alterer.getFlattenedValue(null, toprocess.markup, toprocess.markup .getClass(), resolver); if (flatvalue != null) { toprocess.markup = flatvalue; } } } } /** * As well as resolving any reference to a BeanResolver in the * <code>resolver</code> field, this method will also copy it across to the * <code>darreshaper</code> field if a) it refers to a LeafObjectParser, and * b) the field is currently empty. This is a courtesy to allow compactly * encoded things like DateParsers to be used first class, although we REALLY * expect users to make transit beans. */ private BeanResolver computeResolver(UIComponent toprocess, Object root) { Object renderer = toprocess instanceof UIBound ? ((UIBound) toprocess).resolver : ((UIVerbatim) toprocess).resolver; ELReference valuebinding = null; UIBound bound = null; if (toprocess instanceof UIBound) { bound = (UIBound) toprocess; valuebinding = bound.valuebinding; } else { UIVerbatim toprocessv = (UIVerbatim) toprocess; if (toprocessv.markup instanceof ELReference) { valuebinding = (ELReference) toprocessv.markup; } } if (renderer == null) { if (valuebinding != null) { ShellInfo shells = alterer.fetchShells(valuebinding.value, root, false); renderer = dataConverterRegistry.fetchConverter(shells); } } if (renderer instanceof ELReference) { renderer = alterer.getBeanValue(((ELReference) renderer).value, beanlocator, null); if (bound != null && bound.darreshaper == null) { bound.darreshaper = (ELReference) bound.resolver; } } if (renderer == null) return null; BeanResolver resolver = ConverterConverter.toResolver(renderer); if (resolver == null) { throw UniversalRuntimeException.accumulate( new IllegalArgumentException(), "Renderer object for " + toprocess.getFullID() + " of unrecognised " + renderer.getClass() + " (expected BeanResolver or LeafObjectParser)"); } return resolver; } }
false
true
public void processComponent(UIComponent toprocesso) { if (toprocesso instanceof UIMessage) { UIMessage toprocess = (UIMessage) toprocesso; if (toprocess.arguments != null) { for (int i = 0; i < toprocess.arguments.length; ++ i) { if (toprocess.arguments[i] instanceof ELReference) { ELReference elref = (ELReference) toprocess.arguments[i]; String flatvalue = (String) alterer.getFlattenedValue(elref.value, beanlocator, String.class, null); toprocess.arguments[i] = flatvalue; } } toprocess.setValue(messagelocator.getMessage(toprocess.messagekeys, toprocess.arguments)); } } if (toprocesso instanceof UIBound) { UIBound toprocess = (UIBound) toprocesso; // If there is a value in the SVE, return it to the control. SubmittedValueEntry sve = rsvc.byID(toprocess.getFullID()); boolean hadcached = false; Object modelvalue = null; if (sve != null && sve.newvalue != null) { toprocess.updateValue(sve.newvalue); hadcached = true; } UIForm form = formModel.formForComponent(toprocess); boolean getform = form == null ? false : form.type.equals(EarlyRequestParser.RENDER_REQUEST); Object root = getform ? (Object) form.viewparams : beanlocator; if (toprocess.valuebinding != null && (toprocess.acquireValue() == null || UITypes.isPlaceholder(toprocess.acquireValue()) || hadcached)) { // a bound component ALWAYS contains a value of the correct type. Object oldvalue = toprocess.acquireValue(); String stripbinding = toprocess.valuebinding.value; BeanResolver resolver = computeResolver(toprocess, root); Object flatvalue = null; try { flatvalue = alterer.getFlattenedValue(stripbinding, root, oldvalue .getClass(), resolver); } catch (Exception e) { // don't let a bad bean model prevent the correct reference being // encoded Logger.log.info("Error resolving EL reference " + stripbinding + " for component with full ID " + toprocess.getFullID(), e); } // If it was cached, we want to propagate the old "oldvalue" to the next // request if (hadcached) { modelvalue = sve.oldvalue; } else if (flatvalue != null) { modelvalue = flatvalue; toprocess.updateValue(flatvalue); } } else if (toprocess.resolver != null) { Object oldvalue = toprocess.acquireValue(); // User may have directly supplied raw value + resolver, for example // MessageKeys. Note that this function of ValueFixer is non-idempotent. BeanResolver resolver = computeResolver(toprocess, root); Object flatvalue = alterer.getFlattenedValue(null, oldvalue, oldvalue .getClass(), resolver); if (flatvalue != null) { toprocess.updateValue(flatvalue); } } if (toprocess.submittingname == null) { toprocess.submittingname = toprocess.getFullID(); } if (toprocess.valuebinding != null && !getform) { // TODO: Think carefully whether we want these "encoded" bindings to // EVER appear in the component tree. Tradeoffs - we would need to // create // more classes that renderer could recognise to compute bindings, and // increase its knowledge about the rest of RSF. if (toprocess.fossilize && toprocess.fossilizedbinding == null && renderfossilized) { UIParameter fossilized = fossilizedconverter .computeFossilizedBinding(toprocess, modelvalue); toprocess.fossilizedbinding = fossilized; } if (toprocess.darreshaper != null) { toprocess.fossilizedshaper = fossilizedconverter .computeReshaperBinding(toprocess); } } if (toprocess.acquireValue() == null) { throw new IllegalArgumentException( "Error following value fixup: null bound value found in component " + toprocess + " with full ID " + toprocess.getFullID()); } } else if (toprocesso instanceof UIVerbatim) { UIVerbatim toprocess = (UIVerbatim) toprocesso; if (toprocess.markup instanceof ELReference) { ELReference ref = (ELReference) toprocess.markup; toprocess.markup = alterer.getBeanValue(ref.value, beanlocator, null); } if (toprocess.resolver != null) { // User may have directly supplied raw value + resolver, for example // MessageKeys. Note that this function of ValueFixer is non-idempotent. BeanResolver resolver = computeResolver(toprocess, beanlocator); Object flatvalue = alterer.getFlattenedValue(null, toprocess.markup, toprocess.markup .getClass(), resolver); if (flatvalue != null) { toprocess.markup = flatvalue; } } } }
public void processComponent(UIComponent toprocesso) { if (toprocesso instanceof UIMessage) { UIMessage toprocess = (UIMessage) toprocesso; if (toprocess.arguments != null) { for (int i = 0; i < toprocess.arguments.length; ++ i) { if (toprocess.arguments[i] instanceof ELReference) { ELReference elref = (ELReference) toprocess.arguments[i]; String flatvalue = (String) alterer.getFlattenedValue(elref.value, beanlocator, String.class, null); toprocess.arguments[i] = flatvalue; } } } toprocess.setValue(messagelocator.getMessage(toprocess.messagekeys, toprocess.arguments)); } if (toprocesso instanceof UIBound) { UIBound toprocess = (UIBound) toprocesso; // If there is a value in the SVE, return it to the control. SubmittedValueEntry sve = rsvc.byID(toprocess.getFullID()); boolean hadcached = false; Object modelvalue = null; if (sve != null && sve.newvalue != null) { toprocess.updateValue(sve.newvalue); hadcached = true; } UIForm form = formModel.formForComponent(toprocess); boolean getform = form == null ? false : form.type.equals(EarlyRequestParser.RENDER_REQUEST); Object root = getform ? (Object) form.viewparams : beanlocator; if (toprocess.valuebinding != null && (toprocess.acquireValue() == null || UITypes.isPlaceholder(toprocess.acquireValue()) || hadcached)) { // a bound component ALWAYS contains a value of the correct type. Object oldvalue = toprocess.acquireValue(); String stripbinding = toprocess.valuebinding.value; BeanResolver resolver = computeResolver(toprocess, root); Object flatvalue = null; try { flatvalue = alterer.getFlattenedValue(stripbinding, root, oldvalue .getClass(), resolver); } catch (Exception e) { // don't let a bad bean model prevent the correct reference being // encoded Logger.log.info("Error resolving EL reference " + stripbinding + " for component with full ID " + toprocess.getFullID(), e); } // If it was cached, we want to propagate the old "oldvalue" to the next // request if (hadcached) { modelvalue = sve.oldvalue; } else if (flatvalue != null) { modelvalue = flatvalue; toprocess.updateValue(flatvalue); } } else if (toprocess.resolver != null) { Object oldvalue = toprocess.acquireValue(); // User may have directly supplied raw value + resolver, for example // MessageKeys. Note that this function of ValueFixer is non-idempotent. BeanResolver resolver = computeResolver(toprocess, root); Object flatvalue = alterer.getFlattenedValue(null, oldvalue, oldvalue .getClass(), resolver); if (flatvalue != null) { toprocess.updateValue(flatvalue); } } if (toprocess.submittingname == null) { toprocess.submittingname = toprocess.getFullID(); } if (toprocess.valuebinding != null && !getform) { // TODO: Think carefully whether we want these "encoded" bindings to // EVER appear in the component tree. Tradeoffs - we would need to // create // more classes that renderer could recognise to compute bindings, and // increase its knowledge about the rest of RSF. if (toprocess.fossilize && toprocess.fossilizedbinding == null && renderfossilized) { UIParameter fossilized = fossilizedconverter .computeFossilizedBinding(toprocess, modelvalue); toprocess.fossilizedbinding = fossilized; } if (toprocess.darreshaper != null) { toprocess.fossilizedshaper = fossilizedconverter .computeReshaperBinding(toprocess); } } if (toprocess.acquireValue() == null) { throw new IllegalArgumentException( "Error following value fixup: null bound value found in component " + toprocess + " with full ID " + toprocess.getFullID()); } } else if (toprocesso instanceof UIVerbatim) { UIVerbatim toprocess = (UIVerbatim) toprocesso; if (toprocess.markup instanceof ELReference) { ELReference ref = (ELReference) toprocess.markup; toprocess.markup = alterer.getBeanValue(ref.value, beanlocator, null); } if (toprocess.resolver != null) { // User may have directly supplied raw value + resolver, for example // MessageKeys. Note that this function of ValueFixer is non-idempotent. BeanResolver resolver = computeResolver(toprocess, beanlocator); Object flatvalue = alterer.getFlattenedValue(null, toprocess.markup, toprocess.markup .getClass(), resolver); if (flatvalue != null) { toprocess.markup = flatvalue; } } } }
diff --git a/src/main/java/net/md_5/specialsource/SpecialSource.java b/src/main/java/net/md_5/specialsource/SpecialSource.java index 42f801d..03f99c6 100644 --- a/src/main/java/net/md_5/specialsource/SpecialSource.java +++ b/src/main/java/net/md_5/specialsource/SpecialSource.java @@ -1,199 +1,200 @@ /** * Copyright (c) 2012, md_5. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * The name of the author may not be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package net.md_5.specialsource; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import joptsimple.OptionException; import joptsimple.OptionParser; import joptsimple.OptionSet; import org.objectweb.asm.ClassReader; import static java.util.Arrays.asList; public class SpecialSource { private static OptionSet options; public static void main(String[] args) throws Exception { OptionParser parser = new OptionParser() { { acceptsAll(asList("?", "help"), "Show the help"); acceptsAll(asList("a", "first-jar"), "First jar") .withRequiredArg() .ofType(File.class); acceptsAll(asList("b", "second-jar"), "Second jar") .withRequiredArg() .ofType(File.class); acceptsAll(asList("s", "srg-out"), "Mapping file output") .withRequiredArg() .ofType(File.class); acceptsAll(asList("m", "srg-in"), "Mapping file input") .withRequiredArg() .ofType(File.class); acceptsAll(asList("i", "in-jar"), "Input jar to remap") .withRequiredArg() .ofType(File.class); acceptsAll(asList("o", "out-jar"), "Output jar to write") .withRequiredArg() .ofType(File.class); acceptsAll(asList("R", "shade-relocation"), "Simulate maven-shade-plugin relocation patterns on srg-in") .withRequiredArg() .withValuesSeparatedBy(','); acceptsAll(asList("l", "live"), "Enable runtime inheritance lookup"); acceptsAll(asList("q", "quiet"), "Quiet mode"); acceptsAll(asList("c", "compact"), "Output mapping file in compact format"); } }; try { options = parser.parse(args); } catch (OptionException ex) { System.out.println(ex.getLocalizedMessage()); return; } if (options == null || options.has("?")) { try { parser.printHelpOn(System.err); return; } catch (IOException ex) { System.out.println(ex.getLocalizedMessage()); return; } } JarMapping jarMapping; if (options.has("first-jar") && options.has("second-jar")) { // Generate mappings from two otherwise-identical jars log("Reading jars"); Jar jar1 = Jar.init((File) options.valueOf("first-jar")); Jar jar2 = Jar.init((File) options.valueOf("second-jar")); log("Creating jar compare"); JarComparer visitor1 = new JarComparer(jar1); JarComparer visitor2 = new JarComparer(jar2); visit(new Pair<Jar>(jar1, jar2), new Pair<JarComparer>(visitor1, visitor2), new Pair<String>(jar1.main, jar2.main)); jarMapping = new JarMapping(visitor1, visitor2, (File) options.valueOf("srg-out"), options.has("compact")); } else if (options.has("srg-in")) { // Load mappings, possibly shaded ShadeRelocationSimulator shadeRelocationSimulator = null; if (options.has("shade-relocation")) { + @SuppressWarnings("unchecked") List<String> relocations = (List<String>) options.valuesOf("shade-relocation"); shadeRelocationSimulator = new ShadeRelocationSimulator(relocations); for (Map.Entry<String, String> entry : shadeRelocationSimulator.relocations.entrySet()) { log("Relocation: " + entry.getKey() + " -> " + entry.getValue()); } } log("Loading mappings"); jarMapping = new JarMapping((File) options.valueOf("srg-in"), shadeRelocationSimulator); } else { System.err.println("No mappings given, first-jar/second-jar or srg-in required"); parser.printHelpOn(System.err); return; } log(jarMapping.classes.size() + " classes, " + jarMapping.fields.size() + " fields, " + jarMapping.methods.size() + " methods"); if (options.has("in-jar")) { if (!options.has("out-jar")) { System.err.println("No output jar given, in-jar requires in-jar"); parser.printHelpOn(System.err); return; } log("Remapping final jar"); Jar jar3 = Jar.init((File) options.valueOf("in-jar")); List<IInheritanceProvider> inheritanceProviders = new ArrayList<IInheritanceProvider>(); inheritanceProviders.add(new JarInheritanceProvider(jar3)); if (options.has("live")) { inheritanceProviders.add(new RuntimeInheritanceProvider()); } JarRemapper jarRemapper = new JarRemapper(jarMapping, inheritanceProviders); jarRemapper.remapJar(jar3, (File) options.valueOf("out-jar")); } } private static void log(String message) { if (!options.has("q")) { System.out.println(message); } } private static void visit(Pair<Jar> jars, Pair<JarComparer> visitors, Pair<String> classes) throws IOException { JarComparer visitor1 = visitors.first; JarComparer visitor2 = visitors.second; ClassReader clazz1 = new ClassReader(jars.first.getClass(classes.first)); ClassReader clazz2 = new ClassReader(jars.second.getClass(classes.second)); clazz1.accept(visitor1, 0); clazz2.accept(visitor2, 0); validate(visitor1, visitor2); while (visitor1.iterDepth < visitor1.classes.size()) { String className1 = visitor1.classes.get(visitor1.iterDepth); String className2 = visitor2.classes.get(visitor1.iterDepth); Pair<String> pair = new Pair<String>(className1, className2); visitor1.iterDepth++; visit(jars, visitors, pair); } } public static void validate(JarComparer visitor1, JarComparer visitor2) { if (visitor1.classes.size() != visitor2.classes.size()) { throw new IllegalStateException("classes"); } if (visitor1.fields.size() != visitor2.fields.size()) { throw new IllegalStateException("fields"); } if (visitor1.methods.size() != visitor2.methods.size()) { throw new IllegalStateException("methods"); } } }
true
true
public static void main(String[] args) throws Exception { OptionParser parser = new OptionParser() { { acceptsAll(asList("?", "help"), "Show the help"); acceptsAll(asList("a", "first-jar"), "First jar") .withRequiredArg() .ofType(File.class); acceptsAll(asList("b", "second-jar"), "Second jar") .withRequiredArg() .ofType(File.class); acceptsAll(asList("s", "srg-out"), "Mapping file output") .withRequiredArg() .ofType(File.class); acceptsAll(asList("m", "srg-in"), "Mapping file input") .withRequiredArg() .ofType(File.class); acceptsAll(asList("i", "in-jar"), "Input jar to remap") .withRequiredArg() .ofType(File.class); acceptsAll(asList("o", "out-jar"), "Output jar to write") .withRequiredArg() .ofType(File.class); acceptsAll(asList("R", "shade-relocation"), "Simulate maven-shade-plugin relocation patterns on srg-in") .withRequiredArg() .withValuesSeparatedBy(','); acceptsAll(asList("l", "live"), "Enable runtime inheritance lookup"); acceptsAll(asList("q", "quiet"), "Quiet mode"); acceptsAll(asList("c", "compact"), "Output mapping file in compact format"); } }; try { options = parser.parse(args); } catch (OptionException ex) { System.out.println(ex.getLocalizedMessage()); return; } if (options == null || options.has("?")) { try { parser.printHelpOn(System.err); return; } catch (IOException ex) { System.out.println(ex.getLocalizedMessage()); return; } } JarMapping jarMapping; if (options.has("first-jar") && options.has("second-jar")) { // Generate mappings from two otherwise-identical jars log("Reading jars"); Jar jar1 = Jar.init((File) options.valueOf("first-jar")); Jar jar2 = Jar.init((File) options.valueOf("second-jar")); log("Creating jar compare"); JarComparer visitor1 = new JarComparer(jar1); JarComparer visitor2 = new JarComparer(jar2); visit(new Pair<Jar>(jar1, jar2), new Pair<JarComparer>(visitor1, visitor2), new Pair<String>(jar1.main, jar2.main)); jarMapping = new JarMapping(visitor1, visitor2, (File) options.valueOf("srg-out"), options.has("compact")); } else if (options.has("srg-in")) { // Load mappings, possibly shaded ShadeRelocationSimulator shadeRelocationSimulator = null; if (options.has("shade-relocation")) { List<String> relocations = (List<String>) options.valuesOf("shade-relocation"); shadeRelocationSimulator = new ShadeRelocationSimulator(relocations); for (Map.Entry<String, String> entry : shadeRelocationSimulator.relocations.entrySet()) { log("Relocation: " + entry.getKey() + " -> " + entry.getValue()); } } log("Loading mappings"); jarMapping = new JarMapping((File) options.valueOf("srg-in"), shadeRelocationSimulator); } else { System.err.println("No mappings given, first-jar/second-jar or srg-in required"); parser.printHelpOn(System.err); return; } log(jarMapping.classes.size() + " classes, " + jarMapping.fields.size() + " fields, " + jarMapping.methods.size() + " methods"); if (options.has("in-jar")) { if (!options.has("out-jar")) { System.err.println("No output jar given, in-jar requires in-jar"); parser.printHelpOn(System.err); return; } log("Remapping final jar"); Jar jar3 = Jar.init((File) options.valueOf("in-jar")); List<IInheritanceProvider> inheritanceProviders = new ArrayList<IInheritanceProvider>(); inheritanceProviders.add(new JarInheritanceProvider(jar3)); if (options.has("live")) { inheritanceProviders.add(new RuntimeInheritanceProvider()); } JarRemapper jarRemapper = new JarRemapper(jarMapping, inheritanceProviders); jarRemapper.remapJar(jar3, (File) options.valueOf("out-jar")); } }
public static void main(String[] args) throws Exception { OptionParser parser = new OptionParser() { { acceptsAll(asList("?", "help"), "Show the help"); acceptsAll(asList("a", "first-jar"), "First jar") .withRequiredArg() .ofType(File.class); acceptsAll(asList("b", "second-jar"), "Second jar") .withRequiredArg() .ofType(File.class); acceptsAll(asList("s", "srg-out"), "Mapping file output") .withRequiredArg() .ofType(File.class); acceptsAll(asList("m", "srg-in"), "Mapping file input") .withRequiredArg() .ofType(File.class); acceptsAll(asList("i", "in-jar"), "Input jar to remap") .withRequiredArg() .ofType(File.class); acceptsAll(asList("o", "out-jar"), "Output jar to write") .withRequiredArg() .ofType(File.class); acceptsAll(asList("R", "shade-relocation"), "Simulate maven-shade-plugin relocation patterns on srg-in") .withRequiredArg() .withValuesSeparatedBy(','); acceptsAll(asList("l", "live"), "Enable runtime inheritance lookup"); acceptsAll(asList("q", "quiet"), "Quiet mode"); acceptsAll(asList("c", "compact"), "Output mapping file in compact format"); } }; try { options = parser.parse(args); } catch (OptionException ex) { System.out.println(ex.getLocalizedMessage()); return; } if (options == null || options.has("?")) { try { parser.printHelpOn(System.err); return; } catch (IOException ex) { System.out.println(ex.getLocalizedMessage()); return; } } JarMapping jarMapping; if (options.has("first-jar") && options.has("second-jar")) { // Generate mappings from two otherwise-identical jars log("Reading jars"); Jar jar1 = Jar.init((File) options.valueOf("first-jar")); Jar jar2 = Jar.init((File) options.valueOf("second-jar")); log("Creating jar compare"); JarComparer visitor1 = new JarComparer(jar1); JarComparer visitor2 = new JarComparer(jar2); visit(new Pair<Jar>(jar1, jar2), new Pair<JarComparer>(visitor1, visitor2), new Pair<String>(jar1.main, jar2.main)); jarMapping = new JarMapping(visitor1, visitor2, (File) options.valueOf("srg-out"), options.has("compact")); } else if (options.has("srg-in")) { // Load mappings, possibly shaded ShadeRelocationSimulator shadeRelocationSimulator = null; if (options.has("shade-relocation")) { @SuppressWarnings("unchecked") List<String> relocations = (List<String>) options.valuesOf("shade-relocation"); shadeRelocationSimulator = new ShadeRelocationSimulator(relocations); for (Map.Entry<String, String> entry : shadeRelocationSimulator.relocations.entrySet()) { log("Relocation: " + entry.getKey() + " -> " + entry.getValue()); } } log("Loading mappings"); jarMapping = new JarMapping((File) options.valueOf("srg-in"), shadeRelocationSimulator); } else { System.err.println("No mappings given, first-jar/second-jar or srg-in required"); parser.printHelpOn(System.err); return; } log(jarMapping.classes.size() + " classes, " + jarMapping.fields.size() + " fields, " + jarMapping.methods.size() + " methods"); if (options.has("in-jar")) { if (!options.has("out-jar")) { System.err.println("No output jar given, in-jar requires in-jar"); parser.printHelpOn(System.err); return; } log("Remapping final jar"); Jar jar3 = Jar.init((File) options.valueOf("in-jar")); List<IInheritanceProvider> inheritanceProviders = new ArrayList<IInheritanceProvider>(); inheritanceProviders.add(new JarInheritanceProvider(jar3)); if (options.has("live")) { inheritanceProviders.add(new RuntimeInheritanceProvider()); } JarRemapper jarRemapper = new JarRemapper(jarMapping, inheritanceProviders); jarRemapper.remapJar(jar3, (File) options.valueOf("out-jar")); } }
diff --git a/photobox/src/com/photobox/app/PicasaActivity.java b/photobox/src/com/photobox/app/PicasaActivity.java index a840b9b..6db89dc 100644 --- a/photobox/src/com/photobox/app/PicasaActivity.java +++ b/photobox/src/com/photobox/app/PicasaActivity.java @@ -1,64 +1,64 @@ package com.photobox.app; import java.io.File; import java.util.*; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.util.*; import android.os.Bundle; import android.os.Environment; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.*; import com.photobox.R; import com.photobox.files.*; public class PicasaActivity extends Activity { private ListView albumList; private EditText usernameEditText; private PicasaActivity thisActivity; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); thisActivity = this; setContentView(R.layout.picasa); usernameEditText = (EditText)findViewById(R.id.usernameEditText); albumList = (ListView)findViewById(R.id.albumList); Button loadAlbumsButton = (Button)findViewById(R.id.loadAlbumsButton); loadAlbumsButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { List<String> albums = new PicasaApi("" + usernameEditText.getText()).getAlbums(); String[] items; if (albums != null) { items = albums.toArray(new String[] {"dummy array to get correct type"}); } else { - items = new String[] { "no albums found" }; + items = new String[] { "No albums found" }; } ArrayAdapter<String> adapter = new ArrayAdapter<String>( thisActivity, android.R.layout.simple_list_item_1, android.R.id.text1, items); albumList.setAdapter(adapter); } }); } }
true
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); thisActivity = this; setContentView(R.layout.picasa); usernameEditText = (EditText)findViewById(R.id.usernameEditText); albumList = (ListView)findViewById(R.id.albumList); Button loadAlbumsButton = (Button)findViewById(R.id.loadAlbumsButton); loadAlbumsButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { List<String> albums = new PicasaApi("" + usernameEditText.getText()).getAlbums(); String[] items; if (albums != null) { items = albums.toArray(new String[] {"dummy array to get correct type"}); } else { items = new String[] { "no albums found" }; } ArrayAdapter<String> adapter = new ArrayAdapter<String>( thisActivity, android.R.layout.simple_list_item_1, android.R.id.text1, items); albumList.setAdapter(adapter); } }); }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); thisActivity = this; setContentView(R.layout.picasa); usernameEditText = (EditText)findViewById(R.id.usernameEditText); albumList = (ListView)findViewById(R.id.albumList); Button loadAlbumsButton = (Button)findViewById(R.id.loadAlbumsButton); loadAlbumsButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { List<String> albums = new PicasaApi("" + usernameEditText.getText()).getAlbums(); String[] items; if (albums != null) { items = albums.toArray(new String[] {"dummy array to get correct type"}); } else { items = new String[] { "No albums found" }; } ArrayAdapter<String> adapter = new ArrayAdapter<String>( thisActivity, android.R.layout.simple_list_item_1, android.R.id.text1, items); albumList.setAdapter(adapter); } }); }
diff --git a/src/main/java/uk/co/oliwali/HawkEye/SearchParser.java b/src/main/java/uk/co/oliwali/HawkEye/SearchParser.java index 5f1f825..30c8bf8 100644 --- a/src/main/java/uk/co/oliwali/HawkEye/SearchParser.java +++ b/src/main/java/uk/co/oliwali/HawkEye/SearchParser.java @@ -1,194 +1,194 @@ package uk.co.oliwali.HawkEye; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.util.Vector; import uk.co.oliwali.HawkEye.util.Permission; import uk.co.oliwali.HawkEye.util.Util; /** * Class for parsing HawkEye arguments ready to be used by an instance of {@SearchQuery} * @author oliverw92 */ public class SearchParser { public Player player = null; public String[] players = null; public Vector loc = null; public Vector minLoc = null; public Vector maxLoc = null; public Integer radius = null; public List<DataType> actions = new ArrayList<DataType>(); public String[] worlds = null; public String dateFrom = null; public String dateTo = null; public String[] filters = null; public SearchParser() { } public SearchParser(Player player) { this.player = player; } public SearchParser(Player player, int radius) { this.player = player; this.radius = radius; parseLocations(); } public SearchParser(Player player, List<String> args) throws IllegalArgumentException { this.player = player; for (String arg : args) { //Check if argument has a valid prefix if (arg.equalsIgnoreCase("")) continue; String param = arg.substring(0,1).toLowerCase(); if (!arg.substring(1,2).equals(":")) throw new IllegalArgumentException("Invalid argument format: &7" + arg); String[] values = arg.substring(2).split(","); //Players if (param.equals("p")) players = values; //Worlds else if (param.equals("w")) worlds = values; //Filters else if (param.equals("f")) { if (filters != null) filters = Util.concat(filters, values); else filters = values; } //Blocks else if (param.equals("b")) { for (int i = 1; i < values.length; i++) { if (Material.getMaterial(values[i]) != null) values[i] = Integer.toString(Material.getMaterial(values[i]).getId()); } if (filters != null) filters = Util.concat(filters, values); else filters = values; } //Actions else if (param.equals("a")) { for (String value : values) { DataType type = DataType.fromName(value); if (type == null) throw new IllegalArgumentException("Invalid action supplied: &7" + value); if (!Permission.searchType(player, type.getConfigName())) throw new IllegalArgumentException("You do not have permission to search for: &7" + type.getConfigName()); actions.add(type); } } //Location else if (param.equals("l")) { if (values[0].equalsIgnoreCase("here")) loc = player.getLocation().toVector(); else { loc = new Vector(); loc.setX(Integer.parseInt(values[0])); loc.setY(Integer.parseInt(values[1])); loc.setZ(Integer.parseInt(values[2])); } } //Radius else if (param.equals("r")) { if (!Util.isInteger(values[0])) throw new IllegalArgumentException("Invalid radius supplied: &7" + values[0]); radius = Integer.parseInt(values[0]); } //Time else if (param.equals("t")) { int type = 2; for (int i = 0; i < arg.length(); i++) { String c = arg.substring(i, i+1); if (!Util.isInteger(c)) { - if (c.equals("m") || c .equals("s") || c.equals("h")) + if (c.equals("m") || c .equals("s") || c.equals("h") || c.equals("d") || c.equals("w")) type = 0; if (c.equals("-") || c.equals(":")) type = 1; } } //If the time is in the format '0w0d0h0m0s' if (type == 0) { int weeks = 0; int days = 0; int hours = 0; int mins = 0; int secs = 0; String nums = ""; for (int i = 0; i < values[0].length(); i++) { String c = values[0].substring(i, i+1); if (Util.isInteger(c)) { nums += c; continue; } int num = Integer.parseInt(nums); if (c.equals("w")) weeks = num; else if (c.equals("d")) days = num; else if (c.equals("h")) hours = num; else if (c.equals("m")) mins = num; else if (c.equals("s")) secs = num; else throw new IllegalArgumentException("Invalid time measurement: &7" + c); nums = ""; } Calendar cal = Calendar.getInstance(); cal.add(Calendar.WEEK_OF_YEAR, -1 * weeks); cal.add(Calendar.DAY_OF_MONTH, -1 * days); cal.add(Calendar.HOUR, -1 * hours); cal.add(Calendar.MINUTE, -1 * mins); cal.add(Calendar.SECOND, -1 * secs); SimpleDateFormat form = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); dateFrom = form.format(cal.getTime()); } //If the time is in the format 'yyyy-MM-dd HH:mm:ss' else if (type == 1) { if (values.length == 1) { SimpleDateFormat form = new SimpleDateFormat("yyyy-MM-dd"); dateFrom = form.format(Calendar.getInstance().getTime()) + " " + values[0]; } if (values.length >= 2) dateFrom = values[0] + " " + values[1]; if (values.length == 4) dateTo = values[2] + " " + values[3]; } //Invalid time format else if (type == 2) throw new IllegalArgumentException("Invalid time format!"); } else throw new IllegalArgumentException("Invalid parameter supplied: &7" + param); } //Sort out locations parseLocations(); } /** * Formats min and max locations if the radius is set */ public void parseLocations() { //If the radius is set we need to format the min and max locations if (radius != null) { //Check if location and world are supplied if (loc == null) loc = player.getLocation().toVector(); if (worlds == null) worlds = new String[]{ player.getWorld().getName() }; //Format min and max minLoc = new Vector(loc.getX() - radius, loc.getY() - radius, loc.getZ() - radius); maxLoc = new Vector(loc.getX() + radius, loc.getY() + radius, loc.getZ() + radius); } } }
true
true
public SearchParser(Player player, List<String> args) throws IllegalArgumentException { this.player = player; for (String arg : args) { //Check if argument has a valid prefix if (arg.equalsIgnoreCase("")) continue; String param = arg.substring(0,1).toLowerCase(); if (!arg.substring(1,2).equals(":")) throw new IllegalArgumentException("Invalid argument format: &7" + arg); String[] values = arg.substring(2).split(","); //Players if (param.equals("p")) players = values; //Worlds else if (param.equals("w")) worlds = values; //Filters else if (param.equals("f")) { if (filters != null) filters = Util.concat(filters, values); else filters = values; } //Blocks else if (param.equals("b")) { for (int i = 1; i < values.length; i++) { if (Material.getMaterial(values[i]) != null) values[i] = Integer.toString(Material.getMaterial(values[i]).getId()); } if (filters != null) filters = Util.concat(filters, values); else filters = values; } //Actions else if (param.equals("a")) { for (String value : values) { DataType type = DataType.fromName(value); if (type == null) throw new IllegalArgumentException("Invalid action supplied: &7" + value); if (!Permission.searchType(player, type.getConfigName())) throw new IllegalArgumentException("You do not have permission to search for: &7" + type.getConfigName()); actions.add(type); } } //Location else if (param.equals("l")) { if (values[0].equalsIgnoreCase("here")) loc = player.getLocation().toVector(); else { loc = new Vector(); loc.setX(Integer.parseInt(values[0])); loc.setY(Integer.parseInt(values[1])); loc.setZ(Integer.parseInt(values[2])); } } //Radius else if (param.equals("r")) { if (!Util.isInteger(values[0])) throw new IllegalArgumentException("Invalid radius supplied: &7" + values[0]); radius = Integer.parseInt(values[0]); } //Time else if (param.equals("t")) { int type = 2; for (int i = 0; i < arg.length(); i++) { String c = arg.substring(i, i+1); if (!Util.isInteger(c)) { if (c.equals("m") || c .equals("s") || c.equals("h")) type = 0; if (c.equals("-") || c.equals(":")) type = 1; } } //If the time is in the format '0w0d0h0m0s' if (type == 0) { int weeks = 0; int days = 0; int hours = 0; int mins = 0; int secs = 0; String nums = ""; for (int i = 0; i < values[0].length(); i++) { String c = values[0].substring(i, i+1); if (Util.isInteger(c)) { nums += c; continue; } int num = Integer.parseInt(nums); if (c.equals("w")) weeks = num; else if (c.equals("d")) days = num; else if (c.equals("h")) hours = num; else if (c.equals("m")) mins = num; else if (c.equals("s")) secs = num; else throw new IllegalArgumentException("Invalid time measurement: &7" + c); nums = ""; } Calendar cal = Calendar.getInstance(); cal.add(Calendar.WEEK_OF_YEAR, -1 * weeks); cal.add(Calendar.DAY_OF_MONTH, -1 * days); cal.add(Calendar.HOUR, -1 * hours); cal.add(Calendar.MINUTE, -1 * mins); cal.add(Calendar.SECOND, -1 * secs); SimpleDateFormat form = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); dateFrom = form.format(cal.getTime()); } //If the time is in the format 'yyyy-MM-dd HH:mm:ss' else if (type == 1) { if (values.length == 1) { SimpleDateFormat form = new SimpleDateFormat("yyyy-MM-dd"); dateFrom = form.format(Calendar.getInstance().getTime()) + " " + values[0]; } if (values.length >= 2) dateFrom = values[0] + " " + values[1]; if (values.length == 4) dateTo = values[2] + " " + values[3]; } //Invalid time format else if (type == 2) throw new IllegalArgumentException("Invalid time format!"); } else throw new IllegalArgumentException("Invalid parameter supplied: &7" + param); } //Sort out locations parseLocations(); }
public SearchParser(Player player, List<String> args) throws IllegalArgumentException { this.player = player; for (String arg : args) { //Check if argument has a valid prefix if (arg.equalsIgnoreCase("")) continue; String param = arg.substring(0,1).toLowerCase(); if (!arg.substring(1,2).equals(":")) throw new IllegalArgumentException("Invalid argument format: &7" + arg); String[] values = arg.substring(2).split(","); //Players if (param.equals("p")) players = values; //Worlds else if (param.equals("w")) worlds = values; //Filters else if (param.equals("f")) { if (filters != null) filters = Util.concat(filters, values); else filters = values; } //Blocks else if (param.equals("b")) { for (int i = 1; i < values.length; i++) { if (Material.getMaterial(values[i]) != null) values[i] = Integer.toString(Material.getMaterial(values[i]).getId()); } if (filters != null) filters = Util.concat(filters, values); else filters = values; } //Actions else if (param.equals("a")) { for (String value : values) { DataType type = DataType.fromName(value); if (type == null) throw new IllegalArgumentException("Invalid action supplied: &7" + value); if (!Permission.searchType(player, type.getConfigName())) throw new IllegalArgumentException("You do not have permission to search for: &7" + type.getConfigName()); actions.add(type); } } //Location else if (param.equals("l")) { if (values[0].equalsIgnoreCase("here")) loc = player.getLocation().toVector(); else { loc = new Vector(); loc.setX(Integer.parseInt(values[0])); loc.setY(Integer.parseInt(values[1])); loc.setZ(Integer.parseInt(values[2])); } } //Radius else if (param.equals("r")) { if (!Util.isInteger(values[0])) throw new IllegalArgumentException("Invalid radius supplied: &7" + values[0]); radius = Integer.parseInt(values[0]); } //Time else if (param.equals("t")) { int type = 2; for (int i = 0; i < arg.length(); i++) { String c = arg.substring(i, i+1); if (!Util.isInteger(c)) { if (c.equals("m") || c .equals("s") || c.equals("h") || c.equals("d") || c.equals("w")) type = 0; if (c.equals("-") || c.equals(":")) type = 1; } } //If the time is in the format '0w0d0h0m0s' if (type == 0) { int weeks = 0; int days = 0; int hours = 0; int mins = 0; int secs = 0; String nums = ""; for (int i = 0; i < values[0].length(); i++) { String c = values[0].substring(i, i+1); if (Util.isInteger(c)) { nums += c; continue; } int num = Integer.parseInt(nums); if (c.equals("w")) weeks = num; else if (c.equals("d")) days = num; else if (c.equals("h")) hours = num; else if (c.equals("m")) mins = num; else if (c.equals("s")) secs = num; else throw new IllegalArgumentException("Invalid time measurement: &7" + c); nums = ""; } Calendar cal = Calendar.getInstance(); cal.add(Calendar.WEEK_OF_YEAR, -1 * weeks); cal.add(Calendar.DAY_OF_MONTH, -1 * days); cal.add(Calendar.HOUR, -1 * hours); cal.add(Calendar.MINUTE, -1 * mins); cal.add(Calendar.SECOND, -1 * secs); SimpleDateFormat form = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); dateFrom = form.format(cal.getTime()); } //If the time is in the format 'yyyy-MM-dd HH:mm:ss' else if (type == 1) { if (values.length == 1) { SimpleDateFormat form = new SimpleDateFormat("yyyy-MM-dd"); dateFrom = form.format(Calendar.getInstance().getTime()) + " " + values[0]; } if (values.length >= 2) dateFrom = values[0] + " " + values[1]; if (values.length == 4) dateTo = values[2] + " " + values[3]; } //Invalid time format else if (type == 2) throw new IllegalArgumentException("Invalid time format!"); } else throw new IllegalArgumentException("Invalid parameter supplied: &7" + param); } //Sort out locations parseLocations(); }
diff --git a/gui/src/main/java/org/jboss/as/console/client/core/Footer.java b/gui/src/main/java/org/jboss/as/console/client/core/Footer.java index f478d4b0..32700075 100644 --- a/gui/src/main/java/org/jboss/as/console/client/core/Footer.java +++ b/gui/src/main/java/org/jboss/as/console/client/core/Footer.java @@ -1,78 +1,79 @@ /* * JBoss, Home of Professional Open Source * Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @author tags. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package org.jboss.as.console.client.core; import com.google.gwt.dom.client.Style; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.shared.EventBus; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.LayoutPanel; import com.google.gwt.user.client.ui.Widget; import com.google.inject.Inject; import com.gwtplatform.mvp.client.proxy.PlaceRequest; import org.jboss.as.console.client.Console; import org.jboss.as.console.client.auth.CurrentUser; /** * @author Heiko Braun * @date 1/28/11 */ public class Footer { private Label userName; @Inject public Footer(EventBus bus, CurrentUser user) { this.userName = new Label(); this.userName.setText(user.getUserName()); } public Widget asWidget() { LayoutPanel layout = new LayoutPanel(); layout.setStyleName("footer-panel"); HTML settings = new HTML(Console.CONSTANTS.common_label_settings()); settings.setStyleName("html-link"); + settings.getElement().setAttribute("style", "text-align:right; padding-right:10px"); settings.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { Console.MODULES.getPlaceManager().revealPlace( new PlaceRequest(NameTokens.SettingsPresenter) ); } }); layout.add(settings); HTML version = new HTML(org.jboss.as.console.client.Build.VERSION); version.getElement().setAttribute("style", "color:#ffffff;font-size:10px; align:left"); layout.add(version); layout.setWidgetLeftWidth(version, 20, Style.Unit.PX, 200, Style.Unit.PX); layout.setWidgetTopHeight(version, 3, Style.Unit.PX, 16, Style.Unit.PX); layout.setWidgetRightWidth(settings, 5, Style.Unit.PX, 100, Style.Unit.PX); layout.setWidgetTopHeight(settings, 2, Style.Unit.PX, 28, Style.Unit.PX); return layout; } }
true
true
public Widget asWidget() { LayoutPanel layout = new LayoutPanel(); layout.setStyleName("footer-panel"); HTML settings = new HTML(Console.CONSTANTS.common_label_settings()); settings.setStyleName("html-link"); settings.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { Console.MODULES.getPlaceManager().revealPlace( new PlaceRequest(NameTokens.SettingsPresenter) ); } }); layout.add(settings); HTML version = new HTML(org.jboss.as.console.client.Build.VERSION); version.getElement().setAttribute("style", "color:#ffffff;font-size:10px; align:left"); layout.add(version); layout.setWidgetLeftWidth(version, 20, Style.Unit.PX, 200, Style.Unit.PX); layout.setWidgetTopHeight(version, 3, Style.Unit.PX, 16, Style.Unit.PX); layout.setWidgetRightWidth(settings, 5, Style.Unit.PX, 100, Style.Unit.PX); layout.setWidgetTopHeight(settings, 2, Style.Unit.PX, 28, Style.Unit.PX); return layout; }
public Widget asWidget() { LayoutPanel layout = new LayoutPanel(); layout.setStyleName("footer-panel"); HTML settings = new HTML(Console.CONSTANTS.common_label_settings()); settings.setStyleName("html-link"); settings.getElement().setAttribute("style", "text-align:right; padding-right:10px"); settings.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { Console.MODULES.getPlaceManager().revealPlace( new PlaceRequest(NameTokens.SettingsPresenter) ); } }); layout.add(settings); HTML version = new HTML(org.jboss.as.console.client.Build.VERSION); version.getElement().setAttribute("style", "color:#ffffff;font-size:10px; align:left"); layout.add(version); layout.setWidgetLeftWidth(version, 20, Style.Unit.PX, 200, Style.Unit.PX); layout.setWidgetTopHeight(version, 3, Style.Unit.PX, 16, Style.Unit.PX); layout.setWidgetRightWidth(settings, 5, Style.Unit.PX, 100, Style.Unit.PX); layout.setWidgetTopHeight(settings, 2, Style.Unit.PX, 28, Style.Unit.PX); return layout; }
diff --git a/src/com/fortysix/seleniumTests/TestMain.java b/src/com/fortysix/seleniumTests/TestMain.java index ac2b69a..24580f6 100644 --- a/src/com/fortysix/seleniumTests/TestMain.java +++ b/src/com/fortysix/seleniumTests/TestMain.java @@ -1,25 +1,25 @@ package com.fortysix.seleniumTests; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import java.util.logging.Level; import java.util.logging.Logger; /** * Workday * User: johnwelsh * Date: 7/2/12 * Time: 8:44 PM */ public class TestMain { static Logger logger = Logger.getLogger("mainLogger"); public static void main(String[] args) { logger.log(Level.INFO, "Hello world!"); - logger.log(Level.INFO, "HI LINK"); + logger.log(Level.INFO, "HI THERE JOHN"); //WebDriver firefoxDriver = new FirefoxDriver(); //SeleniumExample example = new SeleniumExample(firefoxDriver); //example.testGoogleSearch(); } }
true
true
public static void main(String[] args) { logger.log(Level.INFO, "Hello world!"); logger.log(Level.INFO, "HI LINK"); //WebDriver firefoxDriver = new FirefoxDriver(); //SeleniumExample example = new SeleniumExample(firefoxDriver); //example.testGoogleSearch(); }
public static void main(String[] args) { logger.log(Level.INFO, "Hello world!"); logger.log(Level.INFO, "HI THERE JOHN"); //WebDriver firefoxDriver = new FirefoxDriver(); //SeleniumExample example = new SeleniumExample(firefoxDriver); //example.testGoogleSearch(); }
diff --git a/src/ca/dijital/geo/canvec/ExtractorWorker.java b/src/ca/dijital/geo/canvec/ExtractorWorker.java index 3aa11f2..a029691 100644 --- a/src/ca/dijital/geo/canvec/ExtractorWorker.java +++ b/src/ca/dijital/geo/canvec/ExtractorWorker.java @@ -1,160 +1,153 @@ package ca.dijital.geo.canvec; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Iterator; import java.util.Set; import java.util.zip.GZIPOutputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Performs the work of an ExtractorJob in a separate thread by invoking * the command-line utility. * * @author Rob Skelly <[email protected]> */ public class ExtractorWorker implements Runnable { private static Logger logger = LoggerFactory.getLogger(ExtractorWorker.class); private Thread thread; private ExtractorJob job; private boolean running; private boolean busy; /** * Starts the worker with the given job. If the worker is in use, an exception is thrown. * @param job */ public void start(final ExtractorJob job) throws Exception { if(!running){ busy = true; running = true; this.job = job; this.thread = new Thread(this); this.thread.start(); }else{ throw new Exception("This worker is not free."); } } /** * Stops the worker. */ public void stop(){ if(running){ running = false; try { thread.join(); } catch (InterruptedException e) { logger.error("Error stopping worker.", e); }finally{ job = null; busy = false; } } } /** * Returns true if the worker is running. * @return */ public boolean isBusy(){ return busy; } @Override public void run() { while(running){ Set<File> shapeFiles = job.getShapeFiles(); Iterator<File> files = shapeFiles.iterator(); boolean compress = job.isCompress(); // Create output file. String fileName = job.getOutFile(); if(compress) fileName += ".gz"; File outFile = new File(fileName); OutputStream out = null; try{ // Create a file output, and GZIP it if necessary. out = new BufferedOutputStream(new FileOutputStream(outFile)); // If compression is desired, wrap the output in a gzip stream. if(compress) out = new GZIPOutputStream(out); }catch(IOException e){ logger.error("Failed to open output file {} in job {}.", job.getOutFile(), job.getName(), e); break; } int i=0; int end = shapeFiles.size() - 1; while(files.hasNext()){ File file = files.next(); if(file.getName().toLowerCase().endsWith("shp")){ logger.info("Processing file {}.", file.getName()); // Build shp2pgsql command. StringBuffer command = new StringBuffer("shp2pgsql "); if(i == 0){ command.append("-a "); }else{ command.append("-d "); } if(i == end) command.append("-I "); command.append(file.getAbsolutePath()).append(" "); command.append(job.getSchemaName()).append(".").append(job.getTableName()); try { // Start a process for the command and get the input stream. Process proc = Runtime.getRuntime().exec(command.toString()); InputStream in = proc.getInputStream(); // Write the shp2pgsql output to the output stream. byte[] buf = new byte[1024]; int read = 0; - int accum = 0; - int maxAccum = 1024 * 1024; - while((read = in.read(buf)) > -1){ + while((read = in.read(buf)) > -1) out.write(buf, 0, read); - // If we've accumulated more than 1M of data, flush it. - accum += read; - if(accum > maxAccum) - out.flush(); - } // If gzipping, finish the archive. if(compress) ((GZIPOutputStream) out).finish(); in.close(); // Wait for the process to finish, and report any problems. int retval = proc.waitFor(); if(retval != 0) logger.warn("Return value from shp2pgsql was {}.", retval); logger.info("File complete", file.getName()); } catch (IOException e){ logger.error("Failed while processing job {}.", job.getName(), e); } catch(InterruptedException e) { logger.error("Failed while processing job {}.", job.getName(), e); } ++i; } } try{ // Close the streams. out.close(); }catch(IOException e){ logger.error("Failed to close outputstream in job {}.", job.getName()); } running = false; busy = false; } } }
false
true
public void run() { while(running){ Set<File> shapeFiles = job.getShapeFiles(); Iterator<File> files = shapeFiles.iterator(); boolean compress = job.isCompress(); // Create output file. String fileName = job.getOutFile(); if(compress) fileName += ".gz"; File outFile = new File(fileName); OutputStream out = null; try{ // Create a file output, and GZIP it if necessary. out = new BufferedOutputStream(new FileOutputStream(outFile)); // If compression is desired, wrap the output in a gzip stream. if(compress) out = new GZIPOutputStream(out); }catch(IOException e){ logger.error("Failed to open output file {} in job {}.", job.getOutFile(), job.getName(), e); break; } int i=0; int end = shapeFiles.size() - 1; while(files.hasNext()){ File file = files.next(); if(file.getName().toLowerCase().endsWith("shp")){ logger.info("Processing file {}.", file.getName()); // Build shp2pgsql command. StringBuffer command = new StringBuffer("shp2pgsql "); if(i == 0){ command.append("-a "); }else{ command.append("-d "); } if(i == end) command.append("-I "); command.append(file.getAbsolutePath()).append(" "); command.append(job.getSchemaName()).append(".").append(job.getTableName()); try { // Start a process for the command and get the input stream. Process proc = Runtime.getRuntime().exec(command.toString()); InputStream in = proc.getInputStream(); // Write the shp2pgsql output to the output stream. byte[] buf = new byte[1024]; int read = 0; int accum = 0; int maxAccum = 1024 * 1024; while((read = in.read(buf)) > -1){ out.write(buf, 0, read); // If we've accumulated more than 1M of data, flush it. accum += read; if(accum > maxAccum) out.flush(); } // If gzipping, finish the archive. if(compress) ((GZIPOutputStream) out).finish(); in.close(); // Wait for the process to finish, and report any problems. int retval = proc.waitFor(); if(retval != 0) logger.warn("Return value from shp2pgsql was {}.", retval); logger.info("File complete", file.getName()); } catch (IOException e){ logger.error("Failed while processing job {}.", job.getName(), e); } catch(InterruptedException e) { logger.error("Failed while processing job {}.", job.getName(), e); } ++i; } } try{ // Close the streams. out.close(); }catch(IOException e){ logger.error("Failed to close outputstream in job {}.", job.getName()); } running = false; busy = false; } }
public void run() { while(running){ Set<File> shapeFiles = job.getShapeFiles(); Iterator<File> files = shapeFiles.iterator(); boolean compress = job.isCompress(); // Create output file. String fileName = job.getOutFile(); if(compress) fileName += ".gz"; File outFile = new File(fileName); OutputStream out = null; try{ // Create a file output, and GZIP it if necessary. out = new BufferedOutputStream(new FileOutputStream(outFile)); // If compression is desired, wrap the output in a gzip stream. if(compress) out = new GZIPOutputStream(out); }catch(IOException e){ logger.error("Failed to open output file {} in job {}.", job.getOutFile(), job.getName(), e); break; } int i=0; int end = shapeFiles.size() - 1; while(files.hasNext()){ File file = files.next(); if(file.getName().toLowerCase().endsWith("shp")){ logger.info("Processing file {}.", file.getName()); // Build shp2pgsql command. StringBuffer command = new StringBuffer("shp2pgsql "); if(i == 0){ command.append("-a "); }else{ command.append("-d "); } if(i == end) command.append("-I "); command.append(file.getAbsolutePath()).append(" "); command.append(job.getSchemaName()).append(".").append(job.getTableName()); try { // Start a process for the command and get the input stream. Process proc = Runtime.getRuntime().exec(command.toString()); InputStream in = proc.getInputStream(); // Write the shp2pgsql output to the output stream. byte[] buf = new byte[1024]; int read = 0; while((read = in.read(buf)) > -1) out.write(buf, 0, read); // If gzipping, finish the archive. if(compress) ((GZIPOutputStream) out).finish(); in.close(); // Wait for the process to finish, and report any problems. int retval = proc.waitFor(); if(retval != 0) logger.warn("Return value from shp2pgsql was {}.", retval); logger.info("File complete", file.getName()); } catch (IOException e){ logger.error("Failed while processing job {}.", job.getName(), e); } catch(InterruptedException e) { logger.error("Failed while processing job {}.", job.getName(), e); } ++i; } } try{ // Close the streams. out.close(); }catch(IOException e){ logger.error("Failed to close outputstream in job {}.", job.getName()); } running = false; busy = false; } }
diff --git a/site-manage-tool/tool/src/java/org/sakaiproject/site/tool/SiteAction.java b/site-manage-tool/tool/src/java/org/sakaiproject/site/tool/SiteAction.java index 6a5419b6..3fdc0a48 100644 --- a/site-manage-tool/tool/src/java/org/sakaiproject/site/tool/SiteAction.java +++ b/site-manage-tool/tool/src/java/org/sakaiproject/site/tool/SiteAction.java @@ -1,12375 +1,12376 @@ /********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * * Copyright (c) 2003, 2004, 2005, 2006 The Sakai Foundation. * * Licensed under the Educational Community License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ package org.sakaiproject.site.tool; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.text.Collator; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.Random; import java.util.Set; import java.util.Vector; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.velocity.tools.generic.SortTool; import org.sakaiproject.alias.api.Alias; import org.sakaiproject.alias.cover.AliasService; import org.sakaiproject.archive.api.ImportMetadata; import org.sakaiproject.archive.cover.ArchiveService; import org.sakaiproject.authz.api.AuthzGroup; import org.sakaiproject.authz.api.AuthzPermissionException; import org.sakaiproject.authz.api.GroupNotDefinedException; import org.sakaiproject.authz.api.Member; import org.sakaiproject.authz.api.PermissionsHelper; import org.sakaiproject.authz.api.Role; import org.sakaiproject.authz.cover.AuthzGroupService; import org.sakaiproject.authz.cover.SecurityService; import org.sakaiproject.cheftool.Context; import org.sakaiproject.cheftool.JetspeedRunData; import org.sakaiproject.cheftool.PagedResourceActionII; import org.sakaiproject.cheftool.PortletConfig; import org.sakaiproject.cheftool.RunData; import org.sakaiproject.cheftool.VelocityPortlet; import org.sakaiproject.cheftool.api.Menu; import org.sakaiproject.cheftool.api.MenuItem; import org.sakaiproject.cheftool.menu.MenuEntry; import org.sakaiproject.cheftool.menu.MenuImpl; import org.sakaiproject.component.cover.ComponentManager; import org.sakaiproject.component.cover.ServerConfigurationService; import org.sakaiproject.content.cover.ContentHostingService; import org.sakaiproject.coursemanagement.api.AcademicSession; import org.sakaiproject.coursemanagement.api.CourseOffering; import org.sakaiproject.coursemanagement.api.Enrollment; import org.sakaiproject.coursemanagement.api.EnrollmentSet; import org.sakaiproject.coursemanagement.api.Membership; import org.sakaiproject.coursemanagement.api.Section; import org.sakaiproject.coursemanagement.api.exception.IdNotFoundException; import org.sakaiproject.email.cover.EmailService; import org.sakaiproject.entity.api.Entity; import org.sakaiproject.entity.api.EntityProducer; import org.sakaiproject.entity.api.EntityPropertyNotDefinedException; import org.sakaiproject.entity.api.EntityPropertyTypeException; import org.sakaiproject.entity.api.EntityTransferrer; import org.sakaiproject.entity.api.ResourceProperties; import org.sakaiproject.entity.api.ResourcePropertiesEdit; import org.sakaiproject.entity.cover.EntityManager; import org.sakaiproject.event.api.SessionState; import org.sakaiproject.event.cover.EventTrackingService; import org.sakaiproject.exception.IdInvalidException; import org.sakaiproject.exception.IdUnusedException; import org.sakaiproject.exception.IdUsedException; import org.sakaiproject.exception.ImportException; import org.sakaiproject.exception.PermissionException; import org.sakaiproject.id.cover.IdManager; import org.sakaiproject.importer.api.ImportDataSource; import org.sakaiproject.importer.api.ImportService; import org.sakaiproject.importer.api.SakaiArchive; import org.sakaiproject.javax.PagingPosition; import org.sakaiproject.site.api.Group; import org.sakaiproject.site.api.Site; import org.sakaiproject.site.api.SitePage; import org.sakaiproject.site.api.ToolConfiguration; import org.sakaiproject.site.api.SiteService.SortType; import org.sakaiproject.site.cover.SiteService; import org.sakaiproject.sitemanage.api.SectionField; import org.sakaiproject.time.api.Time; import org.sakaiproject.time.api.TimeBreakdown; import org.sakaiproject.time.cover.TimeService; import org.sakaiproject.tool.api.Tool; import org.sakaiproject.tool.cover.SessionManager; import org.sakaiproject.tool.cover.ToolManager; import org.sakaiproject.user.api.User; import org.sakaiproject.user.api.UserAlreadyDefinedException; import org.sakaiproject.user.api.UserEdit; import org.sakaiproject.user.api.UserIdInvalidException; import org.sakaiproject.user.api.UserNotDefinedException; import org.sakaiproject.user.api.UserPermissionException; import org.sakaiproject.user.cover.UserDirectoryService; import org.sakaiproject.util.ArrayUtil; import org.sakaiproject.util.FileItem; import org.sakaiproject.util.ParameterParser; import org.sakaiproject.util.ResourceLoader; import org.sakaiproject.util.SortedIterator; import org.sakaiproject.util.StringUtil; import org.sakaiproject.util.Validator; /** * <p> * SiteAction controls the interface for worksite setup. * </p> */ public class SiteAction extends PagedResourceActionII { /** Our logger. */ private static Log M_log = LogFactory.getLog(SiteAction.class); private ImportService importService = org.sakaiproject.importer.cover.ImportService .getInstance(); /** portlet configuration parameter values* */ /** Resource bundle using current language locale */ private static ResourceLoader rb = new ResourceLoader("sitesetupgeneric"); private org.sakaiproject.coursemanagement.api.CourseManagementService cms = (org.sakaiproject.coursemanagement.api.CourseManagementService) ComponentManager .get(org.sakaiproject.coursemanagement.api.CourseManagementService.class); private org.sakaiproject.authz.api.GroupProvider groupProvider = (org.sakaiproject.authz.api.GroupProvider) ComponentManager .get(org.sakaiproject.authz.api.GroupProvider.class); private org.sakaiproject.authz.api.AuthzGroupService authzGroupService = (org.sakaiproject.authz.api.AuthzGroupService) ComponentManager .get(org.sakaiproject.authz.api.AuthzGroupService.class); private org.sakaiproject.sitemanage.api.SectionFieldProvider sectionFieldProvider = (org.sakaiproject.sitemanage.api.SectionFieldProvider) ComponentManager .get(org.sakaiproject.sitemanage.api.SectionFieldProvider.class); private org.sakaiproject.sitemanage.api.AffiliatedSectionProvider affiliatedSectionProvider = (org.sakaiproject.sitemanage.api.AffiliatedSectionProvider) ComponentManager .get(org.sakaiproject.sitemanage.api.AffiliatedSectionProvider.class); private static final String SITE_MODE_SITESETUP = "sitesetup"; private static final String SITE_MODE_SITEINFO = "siteinfo"; private static final String STATE_SITE_MODE = "site_mode"; protected final static String[] TEMPLATE = { "-list",// 0 "-type", "-newSiteInformation", "-newSiteFeatures", "-addRemoveFeature", "-addParticipant", "-removeParticipants", "-changeRoles", "-siteDeleteConfirm", "-publishUnpublish", "-newSiteConfirm",// 10 "-newSitePublishUnpublish", "-siteInfo-list",// 12 "-siteInfo-editInfo", "-siteInfo-editInfoConfirm", "-addRemoveFeatureConfirm",// 15 "-publishUnpublish-sendEmail", "-publishUnpublish-confirm", "-siteInfo-editAccess", "-addParticipant-sameRole", "-addParticipant-differentRole",// 20 "-addParticipant-notification", "-addParticipant-confirm", "-siteInfo-editAccess-globalAccess", "-siteInfo-editAccess-globalAccess-confirm", "-changeRoles-confirm",// 25 "-modifyENW", "-importSites", "-siteInfo-import", "-siteInfo-duplicate", "",// 30 "",// 31 "",// 32 "",// 33 "",// 34 "",// 35 "-newSiteCourse",// 36 "-newSiteCourseManual",// 37 "",// 38 "",// 39 "",// 40 "",// 41 "-gradtoolsConfirm",// 42 "-siteInfo-editClass",// 43 "-siteInfo-addCourseConfirm",// 44 "-siteInfo-importMtrlMaster", // 45 -- htripath for import // material from a file "-siteInfo-importMtrlCopy", // 46 "-siteInfo-importMtrlCopyConfirm", "-siteInfo-importMtrlCopyConfirmMsg", // 48 "-siteInfo-group", // 49 "-siteInfo-groupedit", // 50 "-siteInfo-groupDeleteConfirm", // 51, "", "-findCourse" // 53 }; /** Name of state attribute for Site instance id */ private static final String STATE_SITE_INSTANCE_ID = "site.instance.id"; /** Name of state attribute for Site Information */ private static final String STATE_SITE_INFO = "site.info"; /** Name of state attribute for CHEF site type */ private static final String STATE_SITE_TYPE = "site-type"; /** Name of state attribute for poissible site types */ private static final String STATE_SITE_TYPES = "site_types"; private static final String STATE_DEFAULT_SITE_TYPE = "default_site_type"; private static final String STATE_PUBLIC_CHANGEABLE_SITE_TYPES = "changeable_site_types"; private static final String STATE_PUBLIC_SITE_TYPES = "public_site_types"; private static final String STATE_PRIVATE_SITE_TYPES = "private_site_types"; private static final String STATE_DISABLE_JOINABLE_SITE_TYPE = "disable_joinable_site_types"; // Names of state attributes corresponding to properties of a site private final static String PROP_SITE_CONTACT_EMAIL = "contact-email"; private final static String PROP_SITE_CONTACT_NAME = "contact-name"; private final static String PROP_SITE_TERM = "term"; private final static String PROP_SITE_TERM_EID = "term_eid"; /** * Name of the state attribute holding the site list column list is sorted * by */ private static final String SORTED_BY = "site.sorted.by"; /** the list of criteria for sorting */ private static final String SORTED_BY_TITLE = "title"; private static final String SORTED_BY_DESCRIPTION = "description"; private static final String SORTED_BY_TYPE = "type"; private static final String SORTED_BY_STATUS = "status"; private static final String SORTED_BY_CREATION_DATE = "creationdate"; private static final String SORTED_BY_JOINABLE = "joinable"; private static final String SORTED_BY_PARTICIPANT_NAME = "participant_name"; private static final String SORTED_BY_PARTICIPANT_UNIQNAME = "participant_uniqname"; private static final String SORTED_BY_PARTICIPANT_ROLE = "participant_role"; private static final String SORTED_BY_PARTICIPANT_ID = "participant_id"; private static final String SORTED_BY_PARTICIPANT_COURSE = "participant_course"; private static final String SORTED_BY_PARTICIPANT_CREDITS = "participant_credits"; private static final String SORTED_BY_MEMBER_NAME = "member_name"; /** Name of the state attribute holding the site list column to sort by */ private static final String SORTED_ASC = "site.sort.asc"; /** State attribute for list of sites to be deleted. */ private static final String STATE_SITE_REMOVALS = "site.removals"; /** Name of the state attribute holding the site list View selected */ private static final String STATE_VIEW_SELECTED = "site.view.selected"; /** Names of lists related to tools */ private static final String STATE_TOOL_REGISTRATION_LIST = "toolRegistrationList"; private static final String STATE_TOOL_REGISTRATION_SELECTED_LIST = "toolRegistrationSelectedList"; private static final String STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST = "toolRegistrationOldSelectedList"; private static final String STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME = "toolRegistrationOldSelectedHome"; private static final String STATE_TOOL_EMAIL_ADDRESS = "toolEmailAddress"; private static final String STATE_TOOL_HOME_SELECTED = "toolHomeSelected"; private static final String STATE_PROJECT_TOOL_LIST = "projectToolList"; private final static String STATE_NEWS_TITLES = "newstitles"; private final static String STATE_NEWS_URLS = "newsurls"; private final static String NEWS_DEFAULT_TITLE = ServerConfigurationService .getString("news.title"); private final static String NEWS_DEFAULT_URL = ServerConfigurationService .getString("news.feedURL"); private final static String SITE_DEFAULT_LIST = ServerConfigurationService .getString("site.types"); private final static String STATE_WEB_CONTENT_TITLES = "webcontenttitles"; private final static String STATE_WEB_CONTENT_URLS = "wcUrls"; private final static String WEB_CONTENT_DEFAULT_TITLE = "Web Content"; private final static String WEB_CONTENT_DEFAULT_URL = "http://"; private final static String STATE_SITE_QUEST_UNIQNAME = "site_quest_uniqname"; // %%% get rid of the IdAndText tool lists and just use ToolConfiguration or // ToolRegistration lists // %%% same for CourseItems // Names for other state attributes that are lists private final static String STATE_WORKSITE_SETUP_PAGE_LIST = "wSetupPageList"; // the // list // of // site // pages // consistent // with // Worksite // Setup // page // patterns /** * The name of the state form field containing additional information for a * course request */ private static final String FORM_ADDITIONAL = "form.additional"; /** %%% in transition from putting all form variables in state */ private final static String FORM_TITLE = "form_title"; private final static String FORM_DESCRIPTION = "form_description"; private final static String FORM_HONORIFIC = "form_honorific"; private final static String FORM_INSTITUTION = "form_institution"; private final static String FORM_SUBJECT = "form_subject"; private final static String FORM_PHONE = "form_phone"; private final static String FORM_EMAIL = "form_email"; private final static String FORM_REUSE = "form_reuse"; private final static String FORM_RELATED_CLASS = "form_related_class"; private final static String FORM_RELATED_PROJECT = "form_related_project"; private final static String FORM_NAME = "form_name"; private final static String FORM_SHORT_DESCRIPTION = "form_short_description"; private final static String FORM_ICON_URL = "iconUrl"; /** site info edit form variables */ private final static String FORM_SITEINFO_TITLE = "siteinfo_title"; private final static String FORM_SITEINFO_TERM = "siteinfo_term"; private final static String FORM_SITEINFO_DESCRIPTION = "siteinfo_description"; private final static String FORM_SITEINFO_SHORT_DESCRIPTION = "siteinfo_short_description"; private final static String FORM_SITEINFO_SKIN = "siteinfo_skin"; private final static String FORM_SITEINFO_INCLUDE = "siteinfo_include"; private final static String FORM_SITEINFO_ICON_URL = "siteinfo_icon_url"; private final static String FORM_SITEINFO_CONTACT_NAME = "siteinfo_contact_name"; private final static String FORM_SITEINFO_CONTACT_EMAIL = "siteinfo_contact_email"; private final static String FORM_WILL_NOTIFY = "form_will_notify"; /** Context action */ private static final String CONTEXT_ACTION = "SiteAction"; /** The name of the Attribute for display template index */ private static final String STATE_TEMPLATE_INDEX = "site.templateIndex"; /** State attribute for state initialization. */ private static final String STATE_INITIALIZED = "site.initialized"; /** The action for menu */ private static final String STATE_ACTION = "site.action"; /** The user copyright string */ private static final String STATE_MY_COPYRIGHT = "resources.mycopyright"; /** The copyright character */ private static final String COPYRIGHT_SYMBOL = "copyright (c)"; /** The null/empty string */ private static final String NULL_STRING = ""; /** The state attribute alerting user of a sent course request */ private static final String REQUEST_SENT = "site.request.sent"; /** The state attributes in the make public vm */ private static final String STATE_JOINABLE = "state_joinable"; private static final String STATE_JOINERROLE = "state_joinerRole"; /** the list of selected user */ private static final String STATE_SELECTED_USER_LIST = "state_selected_user_list"; private static final String STATE_SELECTED_PARTICIPANT_ROLES = "state_selected_participant_roles"; private static final String STATE_SELECTED_PARTICIPANTS = "state_selected_participants"; private static final String STATE_PARTICIPANT_LIST = "state_participant_list"; private static final String STATE_ADD_PARTICIPANTS = "state_add_participants"; /** for changing participant roles */ private static final String STATE_CHANGEROLE_SAMEROLE = "state_changerole_samerole"; private static final String STATE_CHANGEROLE_SAMEROLE_ROLE = "state_changerole_samerole_role"; /** for remove user */ private static final String STATE_REMOVEABLE_USER_LIST = "state_removeable_user_list"; private static final String STATE_IMPORT = "state_import"; private static final String STATE_IMPORT_SITES = "state_import_sites"; private static final String STATE_IMPORT_SITE_TOOL = "state_import_site_tool"; /** for navigating between sites in site list */ private static final String STATE_SITES = "state_sites"; private static final String STATE_PREV_SITE = "state_prev_site"; private static final String STATE_NEXT_SITE = "state_next_site"; /** for course information */ private final static String STATE_TERM_COURSE_LIST = "state_term_course_list"; private final static String STATE_TERM_COURSE_HASH = "state_term_course_hash"; private final static String STATE_TERM_SELECTED = "state_term_selected"; private final static String STATE_INSTRUCTOR_SELECTED = "state_instructor_selected"; private final static String STATE_FUTURE_TERM_SELECTED = "state_future_term_selected"; private final static String STATE_ADD_CLASS_PROVIDER = "state_add_class_provider"; private final static String STATE_ADD_CLASS_PROVIDER_CHOSEN = "state_add_class_provider_chosen"; private final static String STATE_ADD_CLASS_MANUAL = "state_add_class_manual"; private final static String STATE_AUTO_ADD = "state_auto_add"; private final static String STATE_MANUAL_ADD_COURSE_NUMBER = "state_manual_add_course_number"; private final static String STATE_MANUAL_ADD_COURSE_FIELDS = "state_manual_add_course_fields"; public final static String PROP_SITE_REQUEST_COURSE = "site-request-course-sections"; public final static String SITE_PROVIDER_COURSE_LIST = "site_provider_course_list"; public final static String SITE_MANUAL_COURSE_LIST = "site_manual_course_list"; private final static String STATE_SUBJECT_AFFILIATES = "site.subject.affiliates"; private final static String STATE_ICONS = "icons"; // site template used to create a UM Grad Tools student site public static final String SITE_GTS_TEMPLATE = "!gtstudent"; // the type used to identify a UM Grad Tools student site public static final String SITE_TYPE_GRADTOOLS_STUDENT = "GradToolsStudent"; // list of UM Grad Tools site types for editing public static final String GRADTOOLS_SITE_TYPES = "gradtools_site_types"; public static final String SITE_DUPLICATED = "site_duplicated"; public static final String SITE_DUPLICATED_NAME = "site_duplicated_named"; // used for site creation wizard title public static final String SITE_CREATE_TOTAL_STEPS = "site_create_total_steps"; public static final String SITE_CREATE_CURRENT_STEP = "site_create_current_step"; // types of site where site view roster permission is editable public static final String EDIT_VIEW_ROSTER_SITE_TYPE = "edit_view_roster_site_type"; // htripath : for import material from file - classic import private static final String ALL_ZIP_IMPORT_SITES = "allzipImports"; private static final String FINAL_ZIP_IMPORT_SITES = "finalzipImports"; private static final String DIRECT_ZIP_IMPORT_SITES = "directzipImports"; private static final String CLASSIC_ZIP_FILE_NAME = "classicZipFileName"; private static final String SESSION_CONTEXT_ID = "sessionContextId"; // page size for worksite setup tool private static final String STATE_PAGESIZE_SITESETUP = "state_pagesize_sitesetup"; // page size for site info tool private static final String STATE_PAGESIZE_SITEINFO = "state_pagesize_siteinfo"; // group info private static final String STATE_GROUP_INSTANCE_ID = "state_group_instance_id"; private static final String STATE_GROUP_TITLE = "state_group_title"; private static final String STATE_GROUP_DESCRIPTION = "state_group_description"; private static final String STATE_GROUP_MEMBERS = "state_group_members"; private static final String STATE_GROUP_REMOVE = "state_group_remove"; private static final String GROUP_PROP_WSETUP_CREATED = "group_prop_wsetup_created"; private static final String IMPORT_DATA_SOURCE = "import_data_source"; private static final String EMAIL_CHAR = "@"; // Special tool id for Home page private static final String HOME_TOOL_ID = "home"; private static final String STATE_CM_LEVELS = "site.cm.levels"; private static final String STATE_CM_LEVEL_SELECTIONS = "site.cm.level.selections"; private static final String STATE_CM_SELECTED_SECTION = "site.cm.selectedSection"; private static final String STATE_CM_REQUESTED_SECTIONS = "site.cm.requested"; private static final String STATE_CM_SELECTED_SECTIONS = "site.cm.selectedSections"; private static final String STATE_PROVIDER_SECTION_LIST = "site_provider_section_list"; private static final String STATE_CM_CURRENT_USERID = "site_cm_current_userId"; private static final String STATE_CM_AUTHORIZER_LIST = "site_cm_authorizer_list"; private static final String STATE_CM_AUTHORIZER_SECTIONS = "site_cm_authorizer_sections"; private String cmSubjectCategory; private boolean warnedNoSubjectCategory = false; // the string marks the protocol part in url private static final String PROTOCOL_STRING = "://"; private static final String TOOL_ID_SUMMARY_CALENDAR = "sakai.summary.calendar"; // the string for course site type private static final String STATE_COURSE_SITE_TYPE = "state_course_site_type"; /** * Populate the state object, if needed. */ protected void initState(SessionState state, VelocityPortlet portlet, JetspeedRunData rundata) { super.initState(state, portlet, rundata); // store current userId in state User user = UserDirectoryService.getCurrentUser(); String userId = user.getEid(); state.setAttribute(STATE_CM_CURRENT_USERID, userId); PortletConfig config = portlet.getPortletConfig(); // types of sites that can either be public or private String changeableTypes = StringUtil.trimToNull(config .getInitParameter("publicChangeableSiteTypes")); if (state.getAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES) == null) { if (changeableTypes != null) { state .setAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES, new ArrayList(Arrays.asList(changeableTypes .split(",")))); } else { state.setAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES, new Vector()); } } // type of sites that are always public String publicTypes = StringUtil.trimToNull(config .getInitParameter("publicSiteTypes")); if (state.getAttribute(STATE_PUBLIC_SITE_TYPES) == null) { if (publicTypes != null) { state.setAttribute(STATE_PUBLIC_SITE_TYPES, new ArrayList( Arrays.asList(publicTypes.split(",")))); } else { state.setAttribute(STATE_PUBLIC_SITE_TYPES, new Vector()); } } // types of sites that are always private String privateTypes = StringUtil.trimToNull(config .getInitParameter("privateSiteTypes")); if (state.getAttribute(STATE_PRIVATE_SITE_TYPES) == null) { if (privateTypes != null) { state.setAttribute(STATE_PRIVATE_SITE_TYPES, new ArrayList( Arrays.asList(privateTypes.split(",")))); } else { state.setAttribute(STATE_PRIVATE_SITE_TYPES, new Vector()); } } // default site type String defaultType = StringUtil.trimToNull(config .getInitParameter("defaultSiteType")); if (state.getAttribute(STATE_DEFAULT_SITE_TYPE) == null) { if (defaultType != null) { state.setAttribute(STATE_DEFAULT_SITE_TYPE, defaultType); } else { state.setAttribute(STATE_PRIVATE_SITE_TYPES, new Vector()); } } // certain type(s) of site cannot get its "joinable" option set if (state.getAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE) == null) { if (ServerConfigurationService .getStrings("wsetup.disable.joinable") != null) { state.setAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE, new ArrayList(Arrays.asList(ServerConfigurationService .getStrings("wsetup.disable.joinable")))); } else { state.setAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE, new Vector()); } } // course site type if (state.getAttribute(STATE_COURSE_SITE_TYPE) == null) { state.setAttribute(STATE_COURSE_SITE_TYPE, ServerConfigurationService.getString("courseSiteType", "course")); } if (state.getAttribute(STATE_TOP_PAGE_MESSAGE) == null) { state.setAttribute(STATE_TOP_PAGE_MESSAGE, new Integer(0)); } // skins if any if (state.getAttribute(STATE_ICONS) == null) { setupIcons(state); } if (state.getAttribute(GRADTOOLS_SITE_TYPES) == null) { List gradToolsSiteTypes = new Vector(); if (ServerConfigurationService.getStrings("gradToolsSiteType") != null) { gradToolsSiteTypes = new ArrayList(Arrays .asList(ServerConfigurationService .getStrings("gradToolsSiteType"))); } state.setAttribute(GRADTOOLS_SITE_TYPES, gradToolsSiteTypes); } if (state.getAttribute(EDIT_VIEW_ROSTER_SITE_TYPE) == null) { List siteTypes = new Vector(); if (ServerConfigurationService.getStrings("editViewRosterSiteType") != null) { siteTypes = new ArrayList(Arrays .asList(ServerConfigurationService .getStrings("editViewRosterSiteType"))); } state.setAttribute(EDIT_VIEW_ROSTER_SITE_TYPE, siteTypes); } // get site tool mode from tool registry String site_mode = portlet.getPortletConfig().getInitParameter( STATE_SITE_MODE); state.setAttribute(STATE_SITE_MODE, site_mode); } // initState /** * cleanState removes the current site instance and it's properties from * state */ private void cleanState(SessionState state) { state.removeAttribute(STATE_SITE_INSTANCE_ID); state.removeAttribute(STATE_SITE_INFO); state.removeAttribute(STATE_SITE_TYPE); state.removeAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST); state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME); state.removeAttribute(STATE_TOOL_EMAIL_ADDRESS); state.removeAttribute(STATE_TOOL_HOME_SELECTED); state.removeAttribute(STATE_SELECTED_USER_LIST); state.removeAttribute(STATE_JOINABLE); state.removeAttribute(STATE_JOINERROLE); state.removeAttribute(STATE_NEWS_TITLES); state.removeAttribute(STATE_NEWS_URLS); state.removeAttribute(STATE_WEB_CONTENT_TITLES); state.removeAttribute(STATE_WEB_CONTENT_URLS); state.removeAttribute(STATE_SITE_QUEST_UNIQNAME); state.removeAttribute(STATE_IMPORT); state.removeAttribute(STATE_IMPORT_SITES); state.removeAttribute(STATE_IMPORT_SITE_TOOL); // remove those state attributes related to course site creation state.removeAttribute(STATE_TERM_COURSE_LIST); state.removeAttribute(STATE_TERM_COURSE_HASH); state.removeAttribute(STATE_TERM_SELECTED); state.removeAttribute(STATE_INSTRUCTOR_SELECTED); state.removeAttribute(STATE_FUTURE_TERM_SELECTED); state.removeAttribute(STATE_ADD_CLASS_PROVIDER); state.removeAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN); state.removeAttribute(STATE_ADD_CLASS_MANUAL); state.removeAttribute(STATE_AUTO_ADD); state.removeAttribute(STATE_MANUAL_ADD_COURSE_NUMBER); state.removeAttribute(STATE_MANUAL_ADD_COURSE_FIELDS); state.removeAttribute(SITE_CREATE_TOTAL_STEPS); state.removeAttribute(SITE_CREATE_CURRENT_STEP); state.removeAttribute(STATE_PROVIDER_SECTION_LIST); state.removeAttribute(STATE_CM_LEVELS); state.removeAttribute(STATE_CM_LEVEL_SELECTIONS); state.removeAttribute(STATE_CM_SELECTED_SECTION); state.removeAttribute(STATE_CM_REQUESTED_SECTIONS); state.removeAttribute(STATE_CM_CURRENT_USERID); state.removeAttribute(STATE_CM_AUTHORIZER_LIST); state.removeAttribute(STATE_CM_AUTHORIZER_SECTIONS); state.removeAttribute(FORM_ADDITIONAL); // don't we need to clena this // too? -daisyf } // cleanState /** * Fire up the permissions editor */ public void doPermissions(RunData data, Context context) { // get into helper mode with this helper tool startHelper(data.getRequest(), "sakai.permissions.helper"); SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); String contextString = ToolManager.getCurrentPlacement().getContext(); String siteRef = SiteService.siteReference(contextString); // if it is in Worksite setup tool, pass the selected site's reference if (state.getAttribute(STATE_SITE_MODE) != null && ((String) state.getAttribute(STATE_SITE_MODE)) .equals(SITE_MODE_SITESETUP)) { if (state.getAttribute(STATE_SITE_INSTANCE_ID) != null) { Site s = getStateSite(state); if (s != null) { siteRef = s.getReference(); } } } // setup for editing the permissions of the site for this tool, using // the roles of this site, too state.setAttribute(PermissionsHelper.TARGET_REF, siteRef); // ... with this description state.setAttribute(PermissionsHelper.DESCRIPTION, rb .getString("setperfor") + " " + SiteService.getSiteDisplay(contextString)); // ... showing only locks that are prpefixed with this state.setAttribute(PermissionsHelper.PREFIX, "site."); } // doPermissions /** * Build the context for normal display */ public String buildMainPanelContext(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("tlang", rb); // TODO: what is all this doing? if we are in helper mode, we are // already setup and don't get called here now -ggolden /* * String helperMode = (String) * state.getAttribute(PermissionsAction.STATE_MODE); if (helperMode != * null) { Site site = getStateSite(state); if (site != null) { if * (site.getType() != null && ((List) * state.getAttribute(EDIT_VIEW_ROSTER_SITE_TYPE)).contains(site.getType())) { * context.put("editViewRoster", Boolean.TRUE); } else { * context.put("editViewRoster", Boolean.FALSE); } } else { * context.put("editViewRoster", Boolean.FALSE); } // for new, don't * show site.del in Permission page context.put("hiddenLock", * "site.del"); * * String template = PermissionsAction.buildHelperContext(portlet, * context, data, state); if (template == null) { addAlert(state, * rb.getString("theisa")); } else { return template; } } */ String template = null; context.put("action", CONTEXT_ACTION); // updatePortlet(state, portlet, data); if (state.getAttribute(STATE_INITIALIZED) == null) { init(portlet, data, state); } int index = Integer.valueOf( (String) state.getAttribute(STATE_TEMPLATE_INDEX)).intValue(); template = buildContextForTemplate(index, portlet, context, data, state); return template; } // buildMainPanelContext /** * Build the context for each template using template_index parameter passed * in a form hidden field. Each case is associated with a template. (Not all * templates implemented). See String[] TEMPLATES. * * @param index * is the number contained in the template's template_index */ private String buildContextForTemplate(int index, VelocityPortlet portlet, Context context, RunData data, SessionState state) { String realmId = ""; String site_type = ""; String sortedBy = ""; String sortedAsc = ""; ParameterParser params = data.getParameters(); context.put("tlang", rb); context.put("alertMessage", state.getAttribute(STATE_MESSAGE)); // If cleanState() has removed SiteInfo, get a new instance into state SiteInfo siteInfo = new SiteInfo(); if (state.getAttribute(STATE_SITE_INFO) != null) { siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); } else { state.setAttribute(STATE_SITE_INFO, siteInfo); } // Lists used in more than one template // Access List roles = new Vector(); // the hashtables for News and Web Content tools Hashtable newsTitles = new Hashtable(); Hashtable newsUrls = new Hashtable(); Hashtable wcTitles = new Hashtable(); Hashtable wcUrls = new Hashtable(); List toolRegistrationList = new Vector(); List toolRegistrationSelectedList = new Vector(); ResourceProperties siteProperties = null; // for showing site creation steps if (state.getAttribute(SITE_CREATE_TOTAL_STEPS) != null) { context.put("totalSteps", state .getAttribute(SITE_CREATE_TOTAL_STEPS)); } if (state.getAttribute(SITE_CREATE_CURRENT_STEP) != null) { context.put("step", state.getAttribute(SITE_CREATE_CURRENT_STEP)); } String hasGradSites = ServerConfigurationService.getString( "withDissertation", Boolean.FALSE.toString()); context.put("cms", cms); // course site type context.put("courseSiteType", state.getAttribute(STATE_COURSE_SITE_TYPE)); Site site = getStateSite(state); switch (index) { case 0: /* * buildContextForTemplate chef_site-list.vm * */ // site types List sTypes = (List) state.getAttribute(STATE_SITE_TYPES); // make sure auto-updates are enabled Hashtable views = new Hashtable(); if (SecurityService.isSuperUser()) { views.put(rb.getString("java.allmy"), rb .getString("java.allmy")); views.put(rb.getString("java.my") + " " + rb.getString("java.sites"), rb.getString("java.my")); for (int sTypeIndex = 0; sTypeIndex < sTypes.size(); sTypeIndex++) { String type = (String) sTypes.get(sTypeIndex); views.put(type + " " + rb.getString("java.sites"), type); } if (hasGradSites.equalsIgnoreCase("true")) { views.put(rb.getString("java.gradtools") + " " + rb.getString("java.sites"), rb .getString("java.gradtools")); } if (state.getAttribute(STATE_VIEW_SELECTED) == null) { state.setAttribute(STATE_VIEW_SELECTED, rb .getString("java.allmy")); } context.put("superUser", Boolean.TRUE); } else { context.put("superUser", Boolean.FALSE); views.put(rb.getString("java.allmy"), rb .getString("java.allmy")); // if there is a GradToolsStudent choice inside boolean remove = false; if (hasGradSites.equalsIgnoreCase("true")) { try { // the Grad Tools site option is only presented to // GradTools Candidates String userId = StringUtil.trimToZero(SessionManager .getCurrentSessionUserId()); // am I a grad student? if (!isGradToolsCandidate(userId)) { // not a gradstudent remove = true; } } catch (Exception e) { remove = true; } } else { // not support for dissertation sites remove = true; } // do not show this site type in views // sTypes.remove(new String(SITE_TYPE_GRADTOOLS_STUDENT)); for (int sTypeIndex = 0; sTypeIndex < sTypes.size(); sTypeIndex++) { String type = (String) sTypes.get(sTypeIndex); if (!type.equals(SITE_TYPE_GRADTOOLS_STUDENT)) { views .put(type + " " + rb.getString("java.sites"), type); } } if (!remove) { views.put(rb.getString("java.gradtools") + " " + rb.getString("java.sites"), rb .getString("java.gradtools")); } // default view if (state.getAttribute(STATE_VIEW_SELECTED) == null) { state.setAttribute(STATE_VIEW_SELECTED, rb .getString("java.allmy")); } } context.put("views", views); if (state.getAttribute(STATE_VIEW_SELECTED) != null) { context.put("viewSelected", (String) state .getAttribute(STATE_VIEW_SELECTED)); } String search = (String) state.getAttribute(STATE_SEARCH); context.put("search_term", search); sortedBy = (String) state.getAttribute(SORTED_BY); if (sortedBy == null) { state.setAttribute(SORTED_BY, SortType.TITLE_ASC.toString()); sortedBy = SortType.TITLE_ASC.toString(); } sortedAsc = (String) state.getAttribute(SORTED_ASC); if (sortedAsc == null) { sortedAsc = Boolean.TRUE.toString(); state.setAttribute(SORTED_ASC, sortedAsc); } if (sortedBy != null) context.put("currentSortedBy", sortedBy); if (sortedAsc != null) context.put("currentSortAsc", sortedAsc); String portalUrl = ServerConfigurationService.getPortalUrl(); context.put("portalUrl", portalUrl); List sites = prepPage(state); state.setAttribute(STATE_SITES, sites); context.put("sites", sites); context.put("totalPageNumber", new Integer(totalPageNumber(state))); context.put("searchString", state.getAttribute(STATE_SEARCH)); context.put("form_search", FORM_SEARCH); context.put("formPageNumber", FORM_PAGE_NUMBER); context.put("prev_page_exists", state .getAttribute(STATE_PREV_PAGE_EXISTS)); context.put("next_page_exists", state .getAttribute(STATE_NEXT_PAGE_EXISTS)); context.put("current_page", state.getAttribute(STATE_CURRENT_PAGE)); // put the service in the context (used for allow update calls on // each site) context.put("service", SiteService.getInstance()); context.put("sortby_title", SortType.TITLE_ASC.toString()); context.put("sortby_type", SortType.TYPE_ASC.toString()); context.put("sortby_createdby", SortType.CREATED_BY_ASC.toString()); context.put("sortby_publish", SortType.PUBLISHED_ASC.toString()); context.put("sortby_createdon", SortType.CREATED_ON_ASC.toString()); // top menu bar Menu bar = new MenuImpl(portlet, data, (String) state .getAttribute(STATE_ACTION)); if (SiteService.allowAddSite(null)) { bar.add(new MenuEntry(rb.getString("java.new"), "doNew_site")); } bar.add(new MenuEntry(rb.getString("java.revise"), null, true, MenuItem.CHECKED_NA, "doGet_site", "sitesForm")); bar.add(new MenuEntry(rb.getString("java.delete"), null, true, MenuItem.CHECKED_NA, "doMenu_site_delete", "sitesForm")); context.put("menu", bar); // default to be no pageing context.put("paged", Boolean.FALSE); Menu bar2 = new MenuImpl(portlet, data, (String) state .getAttribute(STATE_ACTION)); // add the search commands addSearchMenus(bar2, state); context.put("menu2", bar2); pagingInfoToContext(state, context); return (String) getContext(data).get("template") + TEMPLATE[0]; case 1: /* * buildContextForTemplate chef_site-type.vm * */ if (hasGradSites.equalsIgnoreCase("true")) { context.put("withDissertation", Boolean.TRUE); try { // the Grad Tools site option is only presented to UM grad // students String userId = StringUtil.trimToZero(SessionManager .getCurrentSessionUserId()); // am I a UM grad student? Boolean isGradStudent = new Boolean( isGradToolsCandidate(userId)); context.put("isGradStudent", isGradStudent); // if I am a UM grad student, do I already have a Grad Tools // site? boolean noGradToolsSite = true; if (hasGradToolsStudentSite(userId)) noGradToolsSite = false; context .put("noGradToolsSite", new Boolean(noGradToolsSite)); } catch (Exception e) { if (Log.isWarnEnabled()) { M_log.warn("buildContextForTemplate chef_site-type.vm " + e); } } } else { context.put("withDissertation", Boolean.FALSE); } List types = (List) state.getAttribute(STATE_SITE_TYPES); context.put("siteTypes", types); // put selected/default site type into context if (siteInfo.site_type != null && siteInfo.site_type.length() > 0) { context.put("typeSelected", siteInfo.site_type); } else if (types.size() > 0) { context.put("typeSelected", types.get(0)); } setTermListForContext(context, state, true); // true => only // upcoming terms setSelectedTermForContext(context, state, STATE_TERM_SELECTED); return (String) getContext(data).get("template") + TEMPLATE[1]; case 2: /* * buildContextForTemplate chef_site-newSiteInformation.vm * */ context.put("siteTypes", state.getAttribute(STATE_SITE_TYPES)); String siteType = (String) state.getAttribute(STATE_SITE_TYPE); context.put("type", siteType); if (siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); context.put("isProjectSite", Boolean.FALSE); if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) { context.put("selectedProviderCourse", state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN)); } List<SectionObject> cmRequestedList = (List<SectionObject>) state .getAttribute(STATE_CM_REQUESTED_SECTIONS); if (cmRequestedList != null) { context.put("cmRequestedSections", cmRequestedList); context.put("back", "53"); } List<SectionObject> cmAuthorizerSectionList = (List<SectionObject>) state .getAttribute(STATE_CM_AUTHORIZER_SECTIONS); if (cmAuthorizerSectionList != null) { context .put("cmAuthorizerSections", cmAuthorizerSectionList); context.put("back", "36"); } if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { int number = ((Integer) state .getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)) .intValue(); context.put("manualAddNumber", new Integer(number - 1)); context.put("manualAddFields", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); context.put("back", "37"); } else { if (courseManagementIsImplemented()) { context.put("back", "36"); } else { context.put("back", "0"); context.put("template-index", "37"); } } context.put("skins", state.getAttribute(STATE_ICONS)); if (StringUtil.trimToNull(siteInfo.getIconUrl()) != null) { context.put("selectedIcon", siteInfo.getIconUrl()); } } else { context.put("isCourseSite", Boolean.FALSE); if (siteType.equalsIgnoreCase("project")) { context.put("isProjectSite", Boolean.TRUE); } if (StringUtil.trimToNull(siteInfo.iconUrl) != null) { context.put(FORM_ICON_URL, siteInfo.iconUrl); } context.put("back", "1"); } context.put(FORM_TITLE, siteInfo.title); context.put(FORM_SHORT_DESCRIPTION, siteInfo.short_description); context.put(FORM_DESCRIPTION, siteInfo.description); // defalt the site contact person to the site creator if (siteInfo.site_contact_name.equals(NULL_STRING) && siteInfo.site_contact_email.equals(NULL_STRING)) { User user = UserDirectoryService.getCurrentUser(); siteInfo.site_contact_name = user.getDisplayName(); siteInfo.site_contact_email = user.getEmail(); } context.put("form_site_contact_name", siteInfo.site_contact_name); context.put("form_site_contact_email", siteInfo.site_contact_email); // those manual inputs context.put("form_requiredFields", sectionFieldProvider .getRequiredFields()); context.put("fieldValues", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); return (String) getContext(data).get("template") + TEMPLATE[2]; case 3: /* * buildContextForTemplate chef_site-newSiteFeatures.vm * */ siteType = (String) state.getAttribute(STATE_SITE_TYPE); if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); context.put("isProjectSite", Boolean.FALSE); } else { context.put("isCourseSite", Boolean.FALSE); if (siteType.equalsIgnoreCase("project")) { context.put("isProjectSite", Boolean.TRUE); } } context.put("defaultTools", ServerConfigurationService .getToolsRequired(siteType)); toolRegistrationSelectedList = (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); // If this is the first time through, check for tools // which should be selected by default. List defaultSelectedTools = ServerConfigurationService .getDefaultTools(siteType); if (toolRegistrationSelectedList == null) { toolRegistrationSelectedList = new Vector(defaultSelectedTools); } context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); // String toolId's context.put(STATE_TOOL_REGISTRATION_LIST, state .getAttribute(STATE_TOOL_REGISTRATION_LIST)); // %%% use // ToolRegistrations // for // template // list context .put("emailId", state .getAttribute(STATE_TOOL_EMAIL_ADDRESS)); context.put("serverName", ServerConfigurationService .getServerName()); // The "Home" tool checkbox needs special treatment to be selected // by // default. Boolean checkHome = (Boolean) state .getAttribute(STATE_TOOL_HOME_SELECTED); if (checkHome == null) { if ((defaultSelectedTools != null) && defaultSelectedTools.contains(HOME_TOOL_ID)) { checkHome = Boolean.TRUE; } } context.put("check_home", checkHome); // titles for news tools context.put("newsTitles", state.getAttribute(STATE_NEWS_TITLES)); // titles for web content tools context.put("wcTitles", state .getAttribute(STATE_WEB_CONTENT_TITLES)); // urls for news tools context.put("newsUrls", state.getAttribute(STATE_NEWS_URLS)); // urls for web content tools context.put("wcUrls", state.getAttribute(STATE_WEB_CONTENT_URLS)); context.put("sites", SiteService.getSites( org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, null, null, null, SortType.TITLE_ASC, null)); context.put("import", state.getAttribute(STATE_IMPORT)); context.put("importSites", state.getAttribute(STATE_IMPORT_SITES)); return (String) getContext(data).get("template") + TEMPLATE[3]; case 4: /* * buildContextForTemplate chef_site-addRemoveFeatures.vm * */ context.put("SiteTitle", site.getTitle()); String type = (String) state.getAttribute(STATE_SITE_TYPE); context.put("defaultTools", ServerConfigurationService .getToolsRequired(type)); boolean myworkspace_site = false; // Put up tool lists filtered by category List siteTypes = (List) state.getAttribute(STATE_SITE_TYPES); if (siteTypes.contains(type)) { myworkspace_site = false; } if (SiteService.isUserSite(site.getId()) || (type != null && type.equalsIgnoreCase("myworkspace"))) { myworkspace_site = true; type = "myworkspace"; } context.put("myworkspace_site", new Boolean(myworkspace_site)); context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST)); // titles for news tools context.put("newsTitles", state.getAttribute(STATE_NEWS_TITLES)); // titles for web content tools context.put("wcTitles", state .getAttribute(STATE_WEB_CONTENT_TITLES)); // urls for news tools context.put("newsUrls", state.getAttribute(STATE_NEWS_URLS)); // urls for web content tools context.put("wcUrls", state.getAttribute(STATE_WEB_CONTENT_URLS)); context.put(STATE_TOOL_REGISTRATION_LIST, state .getAttribute(STATE_TOOL_REGISTRATION_LIST)); context.put("check_home", state .getAttribute(STATE_TOOL_HOME_SELECTED)); // get the email alias when an Email Archive tool has been selected String channelReference = mailArchiveChannelReference(site.getId()); List aliases = AliasService.getAliases(channelReference, 1, 1); if (aliases.size() > 0) { state.setAttribute(STATE_TOOL_EMAIL_ADDRESS, ((Alias) aliases .get(0)).getId()); } else { state.removeAttribute(STATE_TOOL_EMAIL_ADDRESS); } if (state.getAttribute(STATE_TOOL_EMAIL_ADDRESS) != null) { context.put("emailId", state .getAttribute(STATE_TOOL_EMAIL_ADDRESS)); } context.put("serverName", ServerConfigurationService .getServerName()); context.put("backIndex", "12"); return (String) getContext(data).get("template") + TEMPLATE[4]; case 5: /* * buildContextForTemplate chef_site-addParticipant.vm * */ context.put("title", site.getTitle()); roles = getRoles(state); context.put("roles", roles); // Note that (for now) these strings are in both sakai.properties // and sitesetupgeneric.properties context.put("officialAccountSectionTitle", ServerConfigurationService .getString("officialAccountSectionTitle")); context.put("officialAccountName", ServerConfigurationService .getString("officialAccountName")); context.put("officialAccountLabel", ServerConfigurationService .getString("officialAccountLabel")); context.put("nonOfficialAccountSectionTitle", ServerConfigurationService .getString("nonOfficialAccountSectionTitle")); context.put("nonOfficialAccountName", ServerConfigurationService .getString("nonOfficialAccountName")); context.put("nonOfficialAccountLabel", ServerConfigurationService .getString("nonOfficialAccountLabel")); if (state.getAttribute("officialAccountValue") != null) { context.put("officialAccountValue", (String) state .getAttribute("officialAccountValue")); } if (state.getAttribute("nonOfficialAccountValue") != null) { context.put("nonOfficialAccountValue", (String) state .getAttribute("nonOfficialAccountValue")); } if (state.getAttribute("form_same_role") != null) { context.put("form_same_role", ((Boolean) state .getAttribute("form_same_role")).toString()); } else { context.put("form_same_role", Boolean.TRUE.toString()); } context.put("backIndex", "12"); return (String) getContext(data).get("template") + TEMPLATE[5]; case 6: /* * buildContextForTemplate chef_site-removeParticipants.vm * */ context.put("title", site.getTitle()); realmId = SiteService.siteReference(site.getId()); try { AuthzGroup realm = AuthzGroupService.getAuthzGroup(realmId); try { List removeableList = (List) state .getAttribute(STATE_REMOVEABLE_USER_LIST); List removeableParticipants = new Vector(); for (int k = 0; k < removeableList.size(); k++) { User user = UserDirectoryService .getUser((String) removeableList.get(k)); Participant participant = new Participant(); participant.name = user.getSortName(); participant.uniqname = user.getId(); Role r = realm.getUserRole(user.getId()); if (r != null) { participant.role = r.getId(); } removeableParticipants.add(participant); } context.put("removeableList", removeableParticipants); } catch (UserNotDefinedException ee) { } } catch (GroupNotDefinedException e) { } context.put("backIndex", "18"); return (String) getContext(data).get("template") + TEMPLATE[6]; case 7: /* * buildContextForTemplate chef_site-changeRoles.vm * */ context.put("same_role", state .getAttribute(STATE_CHANGEROLE_SAMEROLE)); roles = getRoles(state); context.put("roles", roles); context.put("currentRole", state .getAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE)); context.put("participantSelectedList", state .getAttribute(STATE_SELECTED_PARTICIPANTS)); context.put("selectedRoles", state .getAttribute(STATE_SELECTED_PARTICIPANT_ROLES)); context.put("siteTitle", site.getTitle()); return (String) getContext(data).get("template") + TEMPLATE[7]; case 8: /* * buildContextForTemplate chef_site-siteDeleteConfirm.vm * */ String site_title = NULL_STRING; String[] removals = (String[]) state .getAttribute(STATE_SITE_REMOVALS); List remove = new Vector(); String user = SessionManager.getCurrentSessionUserId(); String workspace = SiteService.getUserSiteId(user); if (removals != null && removals.length != 0) { for (int i = 0; i < removals.length; i++) { String id = (String) removals[i]; if (!(id.equals(workspace))) { try { site_title = SiteService.getSite(id).getTitle(); } catch (IdUnusedException e) { M_log .warn("SiteAction.doSite_delete_confirmed - IdUnusedException " + id); addAlert(state, rb.getString("java.sitewith") + " " + id + " " + rb.getString("java.couldnt") + " "); } if (SiteService.allowRemoveSite(id)) { try { Site removeSite = SiteService.getSite(id); remove.add(removeSite); } catch (IdUnusedException e) { M_log .warn("SiteAction.buildContextForTemplate chef_site-siteDeleteConfirm.vm: IdUnusedException"); } } else { addAlert(state, site_title + " " + rb.getString("java.couldntdel") + " "); } } else { addAlert(state, rb.getString("java.yourwork")); } } if (remove.size() == 0) { addAlert(state, rb.getString("java.click")); } } context.put("removals", remove); return (String) getContext(data).get("template") + TEMPLATE[8]; case 9: /* * buildContextForTemplate chef_site-publishUnpublish.vm * */ context.put("publish", Boolean.valueOf(((SiteInfo) state .getAttribute(STATE_SITE_INFO)).getPublished())); context.put("backIndex", "12"); return (String) getContext(data).get("template") + TEMPLATE[9]; case 10: /* * buildContextForTemplate chef_site-newSiteConfirm.vm * */ siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); siteType = (String) state.getAttribute(STATE_SITE_TYPE); if (siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); context.put("isProjectSite", Boolean.FALSE); if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) { context.put("selectedProviderCourse", state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN)); } if (state.getAttribute(STATE_CM_AUTHORIZER_SECTIONS) != null) { context.put("selectedAuthorizerCourse", state .getAttribute(STATE_CM_AUTHORIZER_SECTIONS)); } if (state.getAttribute(STATE_CM_REQUESTED_SECTIONS) != null) { context.put("selectedRequestedCourse", state .getAttribute(STATE_CM_REQUESTED_SECTIONS)); } if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { int number = ((Integer) state .getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)) .intValue(); context.put("manualAddNumber", new Integer(number - 1)); context.put("manualAddFields", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); } context.put("skins", state.getAttribute(STATE_ICONS)); if (StringUtil.trimToNull(siteInfo.getIconUrl()) != null) { context.put("selectedIcon", siteInfo.getIconUrl()); } } else { context.put("isCourseSite", Boolean.FALSE); if (siteType != null && siteType.equalsIgnoreCase("project")) { context.put("isProjectSite", Boolean.TRUE); } if (StringUtil.trimToNull(siteInfo.iconUrl) != null) { context.put("iconUrl", siteInfo.iconUrl); } } context.put("title", siteInfo.title); context.put("description", siteInfo.description); context.put("short_description", siteInfo.short_description); context.put("siteContactName", siteInfo.site_contact_name); context.put("siteContactEmail", siteInfo.site_contact_email); siteType = (String) state.getAttribute(STATE_SITE_TYPE); toolRegistrationSelectedList = (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); // String toolId's context.put(STATE_TOOL_REGISTRATION_LIST, state .getAttribute(STATE_TOOL_REGISTRATION_LIST)); // %%% use // Tool context.put("check_home", state .getAttribute(STATE_TOOL_HOME_SELECTED)); context .put("emailId", state .getAttribute(STATE_TOOL_EMAIL_ADDRESS)); context.put("serverName", ServerConfigurationService .getServerName()); context.put("include", new Boolean(siteInfo.include)); context.put("published", new Boolean(siteInfo.published)); context.put("joinable", new Boolean(siteInfo.joinable)); context.put("joinerRole", siteInfo.joinerRole); context.put("newsTitles", (Hashtable) state .getAttribute(STATE_NEWS_TITLES)); context.put("wcTitles", (Hashtable) state .getAttribute(STATE_WEB_CONTENT_TITLES)); // back to edit access page context.put("back", "18"); context.put("importSiteTools", state .getAttribute(STATE_IMPORT_SITE_TOOL)); context.put("siteService", SiteService.getInstance()); // those manual inputs context.put("form_requiredFields", sectionFieldProvider .getRequiredFields()); context.put("fieldValues", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); return (String) getContext(data).get("template") + TEMPLATE[10]; case 11: /* * buildContextForTemplate chef_site-newSitePublishUnpublish.vm * */ return (String) getContext(data).get("template") + TEMPLATE[11]; case 12: /* * buildContextForTemplate chef_site-siteInfo-list.vm * */ context.put("userDirectoryService", UserDirectoryService .getInstance()); try { siteProperties = site.getProperties(); siteType = site.getType(); if (siteType != null) { state.setAttribute(STATE_SITE_TYPE, siteType); } boolean isMyWorkspace = false; if (SiteService.isUserSite(site.getId())) { if (SiteService.getSiteUserId(site.getId()).equals( SessionManager.getCurrentSessionUserId())) { isMyWorkspace = true; context.put("siteUserId", SiteService .getSiteUserId(site.getId())); } } context.put("isMyWorkspace", Boolean.valueOf(isMyWorkspace)); String siteId = site.getId(); if (state.getAttribute(STATE_ICONS) != null) { List skins = (List) state.getAttribute(STATE_ICONS); for (int i = 0; i < skins.size(); i++) { MyIcon s = (MyIcon) skins.get(i); if (!StringUtil .different(s.getUrl(), site.getIconUrl())) { context.put("siteUnit", s.getName()); break; } } } context.put("siteIcon", site.getIconUrl()); context.put("siteTitle", site.getTitle()); context.put("siteDescription", site.getDescription()); context.put("siteJoinable", new Boolean(site.isJoinable())); if (site.isPublished()) { context.put("published", Boolean.TRUE); } else { context.put("published", Boolean.FALSE); context.put("owner", site.getCreatedBy().getSortName()); } Time creationTime = site.getCreatedTime(); if (creationTime != null) { context.put("siteCreationDate", creationTime .toStringLocalFull()); } boolean allowUpdateSite = SiteService.allowUpdateSite(siteId); context.put("allowUpdate", Boolean.valueOf(allowUpdateSite)); boolean allowUpdateGroupMembership = SiteService .allowUpdateGroupMembership(siteId); context.put("allowUpdateGroupMembership", Boolean .valueOf(allowUpdateGroupMembership)); boolean allowUpdateSiteMembership = SiteService .allowUpdateSiteMembership(siteId); context.put("allowUpdateSiteMembership", Boolean .valueOf(allowUpdateSiteMembership)); Menu b = new MenuImpl(portlet, data, (String) state .getAttribute(STATE_ACTION)); if (allowUpdateSite) { // top menu bar if (!isMyWorkspace) { b.add(new MenuEntry(rb.getString("java.editsite"), "doMenu_edit_site_info")); } b.add(new MenuEntry(rb.getString("java.edittools"), "doMenu_edit_site_tools")); } if (allowUpdateSiteMembership) { // show add participant menu if (!isMyWorkspace) { // show the Add Participant menu b.add(new MenuEntry(rb.getString("java.addp"), "doMenu_siteInfo_addParticipant")); } } if (allowUpdateGroupMembership) { // show Manage Groups menu if (!isMyWorkspace && (ServerConfigurationService .getString("wsetup.group.support") == "" || ServerConfigurationService .getString("wsetup.group.support") .equalsIgnoreCase(Boolean.TRUE.toString()))) { // show the group toolbar unless configured // to not support group b.add(new MenuEntry(rb.getString("java.group"), "doMenu_group")); } } if (allowUpdateSite) { if (!isMyWorkspace) { List gradToolsSiteTypes = (List) state .getAttribute(GRADTOOLS_SITE_TYPES); boolean isGradToolSite = false; if (siteType != null && gradToolsSiteTypes.contains(siteType)) { isGradToolSite = true; } if (siteType == null || siteType != null && !isGradToolSite) { // hide site access for GRADTOOLS // type of sites b.add(new MenuEntry( rb.getString("java.siteaccess"), "doMenu_edit_site_access")); } if (siteType != null && siteType.equals((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { b.add(new MenuEntry(rb.getString("java.editc"), "doMenu_siteInfo_editClass")); } if (siteType == null || siteType != null && !isGradToolSite) { // hide site duplicate and import // for GRADTOOLS type of sites if (SiteService.allowAddSite(null)) { b.add(new MenuEntry(rb.getString("java.duplicate"), "doMenu_siteInfo_duplicate")); } List updatableSites = SiteService .getSites( org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, null, null, null, SortType.TITLE_ASC, null); // import link should be visible even if only one // site if (updatableSites.size() > 0) { b.add(new MenuEntry( rb.getString("java.import"), "doMenu_siteInfo_import")); // a configuration param for // showing/hiding import // from file choice String importFromFile = ServerConfigurationService .getString("site.setup.import.file", Boolean.TRUE.toString()); if (importFromFile.equalsIgnoreCase("true")) { // htripath: June // 4th added as per // Kris and changed // desc of above b.add(new MenuEntry(rb .getString("java.importFile"), "doAttachmentsMtrlFrmFile")); } } } } // if the page order helper is available, not // stealthed and not hidden, show the link if (notStealthOrHiddenTool("sakai-site-pageorder-helper")) { b.add(new MenuEntry(rb.getString("java.orderpages"), "doPageOrderHelper")); } } if (b.size() > 0) { // add the menus to vm context.put("menu", b); } if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITESETUP)) { // editing from worksite setup tool context.put("fromWSetup", Boolean.TRUE); if (state.getAttribute(STATE_PREV_SITE) != null) { context.put("prevSite", state .getAttribute(STATE_PREV_SITE)); } if (state.getAttribute(STATE_NEXT_SITE) != null) { context.put("nextSite", state .getAttribute(STATE_NEXT_SITE)); } } else { context.put("fromWSetup", Boolean.FALSE); } // allow view roster? boolean allowViewRoster = SiteService.allowViewRoster(siteId); if (allowViewRoster) { context.put("viewRoster", Boolean.TRUE); } else { context.put("viewRoster", Boolean.FALSE); } // set participant list if (allowUpdateSite || allowViewRoster || allowUpdateSiteMembership) { Collection participantsCollection = getParticipantList(state); sortedBy = (String) state.getAttribute(SORTED_BY); sortedAsc = (String) state.getAttribute(SORTED_ASC); if (sortedBy == null) { state.setAttribute(SORTED_BY, SORTED_BY_PARTICIPANT_NAME); sortedBy = SORTED_BY_PARTICIPANT_NAME; } if (sortedAsc == null) { sortedAsc = Boolean.TRUE.toString(); state.setAttribute(SORTED_ASC, sortedAsc); } if (sortedBy != null) context.put("currentSortedBy", sortedBy); if (sortedAsc != null) context.put("currentSortAsc", sortedAsc); context.put("participantListSize", new Integer(participantsCollection.size())); context.put("participantList", prepPage(state)); pagingInfoToContext(state, context); } context.put("include", Boolean.valueOf(site.isPubView())); // site contact information String contactName = siteProperties .getProperty(PROP_SITE_CONTACT_NAME); String contactEmail = siteProperties .getProperty(PROP_SITE_CONTACT_EMAIL); if (contactName == null && contactEmail == null) { User u = site.getCreatedBy(); String email = u.getEmail(); if (email != null) { contactEmail = u.getEmail(); } contactName = u.getDisplayName(); } if (contactName != null) { context.put("contactName", contactName); } if (contactEmail != null) { context.put("contactEmail", contactEmail); } if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); coursesIntoContext(state, context, site); context.put("term", siteProperties .getProperty(PROP_SITE_TERM)); } else { context.put("isCourseSite", Boolean.FALSE); } } catch (Exception e) { M_log.warn(this + " site info list: " + e.toString()); } roles = getRoles(state); context.put("roles", roles); // will have the choice to active/inactive user or not String activeInactiveUser = ServerConfigurationService.getString( "activeInactiveUser", Boolean.FALSE.toString()); if (activeInactiveUser.equalsIgnoreCase("true")) { context.put("activeInactiveUser", Boolean.TRUE); // put realm object into context realmId = SiteService.siteReference(site.getId()); try { context.put("realm", AuthzGroupService .getAuthzGroup(realmId)); } catch (GroupNotDefinedException e) { M_log.warn(this + " IdUnusedException " + realmId); } } else { context.put("activeInactiveUser", Boolean.FALSE); } context.put("groupsWithMember", site .getGroupsWithMember(UserDirectoryService.getCurrentUser() .getId())); return (String) getContext(data).get("template") + TEMPLATE[12]; case 13: /* * buildContextForTemplate chef_site-siteInfo-editInfo.vm * */ siteProperties = site.getProperties(); context.put("title", state.getAttribute(FORM_SITEINFO_TITLE)); context.put("type", site.getType()); siteType = (String) state.getAttribute(STATE_SITE_TYPE); if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); context.put("skins", state.getAttribute(STATE_ICONS)); if (state.getAttribute(FORM_SITEINFO_SKIN) != null) { context.put("selectedIcon", state .getAttribute(FORM_SITEINFO_SKIN)); } else if (site.getIconUrl() != null) { context.put("selectedIcon", site.getIconUrl()); } setTermListForContext(context, state, true); // true->only future terms if (state.getAttribute(FORM_SITEINFO_TERM) == null) { String currentTerm = site.getProperties().getProperty( PROP_SITE_TERM); if (currentTerm != null) { state.setAttribute(FORM_SITEINFO_TERM, currentTerm); } } setSelectedTermForContext(context, state, FORM_SITEINFO_TERM); } else { context.put("isCourseSite", Boolean.FALSE); if (state.getAttribute(FORM_SITEINFO_ICON_URL) == null && StringUtil.trimToNull(site.getIconUrl()) != null) { state.setAttribute(FORM_SITEINFO_ICON_URL, site .getIconUrl()); } if (state.getAttribute(FORM_SITEINFO_ICON_URL) != null) { context.put("iconUrl", state .getAttribute(FORM_SITEINFO_ICON_URL)); } } context.put("description", state .getAttribute(FORM_SITEINFO_DESCRIPTION)); context.put("short_description", state .getAttribute(FORM_SITEINFO_SHORT_DESCRIPTION)); context.put("form_site_contact_name", state .getAttribute(FORM_SITEINFO_CONTACT_NAME)); context.put("form_site_contact_email", state .getAttribute(FORM_SITEINFO_CONTACT_EMAIL)); // Display of appearance icon/url list with course site based on // "disable.course.site.skin.selection" value set with // sakai.properties file. if ((ServerConfigurationService .getString("disable.course.site.skin.selection")) .equals("true")) { context.put("disableCourseSelection", Boolean.TRUE); } return (String) getContext(data).get("template") + TEMPLATE[13]; case 14: /* * buildContextForTemplate chef_site-siteInfo-editInfoConfirm.vm * */ siteProperties = site.getProperties(); siteType = (String) state.getAttribute(STATE_SITE_TYPE); if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); context.put("siteTerm", state.getAttribute(FORM_SITEINFO_TERM)); } else { context.put("isCourseSite", Boolean.FALSE); } context.put("oTitle", site.getTitle()); context.put("title", state.getAttribute(FORM_SITEINFO_TITLE)); context.put("description", state .getAttribute(FORM_SITEINFO_DESCRIPTION)); context.put("oDescription", site.getDescription()); context.put("short_description", state .getAttribute(FORM_SITEINFO_SHORT_DESCRIPTION)); context.put("oShort_description", site.getShortDescription()); context.put("skin", state.getAttribute(FORM_SITEINFO_SKIN)); context.put("oSkin", site.getIconUrl()); context.put("skins", state.getAttribute(STATE_ICONS)); context.put("oIcon", site.getIconUrl()); context.put("icon", state.getAttribute(FORM_SITEINFO_ICON_URL)); context.put("include", state.getAttribute(FORM_SITEINFO_INCLUDE)); context.put("oInclude", Boolean.valueOf(site.isPubView())); context.put("name", state.getAttribute(FORM_SITEINFO_CONTACT_NAME)); context.put("oName", siteProperties .getProperty(PROP_SITE_CONTACT_NAME)); context.put("email", state .getAttribute(FORM_SITEINFO_CONTACT_EMAIL)); context.put("oEmail", siteProperties .getProperty(PROP_SITE_CONTACT_EMAIL)); return (String) getContext(data).get("template") + TEMPLATE[14]; case 15: /* * buildContextForTemplate chef_site-addRemoveFeatureConfirm.vm * */ context.put("title", site.getTitle()); site_type = (String) state.getAttribute(STATE_SITE_TYPE); myworkspace_site = false; if (SiteService.isUserSite(site.getId())) { if (SiteService.getSiteUserId(site.getId()).equals( SessionManager.getCurrentSessionUserId())) { myworkspace_site = true; site_type = "myworkspace"; } } context.put(STATE_TOOL_REGISTRATION_LIST, state .getAttribute(STATE_TOOL_REGISTRATION_LIST)); context.put("check_home", state .getAttribute(STATE_TOOL_HOME_SELECTED)); context.put("selectedTools", orderToolIds(state, (String) state .getAttribute(STATE_SITE_TYPE), (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST))); context.put("oldSelectedTools", state .getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST)); context.put("oldSelectedHome", state .getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME)); context.put("continueIndex", "12"); if (state.getAttribute(STATE_TOOL_EMAIL_ADDRESS) != null) { context.put("emailId", state .getAttribute(STATE_TOOL_EMAIL_ADDRESS)); } context.put("serverName", ServerConfigurationService .getServerName()); context.put("newsTitles", (Hashtable) state .getAttribute(STATE_NEWS_TITLES)); context.put("wcTitles", (Hashtable) state .getAttribute(STATE_WEB_CONTENT_TITLES)); if (fromENWModifyView(state)) { context.put("back", "26"); } else { context.put("back", "4"); } return (String) getContext(data).get("template") + TEMPLATE[15]; case 16: /* * buildContextForTemplate chef_site-publishUnpublish-sendEmail.vm * */ context.put("title", site.getTitle()); context.put("willNotify", state.getAttribute(FORM_WILL_NOTIFY)); return (String) getContext(data).get("template") + TEMPLATE[16]; case 17: /* * buildContextForTemplate chef_site-publishUnpublish-confirm.vm * */ context.put("title", site.getTitle()); context.put("continueIndex", "12"); SiteInfo sInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); if (sInfo.getPublished()) { context.put("publish", Boolean.TRUE); context.put("backIndex", "16"); } else { context.put("publish", Boolean.FALSE); context.put("backIndex", "9"); } context.put("willNotify", state.getAttribute(FORM_WILL_NOTIFY)); return (String) getContext(data).get("template") + TEMPLATE[17]; case 18: /* * buildContextForTemplate chef_siteInfo-editAccess.vm * */ List publicChangeableSiteTypes = (List) state .getAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES); List unJoinableSiteTypes = (List) state .getAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE); if (site != null) { // editing existing site context.put("site", site); siteType = state.getAttribute(STATE_SITE_TYPE) != null ? (String) state .getAttribute(STATE_SITE_TYPE) : null; if (siteType != null && publicChangeableSiteTypes.contains(siteType)) { context.put("publicChangeable", Boolean.TRUE); } else { context.put("publicChangeable", Boolean.FALSE); } context.put("include", Boolean.valueOf(site.isPubView())); if (siteType != null && !unJoinableSiteTypes.contains(siteType)) { // site can be set as joinable context.put("disableJoinable", Boolean.FALSE); if (state.getAttribute(STATE_JOINABLE) == null) { state.setAttribute(STATE_JOINABLE, Boolean.valueOf(site .isJoinable())); } if (state.getAttribute(STATE_JOINERROLE) == null || state.getAttribute(STATE_JOINABLE) != null && ((Boolean) state.getAttribute(STATE_JOINABLE)) .booleanValue()) { state.setAttribute(STATE_JOINERROLE, site .getJoinerRole()); } if (state.getAttribute(STATE_JOINABLE) != null) { context.put("joinable", state .getAttribute(STATE_JOINABLE)); } if (state.getAttribute(STATE_JOINERROLE) != null) { context.put("joinerRole", state .getAttribute(STATE_JOINERROLE)); } } else { // site cannot be set as joinable context.put("disableJoinable", Boolean.TRUE); } context.put("roles", getRoles(state)); context.put("back", "12"); } else { siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); if (siteInfo.site_type != null && publicChangeableSiteTypes .contains(siteInfo.site_type)) { context.put("publicChangeable", Boolean.TRUE); } else { context.put("publicChangeable", Boolean.FALSE); } context.put("include", Boolean.valueOf(siteInfo.getInclude())); context.put("published", Boolean.valueOf(siteInfo .getPublished())); if (siteInfo.site_type != null && !unJoinableSiteTypes.contains(siteInfo.site_type)) { // site can be set as joinable context.put("disableJoinable", Boolean.FALSE); context.put("joinable", Boolean.valueOf(siteInfo.joinable)); context.put("joinerRole", siteInfo.joinerRole); } else { // site cannot be set as joinable context.put("disableJoinable", Boolean.TRUE); } // use the type's template, if defined String realmTemplate = "!site.template"; if (siteInfo.site_type != null) { realmTemplate = realmTemplate + "." + siteInfo.site_type; } try { AuthzGroup r = AuthzGroupService .getAuthzGroup(realmTemplate); context.put("roles", r.getRoles()); } catch (GroupNotDefinedException e) { try { AuthzGroup rr = AuthzGroupService .getAuthzGroup("!site.template"); context.put("roles", rr.getRoles()); } catch (GroupNotDefinedException ee) { } } // new site, go to confirmation page context.put("continue", "10"); if (fromENWModifyView(state)) { context.put("back", "26"); } else if (state.getAttribute(STATE_IMPORT) != null) { context.put("back", "27"); } else { context.put("back", "3"); } siteType = (String) state.getAttribute(STATE_SITE_TYPE); if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); context.put("isProjectSite", Boolean.FALSE); } else { context.put("isCourseSite", Boolean.FALSE); if (siteType.equalsIgnoreCase("project")) { context.put("isProjectSite", Boolean.TRUE); } } } return (String) getContext(data).get("template") + TEMPLATE[18]; case 19: /* * buildContextForTemplate chef_site-addParticipant-sameRole.vm * */ context.put("title", site.getTitle()); context.put("roles", getRoles(state)); context.put("participantList", state .getAttribute(STATE_ADD_PARTICIPANTS)); context.put("form_selectedRole", state .getAttribute("form_selectedRole")); return (String) getContext(data).get("template") + TEMPLATE[19]; case 20: /* * buildContextForTemplate chef_site-addParticipant-differentRole.vm * */ context.put("title", site.getTitle()); context.put("roles", getRoles(state)); context.put("selectedRoles", state .getAttribute(STATE_SELECTED_PARTICIPANT_ROLES)); context.put("participantList", state .getAttribute(STATE_ADD_PARTICIPANTS)); return (String) getContext(data).get("template") + TEMPLATE[20]; case 21: /* * buildContextForTemplate chef_site-addParticipant-notification.vm * */ context.put("title", site.getTitle()); context.put("sitePublished", Boolean.valueOf(site.isPublished())); if (state.getAttribute("form_selectedNotify") == null) { state.setAttribute("form_selectedNotify", Boolean.FALSE); } context.put("notify", state.getAttribute("form_selectedNotify")); boolean same_role = state.getAttribute("form_same_role") == null ? true : ((Boolean) state.getAttribute("form_same_role")) .booleanValue(); if (same_role) { context.put("backIndex", "19"); } else { context.put("backIndex", "20"); } return (String) getContext(data).get("template") + TEMPLATE[21]; case 22: /* * buildContextForTemplate chef_site-addParticipant-confirm.vm * */ context.put("title", site.getTitle()); context.put("participants", state .getAttribute(STATE_ADD_PARTICIPANTS)); context.put("notify", state.getAttribute("form_selectedNotify")); context.put("roles", getRoles(state)); context.put("same_role", state.getAttribute("form_same_role")); context.put("selectedRoles", state .getAttribute(STATE_SELECTED_PARTICIPANT_ROLES)); context .put("selectedRole", state .getAttribute("form_selectedRole")); return (String) getContext(data).get("template") + TEMPLATE[22]; case 23: /* * buildContextForTemplate chef_siteInfo-editAccess-globalAccess.vm * */ context.put("title", site.getTitle()); context.put("roles", getRoles(state)); if (state.getAttribute("form_joinable") == null) { state.setAttribute("form_joinable", new Boolean(site .isJoinable())); } context.put("form_joinable", state.getAttribute("form_joinable")); if (state.getAttribute("form_joinerRole") == null) { state.setAttribute("form_joinerRole", site.getJoinerRole()); } context.put("form_joinerRole", state .getAttribute("form_joinerRole")); return (String) getContext(data).get("template") + TEMPLATE[23]; case 24: /* * buildContextForTemplate * chef_siteInfo-editAccess-globalAccess-confirm.vm * */ context.put("title", site.getTitle()); context.put("form_joinable", state.getAttribute("form_joinable")); context.put("form_joinerRole", state .getAttribute("form_joinerRole")); return (String) getContext(data).get("template") + TEMPLATE[24]; case 25: /* * buildContextForTemplate chef_changeRoles-confirm.vm * */ Boolean sameRole = (Boolean) state .getAttribute(STATE_CHANGEROLE_SAMEROLE); context.put("sameRole", sameRole); if (sameRole.booleanValue()) { // same role context.put("currentRole", state .getAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE)); } else { context.put("selectedRoles", state .getAttribute(STATE_SELECTED_PARTICIPANT_ROLES)); } roles = getRoles(state); context.put("roles", roles); context.put("participantSelectedList", state .getAttribute(STATE_SELECTED_PARTICIPANTS)); if (state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES) != null) { context.put("selectedRoles", state .getAttribute(STATE_SELECTED_PARTICIPANT_ROLES)); } context.put("siteTitle", site.getTitle()); return (String) getContext(data).get("template") + TEMPLATE[25]; case 26: /* * buildContextForTemplate chef_site-modifyENW.vm * */ site_type = (String) state.getAttribute(STATE_SITE_TYPE); boolean existingSite = site != null ? true : false; if (existingSite) { // revising a existing site's tool context.put("existingSite", Boolean.TRUE); context.put("back", "4"); context.put("continue", "15"); context.put("function", "eventSubmit_doAdd_remove_features"); } else { // new site context.put("existingSite", Boolean.FALSE); context.put("function", "eventSubmit_doAdd_features"); if (state.getAttribute(STATE_IMPORT) != null) { context.put("back", "27"); } else { // new site, go to edit access page context.put("back", "3"); } context.put("continue", "18"); } context.put(STATE_TOOL_REGISTRATION_LIST, state .getAttribute(STATE_TOOL_REGISTRATION_LIST)); toolRegistrationSelectedList = (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); // String toolId's String emailId = (String) state .getAttribute(STATE_TOOL_EMAIL_ADDRESS); if (emailId != null) { context.put("emailId", emailId); } // titles for news tools newsTitles = (Hashtable) state.getAttribute(STATE_NEWS_TITLES); if (newsTitles == null) { newsTitles = new Hashtable(); newsTitles.put("sakai.news", NEWS_DEFAULT_TITLE); state.setAttribute(STATE_NEWS_TITLES, newsTitles); } context.put("newsTitles", newsTitles); // urls for news tools newsUrls = (Hashtable) state.getAttribute(STATE_NEWS_URLS); if (newsUrls == null) { newsUrls = new Hashtable(); newsUrls.put("sakai.news", NEWS_DEFAULT_URL); state.setAttribute(STATE_NEWS_URLS, newsUrls); } context.put("newsUrls", newsUrls); // titles for web content tools wcTitles = (Hashtable) state.getAttribute(STATE_WEB_CONTENT_TITLES); if (wcTitles == null) { wcTitles = new Hashtable(); wcTitles.put("sakai.iframe", WEB_CONTENT_DEFAULT_TITLE); state.setAttribute(STATE_WEB_CONTENT_TITLES, wcTitles); } context.put("wcTitles", wcTitles); // URLs for web content tools wcUrls = (Hashtable) state.getAttribute(STATE_WEB_CONTENT_URLS); if (wcUrls == null) { wcUrls = new Hashtable(); wcUrls.put("sakai.iframe", WEB_CONTENT_DEFAULT_URL); state.setAttribute(STATE_WEB_CONTENT_URLS, wcUrls); } context.put("wcUrls", wcUrls); context.put("serverName", ServerConfigurationService .getServerName()); context.put("oldSelectedTools", state .getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST)); return (String) getContext(data).get("template") + TEMPLATE[26]; case 27: /* * buildContextForTemplate chef_site-importSites.vm * */ existingSite = site != null ? true : false; site_type = (String) state.getAttribute(STATE_SITE_TYPE); if (existingSite) { // revising a existing site's tool context.put("continue", "12"); context.put("back", "28"); context.put("totalSteps", "2"); context.put("step", "2"); context.put("currentSite", site); } else { // new site, go to edit access page context.put("back", "3"); if (fromENWModifyView(state)) { context.put("continue", "26"); } else { context.put("continue", "18"); } } context.put(STATE_TOOL_REGISTRATION_LIST, state .getAttribute(STATE_TOOL_REGISTRATION_LIST)); context.put("selectedTools", orderToolIds(state, site_type, (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST))); // String toolId's context.put("importSites", state.getAttribute(STATE_IMPORT_SITES)); context.put("importSitesTools", state .getAttribute(STATE_IMPORT_SITE_TOOL)); context.put("check_home", state .getAttribute(STATE_TOOL_HOME_SELECTED)); context.put("importSupportedTools", importTools()); return (String) getContext(data).get("template") + TEMPLATE[27]; case 28: /* * buildContextForTemplate chef_siteinfo-import.vm * */ context.put("currentSite", site); context.put("importSiteList", state .getAttribute(STATE_IMPORT_SITES)); context.put("sites", SiteService.getSites( org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, null, null, null, SortType.TITLE_ASC, null)); return (String) getContext(data).get("template") + TEMPLATE[28]; case 29: /* * buildContextForTemplate chef_siteinfo-duplicate.vm * */ context.put("siteTitle", site.getTitle()); String sType = site.getType(); if (sType != null && sType.equals((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); context.put("currentTermId", site.getProperties().getProperty( PROP_SITE_TERM)); setTermListForContext(context, state, true); // true upcoming only } else { context.put("isCourseSite", Boolean.FALSE); } if (state.getAttribute(SITE_DUPLICATED) == null) { context.put("siteDuplicated", Boolean.FALSE); } else { context.put("siteDuplicated", Boolean.TRUE); context.put("duplicatedName", state .getAttribute(SITE_DUPLICATED_NAME)); } return (String) getContext(data).get("template") + TEMPLATE[29]; case 36: /* * buildContextForTemplate chef_site-newSiteCourse.vm */ // SAK-9824 Boolean enableCourseCreationForUser = ServerConfigurationService.getBoolean("site.enableCreateAnyUser", Boolean.FALSE); context.put("enableCourseCreationForUser", enableCourseCreationForUser); if (site != null) { context.put("site", site); context.put("siteTitle", site.getTitle()); setTermListForContext(context, state, true); // true -> upcoming only List providerCourseList = (List) state .getAttribute(SITE_PROVIDER_COURSE_LIST); coursesIntoContext(state, context, site); AcademicSession t = (AcademicSession) state .getAttribute(STATE_TERM_SELECTED); context.put("term", t); if (t != null) { String userId = UserDirectoryService.getCurrentUser().getEid(); List courses = prepareCourseAndSectionListing(userId, t .getEid(), state); if (courses != null && courses.size() > 0) { Vector notIncludedCourse = new Vector(); // remove included sites for (Iterator i = courses.iterator(); i.hasNext();) { CourseObject c = (CourseObject) i.next(); if (providerCourseList == null || providerCourseList != null && !providerCourseList.contains(c.getEid())) { notIncludedCourse.add(c); } } state.setAttribute(STATE_TERM_COURSE_LIST, notIncludedCourse); } else { state.removeAttribute(STATE_TERM_COURSE_LIST); } } // step number used in UI state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer("1")); } else { // need to include both list 'cos STATE_CM_AUTHORIZER_SECTIONS // contains sections that doens't belongs to current user and // STATE_ADD_CLASS_PROVIDER_CHOSEN contains section that does - // v2.4 daisyf if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null || state.getAttribute(STATE_CM_AUTHORIZER_SECTIONS) != null) { List<String> providerSectionList = (List<String>) state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN); if (providerSectionList != null) { /* List list1 = prepareSectionObject(providerSectionList, (String) state .getAttribute(STATE_CM_CURRENT_USERID)); */ context.put("selectedProviderCourse", providerSectionList); } List<SectionObject> authorizerSectionList = (List<SectionObject>) state .getAttribute(STATE_CM_AUTHORIZER_SECTIONS); if (authorizerSectionList != null) { List authorizerList = (List) state .getAttribute(STATE_CM_AUTHORIZER_LIST); //authorizerList is a list of SectionObject /* String userId = null; if (authorizerList != null) { userId = (String) authorizerList.get(0); } List list2 = prepareSectionObject( authorizerSectionList, userId); */ ArrayList list2 = new ArrayList(); for (int i=0; i<authorizerSectionList.size();i++){ SectionObject so = (SectionObject)authorizerSectionList.get(i); list2.add(so.getEid()); } context.put("selectedAuthorizerCourse", list2); } } if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { context.put("selectedManualCourse", Boolean.TRUE); } context.put("term", (AcademicSession) state .getAttribute(STATE_TERM_SELECTED)); context.put("currentUserId", (String) state .getAttribute(STATE_CM_CURRENT_USERID)); context.put("form_additional", (String) state .getAttribute(FORM_ADDITIONAL)); context.put("authorizers", getAuthorizers(state)); } if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITESETUP)) { context.put("backIndex", "1"); } else if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITEINFO)) { context.put("backIndex", ""); } List ll = (List) state.getAttribute(STATE_TERM_COURSE_LIST); context.put("termCourseList", state .getAttribute(STATE_TERM_COURSE_LIST)); // added for 2.4 -daisyf context.put("campusDirectory", getCampusDirectory()); context.put("userId", (String) state .getAttribute(STATE_INSTRUCTOR_SELECTED)); /* * for measuring how long it takes to load sections java.util.Date * date = new java.util.Date(); M_log.debug("***2. finish at: * "+date); M_log.debug("***3. userId:"+(String) state * .getAttribute(STATE_INSTRUCTOR_SELECTED)); */ return (String) getContext(data).get("template") + TEMPLATE[36]; case 37: /* * buildContextForTemplate chef_site-newSiteCourseManual.vm */ if (site != null) { context.put("site", site); context.put("siteTitle", site.getTitle()); coursesIntoContext(state, context, site); } buildInstructorSectionsList(state, params, context); context.put("form_requiredFields", sectionFieldProvider .getRequiredFields()); context.put("form_additional", siteInfo.additional); context.put("form_title", siteInfo.title); context.put("form_description", siteInfo.description); context.put("officialAccountName", ServerConfigurationService .getString("officialAccountName", "")); context.put("value_uniqname", state .getAttribute(STATE_SITE_QUEST_UNIQNAME)); int number = 1; if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { number = ((Integer) state .getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)) .intValue(); context.put("currentNumber", new Integer(number)); } context.put("currentNumber", new Integer(number)); context.put("listSize", new Integer(number - 1)); context.put("fieldValues", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) { List l = (List) state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN); context.put("selectedProviderCourse", l); context.put("size", new Integer(l.size() - 1)); } if (state.getAttribute(STATE_CM_REQUESTED_SECTIONS) != null) { List l = (List) state .getAttribute(STATE_CM_REQUESTED_SECTIONS); context.put("cmRequestedSections", l); } if (state.getAttribute(STATE_SITE_MODE).equals(SITE_MODE_SITEINFO)) { context.put("editSite", Boolean.TRUE); context.put("cmSelectedSections", state.getAttribute(STATE_CM_SELECTED_SECTIONS)); } if (site == null) { // v2.4 - added & modified by daisyf if (courseManagementIsImplemented() && state.getAttribute(STATE_TERM_COURSE_LIST) != null) { // back to the list view of sections context.put("back", "36"); } else { context.put("back", "1"); } if (state.getAttribute(STATE_AUTO_ADD) != null) { context.put("autoAdd", Boolean.TRUE); // context.put("back", "36"); } } else { // editing site context.put("back", "36"); } isFutureTermSelected(state); context.put("isFutureTerm", state .getAttribute(STATE_FUTURE_TERM_SELECTED)); context.put("weeksAhead", ServerConfigurationService.getString( "roster.available.weeks.before.term.start", "0")); return (String) getContext(data).get("template") + TEMPLATE[37]; case 42: /* * buildContextForTemplate chef_site-gradtoolsConfirm.vm * */ siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); context.put("title", siteInfo.title); context.put("description", siteInfo.description); context.put("short_description", siteInfo.short_description); toolRegistrationList = (Vector) state .getAttribute(STATE_PROJECT_TOOL_LIST); toolRegistrationSelectedList = (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); // String toolId's context.put(STATE_TOOL_REGISTRATION_LIST, toolRegistrationList); // %%% // use // Tool context.put("check_home", state .getAttribute(STATE_TOOL_HOME_SELECTED)); context .put("emailId", state .getAttribute(STATE_TOOL_EMAIL_ADDRESS)); context.put("serverName", ServerConfigurationService .getServerName()); context.put("include", new Boolean(siteInfo.include)); return (String) getContext(data).get("template") + TEMPLATE[42]; case 43: /* * buildContextForTemplate chef_siteInfo-editClass.vm * */ bar = new MenuImpl(portlet, data, (String) state .getAttribute(STATE_ACTION)); if (SiteService.allowAddSite(null)) { bar.add(new MenuEntry(rb.getString("java.addclasses"), "doMenu_siteInfo_addClass")); } context.put("menu", bar); context.put("siteTitle", site.getTitle()); coursesIntoContext(state, context, site); return (String) getContext(data).get("template") + TEMPLATE[43]; case 44: /* * buildContextForTemplate chef_siteInfo-addCourseConfirm.vm * */ context.put("siteTitle", site.getTitle()); coursesIntoContext(state, context, site); context.put("providerAddCourses", state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN)); if (state.getAttribute(STATE_CM_SELECTED_SECTIONS) != null) { context.put("cmSelectedSections", state.getAttribute(STATE_CM_SELECTED_SECTIONS)); } if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { int addNumber = ((Integer) state .getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)) .intValue() - 1; context.put("manualAddNumber", new Integer(addNumber)); context.put("requestFields", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); context.put("backIndex", "37"); } else { context.put("backIndex", "36"); } // those manual inputs context.put("form_requiredFields", sectionFieldProvider .getRequiredFields()); context.put("fieldValues", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); return (String) getContext(data).get("template") + TEMPLATE[44]; // htripath - import materials from classic case 45: /* * buildContextForTemplate chef_siteInfo-importMtrlMaster.vm * */ return (String) getContext(data).get("template") + TEMPLATE[45]; case 46: /* * buildContextForTemplate chef_siteInfo-importMtrlCopy.vm * */ // this is for list display in listbox context .put("allZipSites", state .getAttribute(ALL_ZIP_IMPORT_SITES)); context.put("finalZipSites", state .getAttribute(FINAL_ZIP_IMPORT_SITES)); // zip file // context.put("zipreffile",state.getAttribute(CLASSIC_ZIP_FILE_NAME)); return (String) getContext(data).get("template") + TEMPLATE[46]; case 47: /* * buildContextForTemplate chef_siteInfo-importMtrlCopyConfirm.vm * */ context.put("finalZipSites", state .getAttribute(FINAL_ZIP_IMPORT_SITES)); return (String) getContext(data).get("template") + TEMPLATE[47]; case 48: /* * buildContextForTemplate chef_siteInfo-importMtrlCopyConfirm.vm * */ context.put("finalZipSites", state .getAttribute(FINAL_ZIP_IMPORT_SITES)); return (String) getContext(data).get("template") + TEMPLATE[48]; case 49: /* * buildContextForTemplate chef_siteInfo-group.vm * */ context.put("site", site); bar = new MenuImpl(portlet, data, (String) state .getAttribute(STATE_ACTION)); if (SiteService.allowUpdateSite(site.getId()) || SiteService.allowUpdateGroupMembership(site.getId())) { bar.add(new MenuEntry(rb.getString("java.newgroup"), "doGroup_new")); } context.put("menu", bar); // the group list sortedBy = (String) state.getAttribute(SORTED_BY); sortedAsc = (String) state.getAttribute(SORTED_ASC); if (sortedBy != null) context.put("currentSortedBy", sortedBy); if (sortedAsc != null) context.put("currentSortAsc", sortedAsc); // only show groups created by WSetup tool itself Collection groups = (Collection) site.getGroups(); List groupsByWSetup = new Vector(); for (Iterator gIterator = groups.iterator(); gIterator.hasNext();) { Group gNext = (Group) gIterator.next(); String gProp = gNext.getProperties().getProperty( GROUP_PROP_WSETUP_CREATED); if (gProp != null && gProp.equals(Boolean.TRUE.toString())) { groupsByWSetup.add(gNext); } } if (sortedBy != null && sortedAsc != null) { context.put("groups", new SortedIterator(groupsByWSetup .iterator(), new SiteComparator(sortedBy, sortedAsc))); } return (String) getContext(data).get("template") + TEMPLATE[49]; case 50: /* * buildContextForTemplate chef_siteInfo-groupedit.vm * */ Group g = getStateGroup(state); if (g != null) { context.put("group", g); context.put("newgroup", Boolean.FALSE); } else { context.put("newgroup", Boolean.TRUE); } if (state.getAttribute(STATE_GROUP_TITLE) != null) { context.put("title", state.getAttribute(STATE_GROUP_TITLE)); } if (state.getAttribute(STATE_GROUP_DESCRIPTION) != null) { context.put("description", state .getAttribute(STATE_GROUP_DESCRIPTION)); } Iterator siteMembers = new SortedIterator(getParticipantList(state) .iterator(), new SiteComparator(SORTED_BY_PARTICIPANT_NAME, Boolean.TRUE.toString())); if (siteMembers != null && siteMembers.hasNext()) { context.put("generalMembers", siteMembers); } Set groupMembersSet = (Set) state.getAttribute(STATE_GROUP_MEMBERS); if (state.getAttribute(STATE_GROUP_MEMBERS) != null) { context.put("groupMembers", new SortedIterator(groupMembersSet .iterator(), new SiteComparator(SORTED_BY_MEMBER_NAME, Boolean.TRUE.toString()))); } context.put("groupMembersClone", groupMembersSet); context.put("userDirectoryService", UserDirectoryService .getInstance()); return (String) getContext(data).get("template") + TEMPLATE[50]; case 51: /* * buildContextForTemplate chef_siteInfo-groupDeleteConfirm.vm * */ context.put("site", site); context .put("removeGroupIds", new ArrayList(Arrays .asList((String[]) state .getAttribute(STATE_GROUP_REMOVE)))); return (String) getContext(data).get("template") + TEMPLATE[51]; case 53: { /* * build context for chef_site-findCourse.vm */ AcademicSession t = (AcademicSession) state .getAttribute(STATE_TERM_SELECTED); List cmLevels = (List) state.getAttribute(STATE_CM_LEVELS), selections = (List) state .getAttribute(STATE_CM_LEVEL_SELECTIONS); if (cmLevels == null) { cmLevels = getCMLevelLabels(); } SectionObject selectedSect = (SectionObject) state .getAttribute(STATE_CM_SELECTED_SECTION); List<SectionObject> requestedSections = (List<SectionObject>) state .getAttribute(STATE_CM_REQUESTED_SECTIONS); if (courseManagementIsImplemented() && cms != null) { context.put("cmsAvailable", new Boolean(true)); } if (cms == null || !courseManagementIsImplemented() || cmLevels == null || cmLevels.size() < 1) { // TODO: redirect to manual entry: case #37 } else { Object levelOpts[] = new Object[cmLevels.size()]; int numSelections = 0; if (selections != null) numSelections = selections.size(); // populate options for dropdown lists switch (numSelections) { /* * execution will fall through these statements based on number * of selections already made */ case 3: // intentionally blank case 2: levelOpts[2] = getCMSections((String) selections.get(1)); case 1: levelOpts[1] = getCMCourseOfferings((String) selections .get(0), t.getEid()); default: levelOpts[0] = getCMSubjects(); } context.put("cmLevelOptions", Arrays.asList(levelOpts)); } if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) { context.put("selectedProviderCourse", state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN)); } if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { int courseInd = ((Integer) state .getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)) .intValue(); context.put("manualAddNumber", new Integer(courseInd - 1)); context.put("manualAddFields", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); } context.put("term", (AcademicSession) state .getAttribute(STATE_TERM_SELECTED)); context.put("cmLevels", cmLevels); context.put("cmLevelSelections", selections); context.put("selectedCourse", selectedSect); context.put("cmRequestedSections", requestedSections); if (state.getAttribute(STATE_SITE_MODE).equals(SITE_MODE_SITEINFO)) { context.put("editSite", Boolean.TRUE); context.put("cmSelectedSections", state.getAttribute(STATE_CM_SELECTED_SECTIONS)); } if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITESETUP)) { if (state.getAttribute(STATE_TERM_COURSE_LIST) != null) { context.put("backIndex", "36"); } else { context.put("backIndex", "1"); } } else if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITEINFO)) { context.put("backIndex", "36"); } + context.put("authzGroupService", AuthzGroupService.getInstance()); return (String) getContext(data).get("template") + TEMPLATE[53]; } } // should never be reached return (String) getContext(data).get("template") + TEMPLATE[0]; } // buildContextForTemplate /** * Launch the Page Order Helper Tool -- for ordering, adding and customizing * pages * * @see case 12 * */ public void doPageOrderHelper(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // pass in the siteId of the site to be ordered (so it can configure // sites other then the current site) SessionManager.getCurrentToolSession().setAttribute( HELPER_ID + ".siteId", ((Site) getStateSite(state)).getId()); // launch the helper startHelper(data.getRequest(), "sakai-site-pageorder-helper"); } // htripath: import materials from classic /** * Master import -- for import materials from a file * * @see case 45 * */ public void doAttachmentsMtrlFrmFile(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // state.setAttribute(FILE_UPLOAD_MAX_SIZE, // ServerConfigurationService.getString("content.upload.max", "1")); state.setAttribute(STATE_TEMPLATE_INDEX, "45"); } // doImportMtrlFrmFile /** * Handle File Upload request * * @see case 46 * @throws Exception */ public void doUpload_Mtrl_Frm_File(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); List allzipList = new Vector(); List finalzipList = new Vector(); List directcopyList = new Vector(); // see if the user uploaded a file FileItem fileFromUpload = null; String fileName = null; fileFromUpload = data.getParameters().getFileItem("file"); String max_file_size_mb = ServerConfigurationService.getString( "content.upload.max", "1"); int max_bytes = 1024 * 1024; try { max_bytes = Integer.parseInt(max_file_size_mb) * 1024 * 1024; } catch (Exception e) { // if unable to parse an integer from the value // in the properties file, use 1 MB as a default max_file_size_mb = "1"; max_bytes = 1024 * 1024; } if (fileFromUpload == null) { // "The user submitted a file to upload but it was too big!" addAlert(state, rb.getString("importFile.size") + " " + max_file_size_mb + "MB " + rb.getString("importFile.exceeded")); } else if (fileFromUpload.getFileName() == null || fileFromUpload.getFileName().length() == 0) { addAlert(state, rb.getString("importFile.choosefile")); } else { byte[] fileData = fileFromUpload.get(); if (fileData.length >= max_bytes) { addAlert(state, rb.getString("size") + " " + max_file_size_mb + "MB " + rb.getString("importFile.exceeded")); } else if (fileData.length > 0) { if (importService.isValidArchive(fileData)) { ImportDataSource importDataSource = importService .parseFromFile(fileData); Log.info("chef", "Getting import items from manifest."); List lst = importDataSource.getItemCategories(); if (lst != null && lst.size() > 0) { Iterator iter = lst.iterator(); while (iter.hasNext()) { ImportMetadata importdata = (ImportMetadata) iter .next(); // Log.info("chef","Preparing import // item '" + importdata.getId() + "'"); if ((!importdata.isMandatory()) && (importdata.getFileName() .endsWith(".xml"))) { allzipList.add(importdata); } else { directcopyList.add(importdata); } } } // set Attributes state.setAttribute(ALL_ZIP_IMPORT_SITES, allzipList); state.setAttribute(FINAL_ZIP_IMPORT_SITES, finalzipList); state.setAttribute(DIRECT_ZIP_IMPORT_SITES, directcopyList); state.setAttribute(CLASSIC_ZIP_FILE_NAME, fileName); state.setAttribute(IMPORT_DATA_SOURCE, importDataSource); state.setAttribute(STATE_TEMPLATE_INDEX, "46"); } else { // uploaded file is not a valid archive } } } } // doImportMtrlFrmFile /** * Handle addition to list request * * @param data */ public void doAdd_MtrlSite(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); List zipList = (List) state.getAttribute(ALL_ZIP_IMPORT_SITES); List fnlList = (List) state.getAttribute(FINAL_ZIP_IMPORT_SITES); List importSites = new ArrayList(Arrays.asList(params .getStrings("addImportSelected"))); for (int i = 0; i < importSites.size(); i++) { String value = (String) importSites.get(i); fnlList.add(removeItems(value, zipList)); } state.setAttribute(ALL_ZIP_IMPORT_SITES, zipList); state.setAttribute(FINAL_ZIP_IMPORT_SITES, fnlList); state.setAttribute(STATE_TEMPLATE_INDEX, "46"); } // doAdd_MtrlSite /** * Helper class for Add and remove * * @param value * @param items * @return */ public ImportMetadata removeItems(String value, List items) { ImportMetadata result = null; for (int i = 0; i < items.size(); i++) { ImportMetadata item = (ImportMetadata) items.get(i); if (value.equals(item.getId())) { result = (ImportMetadata) items.remove(i); break; } } return result; } /** * Handle the request for remove * * @param data */ public void doRemove_MtrlSite(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); List zipList = (List) state.getAttribute(ALL_ZIP_IMPORT_SITES); List fnlList = (List) state.getAttribute(FINAL_ZIP_IMPORT_SITES); List importSites = new ArrayList(Arrays.asList(params .getStrings("removeImportSelected"))); for (int i = 0; i < importSites.size(); i++) { String value = (String) importSites.get(i); zipList.add(removeItems(value, fnlList)); } state.setAttribute(ALL_ZIP_IMPORT_SITES, zipList); state.setAttribute(FINAL_ZIP_IMPORT_SITES, fnlList); state.setAttribute(STATE_TEMPLATE_INDEX, "46"); } // doAdd_MtrlSite /** * Handle the request for copy * * @param data */ public void doCopyMtrlSite(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); List fnlList = (List) state.getAttribute(FINAL_ZIP_IMPORT_SITES); state.setAttribute(FINAL_ZIP_IMPORT_SITES, fnlList); state.setAttribute(STATE_TEMPLATE_INDEX, "47"); } // doCopy_MtrlSite /** * Handle the request for Save * * @param data * @throws ImportException */ public void doSaveMtrlSite(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); String siteId = (String) state.getAttribute(STATE_SITE_INSTANCE_ID); List fnlList = (List) state.getAttribute(FINAL_ZIP_IMPORT_SITES); List directList = (List) state.getAttribute(DIRECT_ZIP_IMPORT_SITES); ImportDataSource importDataSource = (ImportDataSource) state .getAttribute(IMPORT_DATA_SOURCE); // combine the selected import items with the mandatory import items fnlList.addAll(directList); Log.info("chef", "doSaveMtrlSite() about to import " + fnlList.size() + " top level items"); Log.info("chef", "doSaveMtrlSite() the importDataSource is " + importDataSource.getClass().getName()); if (importDataSource instanceof SakaiArchive) { Log.info("chef", "doSaveMtrlSite() our data source is a Sakai format"); ((SakaiArchive) importDataSource).buildSourceFolder(fnlList); Log.info("chef", "doSaveMtrlSite() source folder is " + ((SakaiArchive) importDataSource).getSourceFolder()); ArchiveService.merge(((SakaiArchive) importDataSource) .getSourceFolder(), siteId, null); } else { importService.doImportItems(importDataSource .getItemsForCategories(fnlList), siteId); } // remove attributes state.removeAttribute(ALL_ZIP_IMPORT_SITES); state.removeAttribute(FINAL_ZIP_IMPORT_SITES); state.removeAttribute(DIRECT_ZIP_IMPORT_SITES); state.removeAttribute(CLASSIC_ZIP_FILE_NAME); state.removeAttribute(SESSION_CONTEXT_ID); state.removeAttribute(IMPORT_DATA_SOURCE); state.setAttribute(STATE_TEMPLATE_INDEX, "48"); // state.setAttribute(STATE_TEMPLATE_INDEX, "28"); } // doSave_MtrlSite public void doSaveMtrlSiteMsg(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // remove attributes state.removeAttribute(ALL_ZIP_IMPORT_SITES); state.removeAttribute(FINAL_ZIP_IMPORT_SITES); state.removeAttribute(DIRECT_ZIP_IMPORT_SITES); state.removeAttribute(CLASSIC_ZIP_FILE_NAME); state.removeAttribute(SESSION_CONTEXT_ID); state.setAttribute(STATE_TEMPLATE_INDEX, "12"); } // htripath-end /** * Handle the site search request. */ public void doSite_search(RunData data, Context context) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // read the search form field into the state object String search = StringUtil.trimToNull(data.getParameters().getString( FORM_SEARCH)); // set the flag to go to the prev page on the next list if (search == null) { state.removeAttribute(STATE_SEARCH); } else { state.setAttribute(STATE_SEARCH, search); } } // doSite_search /** * Handle a Search Clear request. */ public void doSite_search_clear(RunData data, Context context) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // clear the search state.removeAttribute(STATE_SEARCH); } // doSite_search_clear private void coursesIntoContext(SessionState state, Context context, Site site) { List providerCourseList = getProviderCourseList(StringUtil .trimToNull(getExternalRealmId(state))); if (providerCourseList != null && providerCourseList.size() > 0) { state.setAttribute(SITE_PROVIDER_COURSE_LIST, providerCourseList); String sectionTitleString = ""; for(int i = 0; i < providerCourseList.size(); i++) { String sectionId = (String) providerCourseList.get(i); try { Section s = cms.getSection(sectionId); sectionTitleString = (i>1)?sectionTitleString + "<br />" + s.getTitle():s.getTitle(); } catch (Exception e) { M_log.warn("coursesIntoContext " + e.getMessage() + " sectionId=" + sectionId); } } context.put("providedSectionTitle", sectionTitleString); context.put("providerCourseList", providerCourseList); } // put manual requested courses into context courseListFromStringIntoContext(state, context, site, STATE_CM_REQUESTED_SECTIONS, STATE_CM_REQUESTED_SECTIONS, "cmRequestedCourseList"); // put manual requested courses into context courseListFromStringIntoContext(state, context, site, PROP_SITE_REQUEST_COURSE, SITE_MANUAL_COURSE_LIST, "manualCourseList"); } private void courseListFromStringIntoContext(SessionState state, Context context, Site site, String site_prop_name, String state_attribute_string, String context_string) { String courseListString = StringUtil.trimToNull(site.getProperties().getProperty(site_prop_name)); if (courseListString != null) { List courseList = new Vector(); if (courseListString.indexOf("+") != -1) { courseList = new ArrayList(Arrays.asList(courseListString.split("\\+"))); } else { courseList.add(courseListString); } if (state_attribute_string.equals(STATE_CM_REQUESTED_SECTIONS)) { // need to construct the list of SectionObjects List<SectionObject> soList = new Vector(); for (int i=0; i<courseList.size();i++) { String courseEid = (String) courseList.get(i); try { Section s = cms.getSection(courseEid); if (s!=null) soList.add(new SectionObject(s)); } catch (Exception e) { M_log.warn(e.getMessage() + courseEid); } } if (soList.size() > 0) state.setAttribute(STATE_CM_REQUESTED_SECTIONS, soList); } else { // the list is of String objects state.setAttribute(state_attribute_string, courseList); } } context.put(context_string, state.getAttribute(state_attribute_string)); } /** * buildInstructorSectionsList Build the CourseListItem list for this * Instructor for the requested Term * */ private void buildInstructorSectionsList(SessionState state, ParameterParser params, Context context) { // Site information // The sections of the specified term having this person as Instructor context.put("providerCourseSectionList", state .getAttribute("providerCourseSectionList")); context.put("manualCourseSectionList", state .getAttribute("manualCourseSectionList")); context.put("term", (AcademicSession) state .getAttribute(STATE_TERM_SELECTED)); setTermListForContext(context, state, true); //-> future terms only context.put(STATE_TERM_COURSE_LIST, state .getAttribute(STATE_TERM_COURSE_LIST)); context.put("tlang", rb); } // buildInstructorSectionsList /** * getProviderCourseList a course site/realm id in one of three formats, for * a single section, for multiple sections of the same course, or for a * cross-listing having multiple courses. getProviderCourseList parses a * realm id into year, term, campus_code, catalog_nbr, section components. * * @param id * is a String representation of the course realm id (external * id). */ private List getProviderCourseList(String id) { Vector rv = new Vector(); if (id == null || id == NULL_STRING) { return rv; } // Break Provider Id into course id parts String[] courseIds = groupProvider.unpackId(id); // Iterate through course ids for (int i=0; i<courseIds.length; i++) { String courseId = (String) courseIds[i]; rv.add(courseId); } return rv; } // getProviderCourseList /** * {@inheritDoc} */ protected int sizeResources(SessionState state) { int size = 0; String search = ""; String userId = SessionManager.getCurrentSessionUserId(); // if called from the site list page if (((String) state.getAttribute(STATE_TEMPLATE_INDEX)).equals("0")) { search = StringUtil.trimToNull((String) state .getAttribute(STATE_SEARCH)); if (SecurityService.isSuperUser()) { // admin-type of user String view = (String) state.getAttribute(STATE_VIEW_SELECTED); if (view != null) { if (view.equals(rb.getString("java.allmy"))) { // search for non-user sites, using // the criteria size = SiteService .countSites( org.sakaiproject.site.api.SiteService.SelectionType.NON_USER, null, search, null); } else if (view.equals(rb.getString("java.my"))) { // search for a specific user site // for the particular user id in the // criteria - exact match only try { SiteService.getSite(SiteService .getUserSiteId(search)); size++; } catch (IdUnusedException e) { } } else if (view.equalsIgnoreCase(rb .getString("java.gradtools"))) { // search for gradtools sites size = SiteService .countSites( org.sakaiproject.site.api.SiteService.SelectionType.NON_USER, state .getAttribute(GRADTOOLS_SITE_TYPES), search, null); } else { // search for specific type of sites size = SiteService .countSites( org.sakaiproject.site.api.SiteService.SelectionType.NON_USER, view, search, null); } } } else { Site userWorkspaceSite = null; try { userWorkspaceSite = SiteService.getSite(SiteService .getUserSiteId(userId)); } catch (IdUnusedException e) { M_log.warn("Cannot find user " + SessionManager.getCurrentSessionUserId() + "'s My Workspace site."); } String view = (String) state.getAttribute(STATE_VIEW_SELECTED); if (view != null) { if (view.equals(rb.getString("java.allmy"))) { view = null; // add my workspace if any if (userWorkspaceSite != null) { if (search != null) { if (userId.indexOf(search) != -1) { size++; } } else { size++; } } size += SiteService .countSites( org.sakaiproject.site.api.SiteService.SelectionType.ACCESS, null, search, null); } else if (view.equalsIgnoreCase(rb .getString("java.gradtools"))) { // search for gradtools sites size += SiteService .countSites( org.sakaiproject.site.api.SiteService.SelectionType.ACCESS, state .getAttribute(GRADTOOLS_SITE_TYPES), search, null); } else { // search for specific type of sites size += SiteService .countSites( org.sakaiproject.site.api.SiteService.SelectionType.ACCESS, view, search, null); } } } } // for SiteInfo list page else if (state.getAttribute(STATE_TEMPLATE_INDEX).toString().equals( "12")) { Collection l = (Collection) state.getAttribute(STATE_PARTICIPANT_LIST); size = (l != null) ? l.size() : 0; } return size; } // sizeResources /** * {@inheritDoc} */ protected List readResourcesPage(SessionState state, int first, int last) { String search = StringUtil.trimToNull((String) state .getAttribute(STATE_SEARCH)); // if called from the site list page if (((String) state.getAttribute(STATE_TEMPLATE_INDEX)).equals("0")) { // get sort type SortType sortType = null; String sortBy = (String) state.getAttribute(SORTED_BY); boolean sortAsc = (new Boolean((String) state .getAttribute(SORTED_ASC))).booleanValue(); if (sortBy.equals(SortType.TITLE_ASC.toString())) { sortType = sortAsc ? SortType.TITLE_ASC : SortType.TITLE_DESC; } else if (sortBy.equals(SortType.TYPE_ASC.toString())) { sortType = sortAsc ? SortType.TYPE_ASC : SortType.TYPE_DESC; } else if (sortBy.equals(SortType.CREATED_BY_ASC.toString())) { sortType = sortAsc ? SortType.CREATED_BY_ASC : SortType.CREATED_BY_DESC; } else if (sortBy.equals(SortType.CREATED_ON_ASC.toString())) { sortType = sortAsc ? SortType.CREATED_ON_ASC : SortType.CREATED_ON_DESC; } else if (sortBy.equals(SortType.PUBLISHED_ASC.toString())) { sortType = sortAsc ? SortType.PUBLISHED_ASC : SortType.PUBLISHED_DESC; } if (SecurityService.isSuperUser()) { // admin-type of user String view = (String) state.getAttribute(STATE_VIEW_SELECTED); if (view != null) { if (view.equals(rb.getString("java.allmy"))) { // search for non-user sites, using the // criteria return SiteService .getSites( org.sakaiproject.site.api.SiteService.SelectionType.NON_USER, null, search, null, sortType, new PagingPosition(first, last)); } else if (view.equalsIgnoreCase(rb.getString("java.my"))) { // search for a specific user site for // the particular user id in the // criteria - exact match only List rv = new Vector(); try { Site userSite = SiteService.getSite(SiteService .getUserSiteId(search)); rv.add(userSite); } catch (IdUnusedException e) { } return rv; } else if (view.equalsIgnoreCase(rb .getString("java.gradtools"))) { // search for gradtools sites return SiteService .getSites( org.sakaiproject.site.api.SiteService.SelectionType.NON_USER, state .getAttribute(GRADTOOLS_SITE_TYPES), search, null, sortType, new PagingPosition(first, last)); } else { // search for a specific site return SiteService .getSites( org.sakaiproject.site.api.SiteService.SelectionType.ANY, view, search, null, sortType, new PagingPosition(first, last)); } } } else { List rv = new Vector(); Site userWorkspaceSite = null; String userId = SessionManager.getCurrentSessionUserId(); try { userWorkspaceSite = SiteService.getSite(SiteService .getUserSiteId(userId)); } catch (IdUnusedException e) { M_log.warn("Cannot find user " + SessionManager.getCurrentSessionUserId() + "'s My Workspace site."); } String view = (String) state.getAttribute(STATE_VIEW_SELECTED); if (view != null) { if (view.equals(rb.getString("java.allmy"))) { view = null; // add my workspace if any if (userWorkspaceSite != null) { if (search != null) { if (userId.indexOf(search) != -1) { rv.add(userWorkspaceSite); } } else { rv.add(userWorkspaceSite); } } rv .addAll(SiteService .getSites( org.sakaiproject.site.api.SiteService.SelectionType.ACCESS, null, search, null, sortType, new PagingPosition(first, last))); } else if (view.equalsIgnoreCase(rb .getString("java.gradtools"))) { // search for a specific user site for // the particular user id in the // criteria - exact match only rv .addAll(SiteService .getSites( org.sakaiproject.site.api.SiteService.SelectionType.ACCESS, state .getAttribute(GRADTOOLS_SITE_TYPES), search, null, sortType, new PagingPosition(first, last))); } else { rv .addAll(SiteService .getSites( org.sakaiproject.site.api.SiteService.SelectionType.ACCESS, view, search, null, sortType, new PagingPosition(first, last))); } } return rv; } } // if in Site Info list view else if (state.getAttribute(STATE_TEMPLATE_INDEX).toString().equals( "12")) { List participants = (state.getAttribute(STATE_PARTICIPANT_LIST) != null) ? collectionToList((Collection) state.getAttribute(STATE_PARTICIPANT_LIST)): new Vector(); String sortedBy = (String) state.getAttribute(SORTED_BY); String sortedAsc = (String) state.getAttribute(SORTED_ASC); Iterator sortedParticipants = null; if (sortedBy != null) { sortedParticipants = new SortedIterator(participants .iterator(), new SiteComparator(sortedBy, sortedAsc)); participants.clear(); while (sortedParticipants.hasNext()) { participants.add(sortedParticipants.next()); } } PagingPosition page = new PagingPosition(first, last); page.validate(participants.size()); participants = participants.subList(page.getFirst() - 1, page.getLast()); return participants; } return null; } // readResourcesPage /** * get the selected tool ids from import sites */ private boolean select_import_tools(ParameterParser params, SessionState state) { // has the user selected any tool for importing? boolean anyToolSelected = false; Hashtable importTools = new Hashtable(); // the tools for current site List selectedTools = (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); // String // toolId's for (int i = 0; i < selectedTools.size(); i++) { // any tools chosen from import sites? String toolId = (String) selectedTools.get(i); if (params.getStrings(toolId) != null) { importTools.put(toolId, new ArrayList(Arrays.asList(params .getStrings(toolId)))); if (!anyToolSelected) { anyToolSelected = true; } } } state.setAttribute(STATE_IMPORT_SITE_TOOL, importTools); return anyToolSelected; } // select_import_tools /** * Is it from the ENW edit page? * * @return ture if the process went through the ENW page; false, otherwise */ private boolean fromENWModifyView(SessionState state) { boolean fromENW = false; List oTools = (List) state .getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST); List toolList = (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); for (int i = 0; i < toolList.size() && !fromENW; i++) { String toolId = (String) toolList.get(i); if (toolId.equals("sakai.mailbox") || toolId.indexOf("sakai.news") != -1 || toolId.indexOf("sakai.iframe") != -1) { if (oTools == null) { // if during site creation proces fromENW = true; } else if (!oTools.contains(toolId)) { // if user is adding either EmailArchive tool, News tool or // Web Content tool, go to the Customize page for the tool fromENW = true; } } } return fromENW; } /** * doNew_site is called when the Site list tool bar New... button is clicked * */ public void doNew_site(RunData data) throws Exception { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // start clean cleanState(state); List siteTypes = (List) state.getAttribute(STATE_SITE_TYPES); if (siteTypes != null) { if (siteTypes.size() == 1) { String siteType = (String) siteTypes.get(0); if (!siteType.equals(ServerConfigurationService.getString( "courseSiteType", (String) state.getAttribute(STATE_COURSE_SITE_TYPE)))) { // if only one site type is allowed and the type isn't // course type // skip the select site type step setNewSiteType(state, siteType); state.setAttribute(STATE_TEMPLATE_INDEX, "2"); } else { state.setAttribute(STATE_TEMPLATE_INDEX, "1"); } } else { state.setAttribute(STATE_TEMPLATE_INDEX, "1"); } } } // doNew_site /** * doMenu_site_delete is called when the Site list tool bar Delete button is * clicked * */ public void doMenu_site_delete(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); if (params.getStrings("selectedMembers") == null) { addAlert(state, rb.getString("java.nosites")); state.setAttribute(STATE_TEMPLATE_INDEX, "0"); return; } String[] removals = (String[]) params.getStrings("selectedMembers"); state.setAttribute(STATE_SITE_REMOVALS, removals); // present confirm delete template state.setAttribute(STATE_TEMPLATE_INDEX, "8"); } // doMenu_site_delete public void doSite_delete_confirmed(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); if (params.getStrings("selectedMembers") == null) { M_log .warn("SiteAction.doSite_delete_confirmed selectedMembers null"); state.setAttribute(STATE_TEMPLATE_INDEX, "0"); // return to the // site list return; } List chosenList = new ArrayList(Arrays.asList(params .getStrings("selectedMembers"))); // Site id's of checked // sites if (!chosenList.isEmpty()) { for (ListIterator i = chosenList.listIterator(); i.hasNext();) { String id = (String) i.next(); String site_title = NULL_STRING; try { site_title = SiteService.getSite(id).getTitle(); } catch (IdUnusedException e) { M_log .warn("SiteAction.doSite_delete_confirmed - IdUnusedException " + id); addAlert(state, rb.getString("java.sitewith") + " " + id + " " + rb.getString("java.couldnt") + " "); } if (SiteService.allowRemoveSite(id)) { try { Site site = SiteService.getSite(id); site_title = site.getTitle(); SiteService.removeSite(site); } catch (IdUnusedException e) { M_log .warn("SiteAction.doSite_delete_confirmed - IdUnusedException " + id); addAlert(state, rb.getString("java.sitewith") + " " + site_title + "(" + id + ") " + rb.getString("java.couldnt") + " "); } catch (PermissionException e) { M_log .warn("SiteAction.doSite_delete_confirmed - PermissionException, site " + site_title + "(" + id + ")."); addAlert(state, site_title + " " + rb.getString("java.dontperm") + " "); } } else { M_log .warn("SiteAction.doSite_delete_confirmed - allowRemoveSite failed for site " + id); addAlert(state, site_title + " " + rb.getString("java.dontperm") + " "); } } } state.setAttribute(STATE_TEMPLATE_INDEX, "0"); // return to the site // list // TODO: hard coding this frame id is fragile, portal dependent, and // needs to be fixed -ggolden // schedulePeerFrameRefresh("sitenav"); scheduleTopRefresh(); } // doSite_delete_confirmed /** * get the Site object based on SessionState attribute values * * @return Site object related to current state; null if no such Site object * could be found */ protected Site getStateSite(SessionState state) { Site site = null; if (state.getAttribute(STATE_SITE_INSTANCE_ID) != null) { try { site = SiteService.getSite((String) state .getAttribute(STATE_SITE_INSTANCE_ID)); } catch (Exception ignore) { } } return site; } // getStateSite /** * get the Group object based on SessionState attribute values * * @return Group object related to current state; null if no such Group * object could be found */ protected Group getStateGroup(SessionState state) { Group group = null; Site site = getStateSite(state); if (site != null && state.getAttribute(STATE_GROUP_INSTANCE_ID) != null) { try { group = site.getGroup((String) state .getAttribute(STATE_GROUP_INSTANCE_ID)); } catch (Exception ignore) { } } return group; } // getStateGroup /** * do called when "eventSubmit_do" is in the request parameters to c is * called from site list menu entry Revise... to get a locked site as * editable and to go to the correct template to begin DB version of writes * changes to disk at site commit whereas XML version writes at server * shutdown */ public void doGet_site(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); // check form filled out correctly if (params.getStrings("selectedMembers") == null) { addAlert(state, rb.getString("java.nosites")); state.setAttribute(STATE_TEMPLATE_INDEX, "0"); return; } List chosenList = new ArrayList(Arrays.asList(params .getStrings("selectedMembers"))); // Site id's of checked // sites String siteId = ""; if (!chosenList.isEmpty()) { if (chosenList.size() != 1) { addAlert(state, rb.getString("java.please")); state.setAttribute(STATE_TEMPLATE_INDEX, "0"); return; } siteId = (String) chosenList.get(0); getReviseSite(state, siteId); state.setAttribute(SORTED_BY, SORTED_BY_PARTICIPANT_NAME); state.setAttribute(SORTED_ASC, Boolean.TRUE.toString()); } // reset the paging info resetPaging(state); if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITESETUP)) { state.setAttribute(STATE_PAGESIZE_SITESETUP, state .getAttribute(STATE_PAGESIZE)); } Hashtable h = (Hashtable) state.getAttribute(STATE_PAGESIZE_SITEINFO); if (!h.containsKey(siteId)) { // when first entered Site Info, set the participant list size to // 200 as default state.setAttribute(STATE_PAGESIZE, new Integer(200)); // update h.put(siteId, new Integer(200)); state.setAttribute(STATE_PAGESIZE_SITEINFO, h); } else { // restore the page size in site info tool state.setAttribute(STATE_PAGESIZE, h.get(siteId)); } } // doGet_site /** * do called when "eventSubmit_do" is in the request parameters to c */ public void doMenu_site_reuse(RunData data) throws Exception { // called from chef_site-list.vm after a site has been selected from // list // create a new Site object based on selected Site object and put in // state // SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_TEMPLATE_INDEX, "1"); } // doMenu_site_reuse /** * do called when "eventSubmit_do" is in the request parameters to c */ public void doMenu_site_revise(RunData data) throws Exception { // called from chef_site-list.vm after a site has been selected from // list // get site as Site object, check SiteCreationStatus and SiteType of // site, put in state, and set STATE_TEMPLATE_INDEX correctly // set mode to state_mode_site_type SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_TEMPLATE_INDEX, "1"); } // doMenu_site_revise /** * doView_sites is called when "eventSubmit_doView_sites" is in the request * parameters */ public void doView_sites(RunData data) throws Exception { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); state.setAttribute(STATE_VIEW_SELECTED, params.getString("view")); state.setAttribute(STATE_TEMPLATE_INDEX, "0"); resetPaging(state); } // doView_sites /** * do called when "eventSubmit_do" is in the request parameters to c */ public void doView(RunData data) throws Exception { // called from chef_site-list.vm with a select option to build query of // sites // // SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_TEMPLATE_INDEX, "1"); } // doView /** * do called when "eventSubmit_do" is in the request parameters to c */ public void doSite_type(RunData data) { /* * for measuring how long it takes to load sections java.util.Date date = * new java.util.Date(); M_log.debug("***1. start preparing * section:"+date); */ SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); int index = Integer.valueOf(params.getString("template-index")) .intValue(); actionForTemplate("continue", index, params, state); String type = StringUtil.trimToNull(params.getString("itemType")); int totalSteps = 0; if (type == null) { addAlert(state, rb.getString("java.select") + " "); } else { setNewSiteType(state, type); if (type.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { User user = UserDirectoryService.getCurrentUser(); String currentUserId = user.getEid(); String userId = params.getString("userId"); if (userId == null || "".equals(userId)) { userId = currentUserId; } else { // implies we are trying to pick sections owned by other // users. Currently "select section by user" page only // take one user per sitte request - daisy's note 1 ArrayList<String> list = new ArrayList(); list.add(userId); state.setAttribute(STATE_CM_AUTHORIZER_LIST, list); } state.setAttribute(STATE_INSTRUCTOR_SELECTED, userId); String academicSessionEid = params.getString("selectTerm"); AcademicSession t = cms.getAcademicSession(academicSessionEid); state.setAttribute(STATE_TERM_SELECTED, t); if (t != null) { List sections = prepareCourseAndSectionListing(userId, t .getEid(), state); isFutureTermSelected(state); if (sections != null && sections.size() > 0) { state.setAttribute(STATE_TERM_COURSE_LIST, sections); state.setAttribute(STATE_TEMPLATE_INDEX, "36"); state.setAttribute(STATE_AUTO_ADD, Boolean.TRUE); } else { state.removeAttribute(STATE_TERM_COURSE_LIST); Boolean skipCourseSectionSelection = ServerConfigurationService.getBoolean("wsetup.skipCourseSectionSelection", Boolean.FALSE); if (!skipCourseSectionSelection.booleanValue() && courseManagementIsImplemented()) { state.setAttribute(STATE_TEMPLATE_INDEX, "53"); } else { state.setAttribute(STATE_TEMPLATE_INDEX, "37"); } } } else { // not course type state.setAttribute(STATE_TEMPLATE_INDEX, "37"); totalSteps = 5; } } else if (type.equals("project")) { totalSteps = 4; state.setAttribute(STATE_TEMPLATE_INDEX, "2"); } else if (type.equals(SITE_TYPE_GRADTOOLS_STUDENT)) { // if a GradTools site use pre-defined site info and exclude // from public listing SiteInfo siteInfo = new SiteInfo(); if (state.getAttribute(STATE_SITE_INFO) != null) { siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); } User currentUser = UserDirectoryService.getCurrentUser(); siteInfo.title = rb.getString("java.grad") + " - " + currentUser.getId(); siteInfo.description = rb.getString("java.gradsite") + " " + currentUser.getDisplayName(); siteInfo.short_description = rb.getString("java.grad") + " - " + currentUser.getId(); siteInfo.include = false; state.setAttribute(STATE_SITE_INFO, siteInfo); // skip directly to confirm creation of site state.setAttribute(STATE_TEMPLATE_INDEX, "42"); } else { state.setAttribute(STATE_TEMPLATE_INDEX, "2"); } } if (state.getAttribute(SITE_CREATE_TOTAL_STEPS) == null) { state .setAttribute(SITE_CREATE_TOTAL_STEPS, new Integer( totalSteps)); } if (state.getAttribute(SITE_CREATE_CURRENT_STEP) == null) { state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer(1)); } } // doSite_type /** * Determine whether the selected term is considered of "future term" * @param state * @param t */ private void isFutureTermSelected(SessionState state) { AcademicSession t = (AcademicSession) state.getAttribute(STATE_TERM_SELECTED); int weeks = 0; Calendar c = (Calendar) Calendar.getInstance().clone(); try { weeks = Integer .parseInt(ServerConfigurationService .getString( "roster.available.weeks.before.term.start", "0")); c.add(Calendar.DATE, weeks * 7); } catch (Exception ignore) { } if (c.getTimeInMillis() < t.getStartDate().getTime()) { // if a future term is selected state.setAttribute(STATE_FUTURE_TERM_SELECTED, Boolean.TRUE); } else { state.setAttribute(STATE_FUTURE_TERM_SELECTED, Boolean.FALSE); } } public void doChange_user(RunData data) { doSite_type(data); } // doChange_user /** * cleanEditGroupParams clean the state parameters used by editing group * process * */ public void cleanEditGroupParams(SessionState state) { state.removeAttribute(STATE_GROUP_INSTANCE_ID); state.removeAttribute(STATE_GROUP_TITLE); state.removeAttribute(STATE_GROUP_DESCRIPTION); state.removeAttribute(STATE_GROUP_MEMBERS); state.removeAttribute(STATE_GROUP_REMOVE); } // cleanEditGroupParams /** * doGroup_edit * */ public void doGroup_update(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); Set gMemberSet = (Set) state.getAttribute(STATE_GROUP_MEMBERS); Site site = getStateSite(state); String title = StringUtil.trimToNull(params.getString(rb .getString("group.title"))); state.setAttribute(STATE_GROUP_TITLE, title); String description = StringUtil.trimToZero(params.getString(rb .getString("group.description"))); state.setAttribute(STATE_GROUP_DESCRIPTION, description); boolean found = false; String option = params.getString("option"); if (option.equals("add")) { // add selected members into it if (params.getStrings("generallist") != null) { List addMemberIds = new ArrayList(Arrays.asList(params .getStrings("generallist"))); for (int i = 0; i < addMemberIds.size(); i++) { String aId = (String) addMemberIds.get(i); found = false; for (Iterator iSet = gMemberSet.iterator(); !found && iSet.hasNext();) { if (((Member) iSet.next()).getUserEid().equals(aId)) { found = true; } } if (!found) { try { User u = UserDirectoryService.getUser(aId); gMemberSet.add(site.getMember(u.getId())); } catch (UserNotDefinedException e) { try { User u2 = UserDirectoryService .getUserByEid(aId); gMemberSet.add(site.getMember(u2.getId())); } catch (UserNotDefinedException ee) { M_log.warn(this + ee.getMessage() + aId); } } } } } state.setAttribute(STATE_GROUP_MEMBERS, gMemberSet); } else if (option.equals("remove")) { // update the group member list by remove selected members from it if (params.getStrings("grouplist") != null) { List removeMemberIds = new ArrayList(Arrays.asList(params .getStrings("grouplist"))); for (int i = 0; i < removeMemberIds.size(); i++) { found = false; for (Iterator iSet = gMemberSet.iterator(); !found && iSet.hasNext();) { Member mSet = (Member) iSet.next(); if (mSet.getUserId().equals( (String) removeMemberIds.get(i))) { found = true; gMemberSet.remove(mSet); } } } } state.setAttribute(STATE_GROUP_MEMBERS, gMemberSet); } else if (option.equals("cancel")) { // cancel from the update the group member process doCancel(data); cleanEditGroupParams(state); } else if (option.equals("save")) { Group group = null; if (site != null && state.getAttribute(STATE_GROUP_INSTANCE_ID) != null) { try { group = site.getGroup((String) state .getAttribute(STATE_GROUP_INSTANCE_ID)); } catch (Exception ignore) { } } if (title == null) { addAlert(state, rb.getString("editgroup.titlemissing")); } else { if (group == null) { // when adding a group, check whether the group title has // been used already boolean titleExist = false; for (Iterator iGroups = site.getGroups().iterator(); !titleExist && iGroups.hasNext();) { Group iGroup = (Group) iGroups.next(); if (iGroup.getTitle().equals(title)) { // found same title titleExist = true; } } if (titleExist) { addAlert(state, rb.getString("group.title.same")); } } } if (state.getAttribute(STATE_MESSAGE) == null) { if (group == null) { // adding new group group = site.addGroup(); group.getProperties().addProperty( GROUP_PROP_WSETUP_CREATED, Boolean.TRUE.toString()); } if (group != null) { group.setTitle(title); group.setDescription(description); // save the modification to group members // remove those no longer included in the group Set members = group.getMembers(); for (Iterator iMembers = members.iterator(); iMembers .hasNext();) { found = false; String mId = ((Member) iMembers.next()).getUserId(); for (Iterator iMemberSet = gMemberSet.iterator(); !found && iMemberSet.hasNext();) { if (mId.equals(((Member) iMemberSet.next()) .getUserId())) { found = true; } } if (!found) { group.removeMember(mId); } } // add those seleted members for (Iterator iMemberSet = gMemberSet.iterator(); iMemberSet .hasNext();) { String memberId = ((Member) iMemberSet.next()) .getUserId(); if (group.getUserRole(memberId) == null) { Role r = site.getUserRole(memberId); Member m = site.getMember(memberId); // for every member added through the "Manage // Groups" interface, he should be defined as // non-provided group.addMember(memberId, r != null ? r.getId() : "", m != null ? m.isActive() : true, false); } } if (state.getAttribute(STATE_MESSAGE) == null) { try { SiteService.save(site); } catch (IdUnusedException e) { } catch (PermissionException e) { } // return to group list view state.setAttribute(STATE_TEMPLATE_INDEX, "49"); cleanEditGroupParams(state); } } } } } // doGroup_updatemembers /** * doGroup_new * */ public void doGroup_new(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); if (state.getAttribute(STATE_GROUP_TITLE) == null) { state.setAttribute(STATE_GROUP_TITLE, ""); } if (state.getAttribute(STATE_GROUP_DESCRIPTION) == null) { state.setAttribute(STATE_GROUP_DESCRIPTION, ""); } if (state.getAttribute(STATE_GROUP_MEMBERS) == null) { state.setAttribute(STATE_GROUP_MEMBERS, new HashSet()); } state.setAttribute(STATE_TEMPLATE_INDEX, "50"); } // doGroup_new /** * doGroup_edit * */ public void doGroup_edit(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); String groupId = data.getParameters().getString("groupId"); state.setAttribute(STATE_GROUP_INSTANCE_ID, groupId); Site site = getStateSite(state); if (site != null) { Group g = site.getGroup(groupId); if (g != null) { if (state.getAttribute(STATE_GROUP_TITLE) == null) { state.setAttribute(STATE_GROUP_TITLE, g.getTitle()); } if (state.getAttribute(STATE_GROUP_DESCRIPTION) == null) { state.setAttribute(STATE_GROUP_DESCRIPTION, g .getDescription()); } if (state.getAttribute(STATE_GROUP_MEMBERS) == null) { // double check the member existance Set gMemberSet = g.getMembers(); Set rvGMemberSet = new HashSet(); for (Iterator iSet = gMemberSet.iterator(); iSet.hasNext();) { Member member = (Member) iSet.next(); try { UserDirectoryService.getUser(member.getUserId()); ((Set) rvGMemberSet).add(member); } catch (UserNotDefinedException e) { // cannot find user M_log.warn(this + rb.getString("user.notdefined") + member.getUserId()); } } state.setAttribute(STATE_GROUP_MEMBERS, rvGMemberSet); } } } state.setAttribute(STATE_TEMPLATE_INDEX, "50"); } // doGroup_edit /** * doGroup_remove_prep Go to confirmation page before deleting group(s) * */ public void doGroup_remove_prep(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); String[] removeGroupIds = data.getParameters().getStrings( "removeGroups"); if (removeGroupIds.length > 0) { state.setAttribute(STATE_GROUP_REMOVE, removeGroupIds); state.setAttribute(STATE_TEMPLATE_INDEX, "51"); } } // doGroup_remove_prep /** * doGroup_remove_confirmed Delete selected groups after confirmation * */ public void doGroup_remove_confirmed(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); String[] removeGroupIds = (String[]) state .getAttribute(STATE_GROUP_REMOVE); Site site = getStateSite(state); for (int i = 0; i < removeGroupIds.length; i++) { if (site != null) { Group g = site.getGroup(removeGroupIds[i]); if (g != null) { site.removeGroup(g); } } } try { SiteService.save(site); } catch (IdUnusedException e) { addAlert(state, rb.getString("editgroup.site.notfound.alert")); } catch (PermissionException e) { addAlert(state, rb.getString("editgroup.site.permission.alert")); } if (state.getAttribute(STATE_MESSAGE) == null) { cleanEditGroupParams(state); state.setAttribute(STATE_TEMPLATE_INDEX, "49"); } } // doGroup_remove_confirmed /** * doMenu_edit_site_info The menu choice to enter group view * */ public void doMenu_group(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset sort criteria state.setAttribute(SORTED_BY, rb.getString("group.title")); state.setAttribute(SORTED_ASC, Boolean.TRUE.toString()); state.setAttribute(STATE_TEMPLATE_INDEX, "49"); } // doMenu_group /** * */ private void removeSection(SessionState state, ParameterParser params) { // v2.4 - added by daisyf // RemoveSection - remove any selected course from a list of // provider courses // check if any section need to be removed removeAnyFlagedSection(state, params); SiteInfo siteInfo = new SiteInfo(); if (state.getAttribute(STATE_SITE_INFO) != null) { siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); } List providerChosenList = (List) state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN); collectNewSiteInfo(siteInfo, state, params, providerChosenList); // next step //state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer(2)); } /** * dispatch to different functions based on the option value in the * parameter */ public void doManual_add_course(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String option = params.getString("option"); if (option.equalsIgnoreCase("change") || option.equalsIgnoreCase("add")) { readCourseSectionInfo(state, params); String uniqname = StringUtil.trimToNull(params .getString("uniqname")); state.setAttribute(STATE_SITE_QUEST_UNIQNAME, uniqname); updateSiteInfo(params, state); if (option.equalsIgnoreCase("add")) { if (state.getAttribute(STATE_FUTURE_TERM_SELECTED) != null && !((Boolean) state .getAttribute(STATE_FUTURE_TERM_SELECTED)) .booleanValue()) { // if a future term is selected, do not check authorization // uniqname if (uniqname == null) { addAlert(state, rb.getString("java.author") + " " + ServerConfigurationService .getString("officialAccountName") + ". "); } else { try { UserDirectoryService.getUserByEid(uniqname); } catch (UserNotDefinedException e) { addAlert( state, rb.getString("java.validAuthor1") + " " + ServerConfigurationService .getString("officialAccountName") + " " + rb.getString("java.validAuthor2")); } } } if (state.getAttribute(STATE_MESSAGE) == null) { if (getStateSite(state) == null) { state.setAttribute(STATE_TEMPLATE_INDEX, "2"); } else { state.setAttribute(STATE_TEMPLATE_INDEX, "44"); } } updateCurrentStep(state, true); } } else if (option.equalsIgnoreCase("back")) { doBack(data); if (state.getAttribute(STATE_MESSAGE) == null) { updateCurrentStep(state, false); } } else if (option.equalsIgnoreCase("cancel")) { if (getStateSite(state) == null) { doCancel_create(data); } else { doCancel(data); } } else if (option.equalsIgnoreCase("removeSection")) { // remove selected section removeSection(state, params); } } // doManual_add_course /** * dispatch to different functions based on the option value in the * parameter */ public void doSite_information(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String option = params.getString("option"); if (option.equalsIgnoreCase("continue")) { doContinue(data); } else if (option.equalsIgnoreCase("back")) { doBack(data); } else if (option.equalsIgnoreCase("cancel")) { if (getStateSite(state) == null) { doCancel_create(data); } else { doCancel(data); } } else if (option.equalsIgnoreCase("removeSection")) { // remove selected section removeSection(state, params); } } // doSite_information /** * read the input information of subject, course and section in the manual * site creation page */ private void readCourseSectionInfo(SessionState state, ParameterParser params) { String option = params.getString("option"); int oldNumber = 1; if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { oldNumber = ((Integer) state .getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue(); } // read the user input int validInputSites = 0; boolean validInput = true; List multiCourseInputs = new Vector(); for (int i = 0; i < oldNumber; i++) { List requiredFields = sectionFieldProvider.getRequiredFields(); List aCourseInputs = new Vector(); int emptyInputNum = 0; // iterate through all required fields for (int k = 0; k < requiredFields.size(); k++) { SectionField sectionField = (SectionField) requiredFields .get(k); String fieldLabel = sectionField.getLabelKey(); String fieldInput = StringUtil.trimToZero(params .getString(fieldLabel + i)); sectionField.setValue(fieldInput); aCourseInputs.add(sectionField); if (fieldInput.length() == 0) { // is this an empty String input? emptyInputNum++; } } // is any input invalid? if (emptyInputNum == 0) { // valid if all the inputs are not empty multiCourseInputs.add(validInputSites++, aCourseInputs); } else if (emptyInputNum == requiredFields.size()) { // ignore if all inputs are empty if (option.equalsIgnoreCase("change")) { multiCourseInputs.add(validInputSites++, aCourseInputs); } } else { if (state.getAttribute(STATE_FUTURE_TERM_SELECTED) != null && ((Boolean) state .getAttribute(STATE_FUTURE_TERM_SELECTED)) .booleanValue()) { // if future term selected, then not all fields are required // %%% } else { validInput = false; } multiCourseInputs.add(validInputSites++, aCourseInputs); } } // how many more course/section to include in the site? if (option.equalsIgnoreCase("change")) { if (params.getString("number") != null) { int newNumber = Integer.parseInt(params.getString("number")); state.setAttribute(STATE_MANUAL_ADD_COURSE_NUMBER, new Integer(oldNumber + newNumber)); List requiredFields = sectionFieldProvider.getRequiredFields(); for (int j = 0; j < newNumber; j++) { // add a new course input List aCourseInputs = new Vector(); // iterate through all required fields for (int m = 0; m < requiredFields.size(); m++) { aCourseInputs = sectionFieldProvider.getRequiredFields(); } multiCourseInputs.add(aCourseInputs); } } } state.setAttribute(STATE_MANUAL_ADD_COURSE_FIELDS, multiCourseInputs); if (!option.equalsIgnoreCase("change")) { if (!validInput || validInputSites == 0) { // not valid input addAlert(state, rb.getString("java.miss")); } // valid input, adjust the add course number state.setAttribute(STATE_MANUAL_ADD_COURSE_NUMBER, new Integer( validInputSites)); } // set state attributes state.setAttribute(FORM_ADDITIONAL, StringUtil.trimToZero(params .getString("additional"))); SiteInfo siteInfo = new SiteInfo(); if (state.getAttribute(STATE_SITE_INFO) != null) { siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); } List providerCourseList = (List) state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN); // store the manually requested sections in one site property if ((providerCourseList == null || providerCourseList.size() == 0) && multiCourseInputs.size() > 0) { AcademicSession t = (AcademicSession) state .getAttribute(STATE_TERM_SELECTED); String sectionEid = sectionFieldProvider.getSectionEid(t.getEid(), (List) multiCourseInputs.get(0)); // default title String title = sectionEid; try { title = cms.getSection(sectionEid).getTitle(); } catch (Exception e) { // ignore } siteInfo.title = title; } state.setAttribute(STATE_SITE_INFO, siteInfo); } // readCourseSectionInfo /** * set the site type for new site * * @param type * The type String */ private void setNewSiteType(SessionState state, String type) { state.removeAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST); state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME); // start out with fresh site information SiteInfo siteInfo = new SiteInfo(); siteInfo.site_type = type; siteInfo.published = true; state.setAttribute(STATE_SITE_INFO, siteInfo); // get registered tools list Set categories = new HashSet(); categories.add(type); Set toolRegistrations = ToolManager.findTools(categories, null); List tools = new Vector(); SortedIterator i = new SortedIterator(toolRegistrations.iterator(), new ToolComparator()); for (; i.hasNext();) { // form a new Tool Tool tr = (Tool) i.next(); MyTool newTool = new MyTool(); newTool.title = tr.getTitle(); newTool.id = tr.getId(); newTool.description = tr.getDescription(); tools.add(newTool); } state.setAttribute(STATE_TOOL_REGISTRATION_LIST, tools); state.setAttribute(STATE_SITE_TYPE, type); } /** * Set the field on which to sort the list of students * */ public void doSort_roster(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // get the field on which to sort the student list ParameterParser params = data.getParameters(); String criterion = params.getString("criterion"); // current sorting sequence String asc = ""; if (!criterion.equals(state.getAttribute(SORTED_BY))) { state.setAttribute(SORTED_BY, criterion); asc = Boolean.TRUE.toString(); state.setAttribute(SORTED_ASC, asc); } else { // current sorting sequence asc = (String) state.getAttribute(SORTED_ASC); // toggle between the ascending and descending sequence if (asc.equals(Boolean.TRUE.toString())) { asc = Boolean.FALSE.toString(); } else { asc = Boolean.TRUE.toString(); } state.setAttribute(SORTED_ASC, asc); } } // doSort_roster /** * Set the field on which to sort the list of sites * */ public void doSort_sites(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // call this method at the start of a sort for proper paging resetPaging(state); // get the field on which to sort the site list ParameterParser params = data.getParameters(); String criterion = params.getString("criterion"); // current sorting sequence String asc = ""; if (!criterion.equals(state.getAttribute(SORTED_BY))) { state.setAttribute(SORTED_BY, criterion); asc = Boolean.TRUE.toString(); state.setAttribute(SORTED_ASC, asc); } else { // current sorting sequence asc = (String) state.getAttribute(SORTED_ASC); // toggle between the ascending and descending sequence if (asc.equals(Boolean.TRUE.toString())) { asc = Boolean.FALSE.toString(); } else { asc = Boolean.TRUE.toString(); } state.setAttribute(SORTED_ASC, asc); } state.setAttribute(SORTED_BY, criterion); } // doSort_sites /** * doContinue is called when "eventSubmit_doContinue" is in the request * parameters */ public void doContinue(RunData data) { // Put current form data in state and continue to the next template, // make any permanent changes SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); int index = Integer.valueOf(params.getString("template-index")) .intValue(); // Let actionForTemplate know to make any permanent changes before // continuing to the next template String direction = "continue"; String option = params.getString("option"); actionForTemplate(direction, index, params, state); if (state.getAttribute(STATE_MESSAGE) == null) { if (index == 9) { // go to the send site publish email page if "publish" option is // chosen SiteInfo sInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); if (sInfo.getPublished()) { state.setAttribute(STATE_TEMPLATE_INDEX, "16"); } else { state.setAttribute(STATE_TEMPLATE_INDEX, "17"); } } else if (index == 36 && ("add").equals(option)) { // this is the Add extra Roster(s) case after a site is created state.setAttribute(STATE_TEMPLATE_INDEX, "44"); } else if (params.getString("continue") != null) { state.setAttribute(STATE_TEMPLATE_INDEX, params .getString("continue")); } } }// doContinue /** * handle with continue add new course site options * */ public void doContinue_new_course(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String option = data.getParameters().getString("option"); if (option.equals("continue")) { doContinue(data); } else if (option.equals("cancel")) { doCancel_create(data); } else if (option.equals("back")) { doBack(data); } else if (option.equals("cancel")) { doCancel_create(data); } else if (option.equalsIgnoreCase("change")) { // change term String termId = params.getString("selectTerm"); AcademicSession t = cms.getAcademicSession(termId); state.setAttribute(STATE_TERM_SELECTED, t); isFutureTermSelected(state); } else if (option.equalsIgnoreCase("cancel_edit")) { // cancel doCancel(data); } else if (option.equalsIgnoreCase("add")) { isFutureTermSelected(state); // continue doContinue(data); } } // doContinue_new_course /** * doBack is called when "eventSubmit_doBack" is in the request parameters * Pass parameter to actionForTemplate to request action for backward * direction */ public void doBack(RunData data) { // Put current form data in state and return to the previous template SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); int currentIndex = Integer.parseInt((String) state .getAttribute(STATE_TEMPLATE_INDEX)); state.setAttribute(STATE_TEMPLATE_INDEX, params.getString("back")); // Let actionForTemplate know not to make any permanent changes before // continuing to the next template String direction = "back"; actionForTemplate(direction, currentIndex, params, state); }// doBack /** * doFinish is called when a site has enough information to be saved as an * unpublished site */ public void doFinish(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_TEMPLATE_INDEX, params .getString("continue")); int index = Integer.valueOf(params.getString("template-index")) .intValue(); actionForTemplate("continue", index, params, state); addNewSite(params, state); addFeatures(state); Site site = getStateSite(state); // for course sites String siteType = (String) state.getAttribute(STATE_SITE_TYPE); if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { String siteId = site.getId(); ResourcePropertiesEdit rp = site.getPropertiesEdit(); AcademicSession term = null; if (state.getAttribute(STATE_TERM_SELECTED) != null) { term = (AcademicSession) state .getAttribute(STATE_TERM_SELECTED); rp.addProperty(PROP_SITE_TERM, term.getTitle()); rp.addProperty(PROP_SITE_TERM_EID, term.getEid()); } // update the site and related realm based on the rosters chosen or requested updateCourseSiteSections(state, siteId, rp, term); } // commit site commitSite(site); String siteId = (String) state.getAttribute(STATE_SITE_INSTANCE_ID); // now that the site exists, we can set the email alias when an // Email Archive tool has been selected String alias = StringUtil.trimToNull((String) state .getAttribute(STATE_TOOL_EMAIL_ADDRESS)); if (alias != null) { String channelReference = mailArchiveChannelReference(siteId); try { AliasService.setAlias(alias, channelReference); } catch (IdUsedException ee) { addAlert(state, rb.getString("java.alias") + " " + alias + " " + rb.getString("java.exists")); } catch (IdInvalidException ee) { addAlert(state, rb.getString("java.alias") + " " + alias + " " + rb.getString("java.isinval")); } catch (PermissionException ee) { addAlert(state, rb.getString("java.addalias") + " "); } } // TODO: hard coding this frame id is fragile, portal dependent, and // needs to be fixed -ggolden // schedulePeerFrameRefresh("sitenav"); scheduleTopRefresh(); resetPaging(state); // clean state variables cleanState(state); state.setAttribute(STATE_TEMPLATE_INDEX, "0"); } }// doFinish /** * Update course site and related realm based on the roster chosen or requested * @param state * @param siteId * @param rp * @param term */ private void updateCourseSiteSections(SessionState state, String siteId, ResourcePropertiesEdit rp, AcademicSession term) { // whether this is in the process of editing a site? boolean editingSite = ((String)state.getAttribute(STATE_SITE_MODE)).equals(SITE_MODE_SITEINFO)?true:false; List providerCourseList = (List) state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN); int manualAddNumber = 0; if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { manualAddNumber = ((Integer) state .getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)) .intValue(); } List<SectionObject> cmRequestedSections = (List<SectionObject>) state .getAttribute(STATE_CM_REQUESTED_SECTIONS); List<SectionObject> cmAuthorizerSections = (List<SectionObject>) state .getAttribute(STATE_CM_AUTHORIZER_SECTIONS); String realm = SiteService.siteReference(siteId); if ((providerCourseList != null) && (providerCourseList.size() != 0)) { String providerRealm = buildExternalRealm(siteId, state, providerCourseList); try { AuthzGroup realmEdit = AuthzGroupService .getAuthzGroup(realm); realmEdit.setProviderGroupId(providerRealm); AuthzGroupService.save(realmEdit); } catch (GroupNotDefinedException e) { M_log.warn(this + " IdUnusedException, not found, or not an AuthzGroup object"); addAlert(state, rb.getString("java.realm")); } // catch (AuthzPermissionException e) // { // M_log.warn(this + " PermissionException, user does not // have permission to edit AuthzGroup object."); // addAlert(state, rb.getString("java.notaccess")); // return; // } catch (Exception e) { addAlert(state, this + rb.getString("java.problem")); } sendSiteNotification(state, providerCourseList); } if (manualAddNumber != 0) { // set the manual sections to the site property String manualSections = rp.getProperty(PROP_SITE_REQUEST_COURSE) != null?rp.getProperty(PROP_SITE_REQUEST_COURSE)+"+":""; // manualCourseInputs is a list of a list of SectionField List manualCourseInputs = (List) state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS); // but we want to feed a list of a list of String (input of // the required fields) for (int j = 0; j < manualAddNumber; j++) { manualSections = manualSections.concat( sectionFieldProvider.getSectionEid( term.getEid(), (List) manualCourseInputs.get(j))) .concat("+"); } // trim the trailing plus sign manualSections = trimTrailingString(manualSections, "+"); rp.addProperty(PROP_SITE_REQUEST_COURSE, manualSections); // send request sendSiteRequest(state, "new", manualAddNumber, manualCourseInputs, "manual"); } if (cmRequestedSections != null && cmRequestedSections.size() > 0 || state.getAttribute(STATE_CM_SELECTED_SECTIONS) != null) { // set the cmRequest sections to the site property String cmRequestedSectionString = ""; if (!editingSite) { // but we want to feed a list of a list of String (input of // the required fields) for (int j = 0; j < cmRequestedSections.size(); j++) { cmRequestedSectionString = cmRequestedSectionString.concat(( cmRequestedSections.get(j)).eid).concat("+"); } // trim the trailing plus sign cmRequestedSectionString = trimTrailingString(cmRequestedSectionString, "+"); sendSiteRequest(state, "new", cmRequestedSections.size(), cmRequestedSections, "cmRequest"); } else { cmRequestedSectionString = rp.getProperty(STATE_CM_REQUESTED_SECTIONS) != null ? (String) rp.getProperty(STATE_CM_REQUESTED_SECTIONS):""; // get the selected cm section if (state.getAttribute(STATE_CM_SELECTED_SECTIONS) != null ) { List<SectionObject> cmSelectedSections = (List) state.getAttribute(STATE_CM_SELECTED_SECTIONS); if (cmRequestedSectionString.length() != 0) { cmRequestedSectionString = cmRequestedSectionString.concat("+"); } for (int j = 0; j < cmSelectedSections.size(); j++) { cmRequestedSectionString = cmRequestedSectionString.concat(( cmSelectedSections.get(j)).eid).concat("+"); } // trim the trailing plus sign cmRequestedSectionString = trimTrailingString(cmRequestedSectionString, "+"); sendSiteRequest(state, "new", cmSelectedSections.size(), cmSelectedSections, "cmRequest"); } } // update site property if (cmRequestedSectionString.length() > 0) { rp.addProperty(STATE_CM_REQUESTED_SECTIONS, cmRequestedSectionString); } else { rp.removeProperty(STATE_CM_REQUESTED_SECTIONS); } } } /** * Trim the trailing occurance of specified string * @param cmRequestedSectionString * @param trailingString * @return */ private String trimTrailingString(String cmRequestedSectionString, String trailingString) { if (cmRequestedSectionString.endsWith(trailingString)) { cmRequestedSectionString = cmRequestedSectionString.substring(0, cmRequestedSectionString.lastIndexOf(trailingString)); } return cmRequestedSectionString; } /** * buildExternalRealm creates a site/realm id in one of three formats, for a * single section, for multiple sections of the same course, or for a * cross-listing having multiple courses * * @param sectionList * is a Vector of CourseListItem * @param id * The site id */ private String buildExternalRealm(String id, SessionState state, List<String> providerIdList) { String realm = SiteService.siteReference(id); if (!AuthzGroupService.allowUpdate(realm)) { addAlert(state, rb.getString("java.rosters")); return null; } String[] providers = new String[providerIdList.size()]; providers = (String[]) providerIdList.toArray(providers); String providerId = groupProvider.packId(providers); return providerId; } // buildExternalRealm /** * Notification sent when a course site needs to be set up by Support * */ private void sendSiteRequest(SessionState state, String request, int requestListSize, List requestFields, String fromContext) { User cUser = UserDirectoryService.getCurrentUser(); boolean sendEmailToRequestee = false; StringBuilder buf = new StringBuilder(); // get the request email from configuration String requestEmail = getSetupRequestEmailAddress(); if (requestEmail != null) { String officialAccountName = ServerConfigurationService .getString("officialAccountName", ""); SiteInfo siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); Site site = getStateSite(state); String id = site.getId(); String title = site.getTitle(); Time time = TimeService.newTime(); String local_time = time.toStringLocalTime(); String local_date = time.toStringLocalDate(); AcademicSession term = null; boolean termExist = false; if (state.getAttribute(STATE_TERM_SELECTED) != null) { termExist = true; term = (AcademicSession) state .getAttribute(STATE_TERM_SELECTED); } String productionSiteName = ServerConfigurationService .getServerName(); String from = NULL_STRING; String to = NULL_STRING; String headerTo = NULL_STRING; String replyTo = NULL_STRING; String message_subject = NULL_STRING; String content = NULL_STRING; String sessionUserName = cUser.getDisplayName(); String additional = NULL_STRING; if (request.equals("new")) { additional = siteInfo.getAdditional(); } else { additional = (String) state.getAttribute(FORM_ADDITIONAL); } boolean isFutureTerm = false; if (state.getAttribute(STATE_FUTURE_TERM_SELECTED) != null && ((Boolean) state .getAttribute(STATE_FUTURE_TERM_SELECTED)) .booleanValue()) { isFutureTerm = true; } // message subject if (termExist) { message_subject = rb.getString("java.sitereqfrom") + " " + sessionUserName + " " + rb.getString("java.for") + " " + term.getEid(); } else { message_subject = rb.getString("java.official") + " " + sessionUserName; } // there is no offical instructor for future term sites String requestId = (String) state .getAttribute(STATE_SITE_QUEST_UNIQNAME); if (!isFutureTerm) { // To site quest account - the instructor of record's if (requestId != null) { try { User instructor = UserDirectoryService .getUser(requestId); from = requestEmail; to = instructor.getEmail(); headerTo = instructor.getEmail(); replyTo = requestEmail; buf.append(rb.getString("java.hello") + " \n\n"); buf.append(rb.getString("java.receiv") + " " + sessionUserName + ", "); buf.append(rb.getString("java.who") + "\n"); if (termExist) { buf.append(term.getTitle()); } // requsted sections if (fromContext.equals("manual")) { addRequestedSectionIntoNotification(state, requestFields, buf); } else if (fromContext.equals("cmRequest")) { addRequestedCMSectionIntoNotification(state, requestFields, buf); } buf.append("\n" + rb.getString("java.sitetitle") + "\t" + title + "\n"); buf.append(rb.getString("java.siteid") + "\t" + id); buf.append("\n\n" + rb.getString("java.according") + " " + sessionUserName + " " + rb.getString("java.record")); buf.append(" " + rb.getString("java.canyou") + " " + sessionUserName + " " + rb.getString("java.assoc") + "\n\n"); buf.append(rb.getString("java.respond") + " " + sessionUserName + rb.getString("java.appoint") + "\n\n"); buf.append(rb.getString("java.thanks") + "\n"); buf.append(productionSiteName + " " + rb.getString("java.support")); content = buf.toString(); // send the email EmailService.send(from, to, message_subject, content, headerTo, replyTo, null); // email has been sent successfully sendEmailToRequestee = true; } catch (UserNotDefinedException ee) { } // try } } // To Support from = cUser.getEmail(); to = requestEmail; headerTo = requestEmail; replyTo = cUser.getEmail(); buf.setLength(0); buf.append(rb.getString("java.to") + "\t\t" + productionSiteName + " " + rb.getString("java.supp") + "\n"); buf.append("\n" + rb.getString("java.from") + "\t" + sessionUserName + "\n"); if (request.equals("new")) { buf.append(rb.getString("java.subj") + "\t" + rb.getString("java.sitereq") + "\n"); } else { buf.append(rb.getString("java.subj") + "\t" + rb.getString("java.sitechreq") + "\n"); } buf.append(rb.getString("java.date") + "\t" + local_date + " " + local_time + "\n\n"); if (request.equals("new")) { buf.append(rb.getString("java.approval") + " " + productionSiteName + " " + rb.getString("java.coursesite") + " "); } else { buf.append(rb.getString("java.approval2") + " " + productionSiteName + " " + rb.getString("java.coursesite") + " "); } if (termExist) { buf.append(term.getTitle()); } if (requestListSize > 1) { buf.append(" " + rb.getString("java.forthese") + " " + requestListSize + " " + rb.getString("java.sections") + "\n\n"); } else { buf.append(" " + rb.getString("java.forthis") + "\n\n"); } // requsted sections if (fromContext.equals("manual")) { addRequestedSectionIntoNotification(state, requestFields, buf); } else if (fromContext.equals("cmRequest")) { addRequestedCMSectionIntoNotification(state, requestFields, buf); } buf.append(rb.getString("java.name") + "\t" + sessionUserName + " (" + officialAccountName + " " + cUser.getEid() + ")\n"); buf.append(rb.getString("java.email") + "\t" + replyTo + "\n\n"); buf.append(rb.getString("java.sitetitle") + "\t" + title + "\n"); buf.append(rb.getString("java.siteid") + "\t" + id + "\n"); buf.append(rb.getString("java.siteinstr") + "\n" + additional + "\n\n"); if (!isFutureTerm) { if (sendEmailToRequestee) { buf.append(rb.getString("java.authoriz") + " " + requestId + " " + rb.getString("java.asreq")); } else { buf.append(rb.getString("java.thesiteemail") + " " + requestId + " " + rb.getString("java.asreq")); } } content = buf.toString(); EmailService.send(from, to, message_subject, content, headerTo, replyTo, null); // To the Instructor from = requestEmail; to = cUser.getEmail(); headerTo = to; replyTo = to; buf.setLength(0); buf.append(rb.getString("java.isbeing") + " "); buf.append(rb.getString("java.meantime") + "\n\n"); buf.append(rb.getString("java.copy") + "\n\n"); buf.append(content); buf.append("\n" + rb.getString("java.wish") + " " + requestEmail); content = buf.toString(); EmailService.send(from, to, message_subject, content, headerTo, replyTo, null); state.setAttribute(REQUEST_SENT, new Boolean(true)); } // if } // sendSiteRequest private void addRequestedSectionIntoNotification(SessionState state, List requestFields, StringBuilder buf) { // what are the required fields shown in the UI List requiredFields = state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS) != null ?(List) state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS):new Vector(); for (int i = 0; i < requiredFields.size(); i++) { List requiredFieldList = (List) requestFields .get(i); for (int j = 0; j < requiredFieldList.size(); j++) { SectionField requiredField = (SectionField) requiredFieldList .get(j); buf.append(requiredField.getLabelKey() + "\t" + requiredField.getValue() + "\n"); } } } private void addRequestedCMSectionIntoNotification(SessionState state, List cmRequestedSections, StringBuilder buf) { // what are the required fields shown in the UI for (int i = 0; i < cmRequestedSections.size(); i++) { SectionObject so = (SectionObject) cmRequestedSections.get(i); buf.append(so.getTitle() + "(" + so.getEid() + ")" + so.getCategory() + "\n"); } } /** * Notification sent when a course site is set up automatcally * */ private void sendSiteNotification(SessionState state, List notifySites) { // get the request email from configuration String requestEmail = getSetupRequestEmailAddress(); if (requestEmail != null) { // send emails Site site = getStateSite(state); String id = site.getId(); String title = site.getTitle(); Time time = TimeService.newTime(); String local_time = time.toStringLocalTime(); String local_date = time.toStringLocalDate(); String term_name = ""; if (state.getAttribute(STATE_TERM_SELECTED) != null) { term_name = ((AcademicSession) state .getAttribute(STATE_TERM_SELECTED)).getEid(); } String message_subject = rb.getString("java.official") + " " + UserDirectoryService.getCurrentUser().getDisplayName() + " " + rb.getString("java.for") + " " + term_name; String from = NULL_STRING; String to = NULL_STRING; String headerTo = NULL_STRING; String replyTo = NULL_STRING; String sender = UserDirectoryService.getCurrentUser() .getDisplayName(); String userId = StringUtil.trimToZero(SessionManager .getCurrentSessionUserId()); try { userId = UserDirectoryService.getUserEid(userId); } catch (UserNotDefinedException e) { M_log.warn(this + rb.getString("user.notdefined") + " " + userId); } // To Support from = UserDirectoryService.getCurrentUser().getEmail(); to = requestEmail; headerTo = requestEmail; replyTo = UserDirectoryService.getCurrentUser().getEmail(); StringBuilder buf = new StringBuilder(); buf.append("\n" + rb.getString("java.fromwork") + " " + ServerConfigurationService.getServerName() + " " + rb.getString("java.supp") + ":\n\n"); buf.append(rb.getString("java.off") + " '" + title + "' (id " + id + "), " + rb.getString("java.wasset") + " "); buf.append(sender + " (" + userId + ", " + rb.getString("java.email2") + " " + replyTo + ") "); buf.append(rb.getString("java.on") + " " + local_date + " " + rb.getString("java.at") + " " + local_time + " "); buf.append(rb.getString("java.for") + " " + term_name + ", "); int nbr_sections = notifySites.size(); if (nbr_sections > 1) { buf.append(rb.getString("java.withrost") + " " + Integer.toString(nbr_sections) + " " + rb.getString("java.sections") + "\n\n"); } else { buf.append(" " + rb.getString("java.withrost2") + "\n\n"); } for (int i = 0; i < nbr_sections; i++) { String course = (String) notifySites.get(i); buf.append(rb.getString("java.course2") + " " + course + "\n"); } String content = buf.toString(); EmailService.send(from, to, message_subject, content, headerTo, replyTo, null); } // if } // sendSiteNotification /** * doCancel called when "eventSubmit_doCancel_create" is in the request * parameters to c */ public void doCancel_create(RunData data) { // Don't put current form data in state, just return to the previous // template SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); removeAddClassContext(state); state.setAttribute(STATE_TEMPLATE_INDEX, "0"); } // doCancel_create /** * doCancel called when "eventSubmit_doCancel" is in the request parameters * to c int index = Integer.valueOf(params.getString * ("template-index")).intValue(); */ public void doCancel(RunData data) { // Don't put current form data in state, just return to the previous // template SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); state.removeAttribute(STATE_MESSAGE); String currentIndex = (String) state.getAttribute(STATE_TEMPLATE_INDEX); String backIndex = params.getString("back"); state.setAttribute(STATE_TEMPLATE_INDEX, backIndex); if (currentIndex.equals("4")) { state.removeAttribute(STATE_TOOL_EMAIL_ADDRESS); state.removeAttribute(STATE_MESSAGE); removeEditToolState(state); } else if (currentIndex.equals("5")) { // remove related state variables removeAddParticipantContext(state); params = data.getParameters(); state.setAttribute(STATE_TEMPLATE_INDEX, params.getString("back")); } else if (currentIndex.equals("6")) { state.removeAttribute(STATE_REMOVEABLE_USER_LIST); } else if (currentIndex.equals("9")) { state.removeAttribute(FORM_WILL_NOTIFY); } else if (currentIndex.equals("17") || currentIndex.equals("16")) { state.removeAttribute(FORM_WILL_NOTIFY); state.setAttribute(STATE_TEMPLATE_INDEX, "12"); } else if (currentIndex.equals("13") || currentIndex.equals("14")) { // clean state attributes state.removeAttribute(FORM_SITEINFO_TITLE); state.removeAttribute(FORM_SITEINFO_DESCRIPTION); state.removeAttribute(FORM_SITEINFO_SHORT_DESCRIPTION); state.removeAttribute(FORM_SITEINFO_SKIN); state.removeAttribute(FORM_SITEINFO_INCLUDE); state.setAttribute(STATE_TEMPLATE_INDEX, "12"); } else if (currentIndex.equals("15")) { params = data.getParameters(); state.setAttribute(STATE_TEMPLATE_INDEX, params .getString("cancelIndex")); removeEditToolState(state); } // htripath: added 'currentIndex.equals("45")' for import from file // cancel else if (currentIndex.equals("19") || currentIndex.equals("20") || currentIndex.equals("21") || currentIndex.equals("22") || currentIndex.equals("45")) { // from adding participant pages // remove related state variables removeAddParticipantContext(state); state.setAttribute(STATE_TEMPLATE_INDEX, "12"); } else if (currentIndex.equals("23") || currentIndex.equals("24")) { // from change global access state.removeAttribute("form_joinable"); state.removeAttribute("form_joinerRole"); state.setAttribute(STATE_TEMPLATE_INDEX, "18"); } else if (currentIndex.equals("7") || currentIndex.equals("25")) { // from change role removeChangeRoleContext(state); state.setAttribute(STATE_TEMPLATE_INDEX, "18"); } else if (currentIndex.equals("3")) { // from adding class if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITESETUP)) { state.setAttribute(STATE_TEMPLATE_INDEX, "0"); } else if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITEINFO)) { state.setAttribute(STATE_TEMPLATE_INDEX, "18"); } } else if (currentIndex.equals("27") || currentIndex.equals("28")) { // from import if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITESETUP)) { // worksite setup if (getStateSite(state) == null) { // in creating new site process state.setAttribute(STATE_TEMPLATE_INDEX, "0"); } else { // in editing site process state.setAttribute(STATE_TEMPLATE_INDEX, "12"); } } else if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITEINFO)) { // site info state.setAttribute(STATE_TEMPLATE_INDEX, "12"); } state.removeAttribute(STATE_IMPORT_SITE_TOOL); state.removeAttribute(STATE_IMPORT_SITES); } else if (currentIndex.equals("26")) { if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITESETUP) && getStateSite(state) == null) { // from creating site state.setAttribute(STATE_TEMPLATE_INDEX, "0"); } else { // from revising site state.setAttribute(STATE_TEMPLATE_INDEX, "12"); } removeEditToolState(state); } else if (currentIndex.equals("37") || currentIndex.equals("44") || currentIndex.equals("53") || currentIndex.equals("36")) { // cancel back to edit class view state.removeAttribute(STATE_TERM_SELECTED); removeAddClassContext(state); state.setAttribute(STATE_TEMPLATE_INDEX, "43"); } } // doCancel /** * doMenu_customize is called when "eventSubmit_doBack" is in the request * parameters Pass parameter to actionForTemplate to request action for * backward direction */ public void doMenu_customize(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_TEMPLATE_INDEX, "15"); }// doMenu_customize /** * doBack_to_list cancels an outstanding site edit, cleans state and returns * to the site list * */ public void doBack_to_list(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); Site site = getStateSite(state); if (site != null) { Hashtable h = (Hashtable) state .getAttribute(STATE_PAGESIZE_SITEINFO); h.put(site.getId(), state.getAttribute(STATE_PAGESIZE)); state.setAttribute(STATE_PAGESIZE_SITEINFO, h); } // restore the page size for Worksite setup tool if (state.getAttribute(STATE_PAGESIZE_SITESETUP) != null) { state.setAttribute(STATE_PAGESIZE, state .getAttribute(STATE_PAGESIZE_SITESETUP)); state.removeAttribute(STATE_PAGESIZE_SITESETUP); } cleanState(state); setupFormNamesAndConstants(state); state.setAttribute(STATE_TEMPLATE_INDEX, "0"); } // doBack_to_list /** * do called when "eventSubmit_do" is in the request parameters to c */ public void doAdd_custom_link(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); if ((params.getString("name")) == null || (params.getString("url") == null)) { Tool tr = ToolManager.getTool("sakai.iframe"); Site site = getStateSite(state); SitePage page = site.addPage(); page.setTitle(params.getString("name")); // the visible label on // the tool menu ToolConfiguration tool = page.addTool(); tool.setTool("sakai.iframe", tr); tool.setTitle(params.getString("name")); commitSite(site); } else { addAlert(state, rb.getString("java.reqmiss")); state.setAttribute(STATE_TEMPLATE_INDEX, params .getString("template-index")); } } // doAdd_custom_link /** * doAdd_remove_features is called when Make These Changes is clicked in * chef_site-addRemoveFeatures */ public void doAdd_remove_features(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); List existTools = (List) state .getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST); ParameterParser params = data.getParameters(); String option = params.getString("option"); // dispatch if (option.equalsIgnoreCase("addNews")) { updateSelectedToolList(state, params, false); insertTool(state, "sakai.news", STATE_NEWS_TITLES, NEWS_DEFAULT_TITLE, STATE_NEWS_URLS, NEWS_DEFAULT_URL, Integer.parseInt(params.getString("newsNum"))); state.setAttribute(STATE_TEMPLATE_INDEX, "26"); } else if (option.equalsIgnoreCase("addWC")) { updateSelectedToolList(state, params, false); insertTool(state, "sakai.iframe", STATE_WEB_CONTENT_TITLES, WEB_CONTENT_DEFAULT_TITLE, STATE_WEB_CONTENT_URLS, WEB_CONTENT_DEFAULT_URL, Integer.parseInt(params .getString("wcNum"))); state.setAttribute(STATE_TEMPLATE_INDEX, "26"); } else if (option.equalsIgnoreCase("save")) { List idsSelected = new Vector(); boolean goToENWPage = false; boolean homeSelected = false; // Add new pages and tools, if any if (params.getStrings("selectedTools") == null) { addAlert(state, rb.getString("atleastonetool")); } else { List l = new ArrayList(Arrays.asList(params .getStrings("selectedTools"))); // toolId's & titles of // chosen tools for (int i = 0; i < l.size(); i++) { String toolId = (String) l.get(i); if (toolId.equals(HOME_TOOL_ID)) { homeSelected = true; } else if (toolId.equals("sakai.mailbox") || toolId.indexOf("sakai.news") != -1 || toolId.indexOf("sakai.iframe") != -1) { // if user is adding either EmailArchive tool, News tool // or Web Content tool, go to the Customize page for the // tool if (!existTools.contains(toolId)) { goToENWPage = true; } if (toolId.equals("sakai.mailbox")) { // get the email alias when an Email Archive tool // has been selected String channelReference = mailArchiveChannelReference((String) state .getAttribute(STATE_SITE_INSTANCE_ID)); List aliases = AliasService.getAliases( channelReference, 1, 1); if (aliases.size() > 0) { state.setAttribute(STATE_TOOL_EMAIL_ADDRESS, ((Alias) aliases.get(0)).getId()); } } } idsSelected.add(toolId); } state.setAttribute(STATE_TOOL_HOME_SELECTED, new Boolean( homeSelected)); } state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, idsSelected); // List of ToolRegistration toolId's if (state.getAttribute(STATE_MESSAGE) == null) { if (goToENWPage) { // go to the configuration page for Email Archive, News and // Web Content tools state.setAttribute(STATE_TEMPLATE_INDEX, "26"); } else { // go to confirmation page state.setAttribute(STATE_TEMPLATE_INDEX, "15"); } } } else if (option.equalsIgnoreCase("continue")) { // continue doContinue(data); } else if (option.equalsIgnoreCase("Back")) { // back doBack(data); } else if (option.equalsIgnoreCase("Cancel")) { // cancel doCancel(data); } } // doAdd_remove_features /** * doSave_revised_features */ public void doSave_revised_features(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); getRevisedFeatures(params, state); Site site = getStateSite(state); String id = site.getId(); // now that the site exists, we can set the email alias when an Email // Archive tool has been selected String alias = StringUtil.trimToNull((String) state .getAttribute(STATE_TOOL_EMAIL_ADDRESS)); if (alias != null) { String channelReference = mailArchiveChannelReference(id); try { AliasService.setAlias(alias, channelReference); } catch (IdUsedException ee) { } catch (IdInvalidException ee) { addAlert(state, rb.getString("java.alias") + " " + alias + " " + rb.getString("java.isinval")); } catch (PermissionException ee) { addAlert(state, rb.getString("java.addalias") + " "); } } if (state.getAttribute(STATE_MESSAGE) == null) { // clean state variables state.removeAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST); state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME); state.removeAttribute(STATE_NEWS_TITLES); state.removeAttribute(STATE_NEWS_URLS); state.removeAttribute(STATE_WEB_CONTENT_TITLES); state.removeAttribute(STATE_WEB_CONTENT_URLS); state.setAttribute(STATE_SITE_INSTANCE_ID, id); state.setAttribute(STATE_TEMPLATE_INDEX, params .getString("continue")); } // refresh the whole page scheduleTopRefresh(); } // doSave_revised_features /** * doMenu_add_participant */ public void doMenu_add_participant(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.removeAttribute(STATE_SELECTED_USER_LIST); state.setAttribute(STATE_TEMPLATE_INDEX, "5"); } // doMenu_add_participant /** * doMenu_siteInfo_addParticipant */ public void doMenu_siteInfo_addParticipant(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.removeAttribute(STATE_SELECTED_USER_LIST); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_TEMPLATE_INDEX, "5"); } } // doMenu_siteInfo_addParticipant /** * doMenu_siteInfo_removeParticipant */ public void doMenu_siteInfo_removeParticipant(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); if (params.getStrings("selectedUser") == null) { addAlert(state, rb.getString("java.nousers")); } else { List removeUser = Arrays.asList(params.getStrings("selectedUser")); // all or some selected user(s) can be removed, go to confirmation // page if (removeUser.size() > 0) { state.setAttribute(STATE_TEMPLATE_INDEX, "6"); } else { addAlert(state, rb.getString("java.however")); } state.setAttribute(STATE_REMOVEABLE_USER_LIST, removeUser); } } // doMenu_siteInfo_removeParticipant /** * doMenu_siteInfo_changeRole */ public void doMenu_siteInfo_changeRole(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); if (params.getStrings("selectedUser") == null) { state.removeAttribute(STATE_SELECTED_USER_LIST); addAlert(state, rb.getString("java.nousers2")); } else { state.setAttribute(STATE_CHANGEROLE_SAMEROLE, Boolean.TRUE); List selectedUserIds = Arrays.asList(params .getStrings("selectedUser")); state.setAttribute(STATE_SELECTED_USER_LIST, selectedUserIds); // get roles for selected participants setSelectedParticipantRoles(state); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_TEMPLATE_INDEX, "7"); } } } // doMenu_siteInfo_changeRole /** * doMenu_siteInfo_globalAccess */ public void doMenu_siteInfo_globalAccess(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_TEMPLATE_INDEX, "23"); } } // doMenu_siteInfo_globalAccess /** * doMenu_siteInfo_cancel_access */ public void doMenu_siteInfo_cancel_access(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.removeAttribute(STATE_SELECTED_USER_LIST); state.setAttribute(STATE_TEMPLATE_INDEX, "12"); } // doMenu_siteInfo_cancel_access /** * doMenu_siteInfo_import */ public void doMenu_siteInfo_import(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // get the tools siteToolsIntoState(state); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_TEMPLATE_INDEX, "28"); } } // doMenu_siteInfo_import /** * doMenu_siteInfo_editClass */ public void doMenu_siteInfo_editClass(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_TEMPLATE_INDEX, "43"); } // doMenu_siteInfo_editClass /** * doMenu_siteInfo_addClass */ public void doMenu_siteInfo_addClass(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); Site site = getStateSite(state); String termEid = site.getProperties().getProperty(PROP_SITE_TERM_EID); if (termEid == null) { // no term eid stored, need to get term eid from the term title String termTitle = site.getProperties().getProperty(PROP_SITE_TERM); List asList = cms.getAcademicSessions(); if (termTitle != null && asList != null) { boolean found = false; for (int i = 0; i<asList.size() && !found; i++) { AcademicSession as = (AcademicSession) asList.get(i); if (as.getTitle().equals(termTitle)) { termEid = as.getEid(); site.getPropertiesEdit().addProperty(PROP_SITE_TERM_EID, termEid); try { SiteService.save(site); } catch (Exception e) { M_log.warn(this + e.getMessage() + site.getId()); } found=true; } } } } state.setAttribute(STATE_TERM_SELECTED, cms.getAcademicSession(termEid)); try { List sections = prepareCourseAndSectionListing(UserDirectoryService.getCurrentUser().getEid(), cms.getAcademicSession(termEid).getEid(), state); isFutureTermSelected(state); if (sections != null && sections.size() > 0) state.setAttribute(STATE_TERM_COURSE_LIST, sections); } catch (Exception e) { M_log.warn(e.getMessage() + termEid); } state.setAttribute(STATE_TEMPLATE_INDEX, "36"); } // doMenu_siteInfo_addClass /** * doMenu_siteInfo_duplicate */ public void doMenu_siteInfo_duplicate(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_TEMPLATE_INDEX, "29"); } } // doMenu_siteInfo_import /** * doMenu_change_roles */ public void doMenu_change_roles(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); if (params.getStrings("removeUser") != null) { state.setAttribute(STATE_SELECTED_USER_LIST, new ArrayList(Arrays .asList(params.getStrings("removeUser")))); state.setAttribute(STATE_TEMPLATE_INDEX, "7"); } else { addAlert(state, rb.getString("java.nousers2")); } } // doMenu_change_roles /** * doMenu_edit_site_info * */ public void doMenu_edit_site_info(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); Site Site = getStateSite(state); ResourceProperties siteProperties = Site.getProperties(); state.setAttribute(FORM_SITEINFO_TITLE, Site.getTitle()); String site_type = (String) state.getAttribute(STATE_SITE_TYPE); if (site_type != null && !site_type.equalsIgnoreCase("myworkspace")) { state.setAttribute(FORM_SITEINFO_INCLUDE, Boolean.valueOf( Site.isPubView()).toString()); } state.setAttribute(FORM_SITEINFO_DESCRIPTION, Site.getDescription()); state.setAttribute(FORM_SITEINFO_SHORT_DESCRIPTION, Site .getShortDescription()); state.setAttribute(FORM_SITEINFO_SKIN, Site.getIconUrl()); if (Site.getIconUrl() != null) { state.setAttribute(FORM_SITEINFO_SKIN, Site.getIconUrl()); } // site contact information String contactName = siteProperties.getProperty(PROP_SITE_CONTACT_NAME); String contactEmail = siteProperties .getProperty(PROP_SITE_CONTACT_EMAIL); if (contactName == null && contactEmail == null) { String creatorId = siteProperties .getProperty(ResourceProperties.PROP_CREATOR); try { User u = UserDirectoryService.getUser(creatorId); String email = u.getEmail(); if (email != null) { contactEmail = u.getEmail(); } contactName = u.getDisplayName(); } catch (UserNotDefinedException e) { } } if (contactName != null) { state.setAttribute(FORM_SITEINFO_CONTACT_NAME, contactName); } if (contactEmail != null) { state.setAttribute(FORM_SITEINFO_CONTACT_EMAIL, contactEmail); } if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_TEMPLATE_INDEX, "13"); } } // doMenu_edit_site_info /** * doMenu_edit_site_tools * */ public void doMenu_edit_site_tools(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // get the tools siteToolsIntoState(state); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_TEMPLATE_INDEX, "4"); } } // doMenu_edit_site_tools /** * doMenu_edit_site_access * */ public void doMenu_edit_site_access(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_TEMPLATE_INDEX, "18"); } } // doMenu_edit_site_access /** * doMenu_publish_site * */ public void doMenu_publish_site(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // get the site properties sitePropertiesIntoState(state); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_TEMPLATE_INDEX, "9"); } } // doMenu_publish_site /** * Back to worksite setup's list view * */ public void doBack_to_site_list(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.removeAttribute(STATE_SELECTED_USER_LIST); state.removeAttribute(STATE_SITE_TYPE); state.removeAttribute(STATE_SITE_INSTANCE_ID); state.setAttribute(STATE_TEMPLATE_INDEX, "0"); } // doBack_to_site_list /** * doSave_site_info * */ public void doSave_siteInfo(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); Site Site = getStateSite(state); ResourcePropertiesEdit siteProperties = Site.getPropertiesEdit(); String site_type = (String) state.getAttribute(STATE_SITE_TYPE); if (site_type != null && !site_type.equals((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { Site.setTitle((String) state.getAttribute(FORM_SITEINFO_TITLE)); } Site.setDescription((String) state .getAttribute(FORM_SITEINFO_DESCRIPTION)); Site.setShortDescription((String) state .getAttribute(FORM_SITEINFO_SHORT_DESCRIPTION)); if (site_type != null) { if (site_type.equals((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { // set icon url for course String skin = (String) state.getAttribute(FORM_SITEINFO_SKIN); setAppearance(state, Site, skin); } else { // set icon url for others String iconUrl = (String) state .getAttribute(FORM_SITEINFO_ICON_URL); Site.setIconUrl(iconUrl); } } // site contact information String contactName = (String) state .getAttribute(FORM_SITEINFO_CONTACT_NAME); if (contactName != null) { siteProperties.addProperty(PROP_SITE_CONTACT_NAME, contactName); } String contactEmail = (String) state .getAttribute(FORM_SITEINFO_CONTACT_EMAIL); if (contactEmail != null) { siteProperties.addProperty(PROP_SITE_CONTACT_EMAIL, contactEmail); } if (state.getAttribute(STATE_MESSAGE) == null) { try { SiteService.save(Site); } catch (IdUnusedException e) { // TODO: } catch (PermissionException e) { // TODO: } // clean state attributes state.removeAttribute(FORM_SITEINFO_TITLE); state.removeAttribute(FORM_SITEINFO_DESCRIPTION); state.removeAttribute(FORM_SITEINFO_SHORT_DESCRIPTION); state.removeAttribute(FORM_SITEINFO_SKIN); state.removeAttribute(FORM_SITEINFO_INCLUDE); state.removeAttribute(FORM_SITEINFO_CONTACT_NAME); state.removeAttribute(FORM_SITEINFO_CONTACT_EMAIL); // back to site info view state.setAttribute(STATE_TEMPLATE_INDEX, "12"); // refresh the whole page scheduleTopRefresh(); } } // doSave_siteInfo /** * init * */ private void init(VelocityPortlet portlet, RunData data, SessionState state) { state.setAttribute(STATE_ACTION, "SiteAction"); setupFormNamesAndConstants(state); if (state.getAttribute(STATE_PAGESIZE_SITEINFO) == null) { state.setAttribute(STATE_PAGESIZE_SITEINFO, new Hashtable()); } if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITESETUP)) { state.setAttribute(STATE_TEMPLATE_INDEX, "0"); } else if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITEINFO)) { String siteId = ToolManager.getCurrentPlacement().getContext(); getReviseSite(state, siteId); Hashtable h = (Hashtable) state .getAttribute(STATE_PAGESIZE_SITEINFO); if (!h.containsKey(siteId)) { // update h.put(siteId, new Integer(200)); state.setAttribute(STATE_PAGESIZE_SITEINFO, h); state.setAttribute(STATE_PAGESIZE, new Integer(200)); } } if (state.getAttribute(STATE_SITE_TYPES) == null) { PortletConfig config = portlet.getPortletConfig(); // all site types (SITE_DEFAULT_LIST overrides tool config) String t = StringUtil.trimToNull(SITE_DEFAULT_LIST); if ( t == null ) t = StringUtil.trimToNull(config.getInitParameter("siteTypes")); if (t != null) { List types = new ArrayList(Arrays.asList(t.split(","))); if (cms == null) { // if there is no CourseManagementService, disable the process of creating course site String courseType = ServerConfigurationService.getString("courseSiteType", (String) state.getAttribute(STATE_COURSE_SITE_TYPE)); types.remove(courseType); } state.setAttribute(STATE_SITE_TYPES, types); } else { state.setAttribute(STATE_SITE_TYPES, new Vector()); } } } // init public void doNavigate_to_site(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); String siteId = StringUtil.trimToNull(data.getParameters().getString( "option")); if (siteId != null) { getReviseSite(state, siteId); } else { doBack_to_list(data); } } // doNavigate_to_site /** * Get site information for revise screen */ private void getReviseSite(SessionState state, String siteId) { if (state.getAttribute(STATE_SELECTED_USER_LIST) == null) { state.setAttribute(STATE_SELECTED_USER_LIST, new Vector()); } List sites = (List) state.getAttribute(STATE_SITES); try { Site site = SiteService.getSite(siteId); state.setAttribute(STATE_SITE_INSTANCE_ID, site.getId()); if (sites != null) { int pos = -1; for (int index = 0; index < sites.size() && pos == -1; index++) { if (((Site) sites.get(index)).getId().equals(siteId)) { pos = index; } } // has any previous site in the list? if (pos > 0) { state.setAttribute(STATE_PREV_SITE, sites.get(pos - 1)); } else { state.removeAttribute(STATE_PREV_SITE); } // has any next site in the list? if (pos < sites.size() - 1) { state.setAttribute(STATE_NEXT_SITE, sites.get(pos + 1)); } else { state.removeAttribute(STATE_NEXT_SITE); } } String type = site.getType(); if (type == null) { if (state.getAttribute(STATE_DEFAULT_SITE_TYPE) != null) { type = (String) state.getAttribute(STATE_DEFAULT_SITE_TYPE); } } state.setAttribute(STATE_SITE_TYPE, type); } catch (IdUnusedException e) { M_log.warn(this + e.toString()); } // one site has been selected state.setAttribute(STATE_TEMPLATE_INDEX, "12"); } // getReviseSite /** * doUpdate_participant * */ public void doUpdate_participant(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); Site s = getStateSite(state); String realmId = SiteService.siteReference(s.getId()); if (AuthzGroupService.allowUpdate(realmId) || SiteService.allowUpdateSiteMembership(s.getId())) { try { AuthzGroup realmEdit = AuthzGroupService.getAuthzGroup(realmId); // does the site has maintain type user(s) before updating // participants? String maintainRoleString = realmEdit.getMaintainRole(); boolean hadMaintainUser = !realmEdit.getUsersHasRole( maintainRoleString).isEmpty(); // update participant roles List participants = collectionToList((Collection) state.getAttribute(STATE_PARTICIPANT_LIST)); // remove all roles and then add back those that were checked for (int i = 0; i < participants.size(); i++) { String id = null; // added participant Participant participant = (Participant) participants.get(i); id = participant.getUniqname(); if (id != null) { // get the newly assigned role String inputRoleField = "role" + id; String roleId = params.getString(inputRoleField); // only change roles when they are different than before if (roleId != null) { // get the grant active status boolean activeGrant = true; String activeGrantField = "activeGrant" + id; if (params.getString(activeGrantField) != null) { activeGrant = params .getString(activeGrantField) .equalsIgnoreCase("true") ? true : false; } boolean fromProvider = !participant.isRemoveable(); if (fromProvider && !roleId.equals(participant.getRole())) { fromProvider = false; } realmEdit.addMember(id, roleId, activeGrant, fromProvider); } } } // remove selected users if (params.getStrings("selectedUser") != null) { List removals = new ArrayList(Arrays.asList(params .getStrings("selectedUser"))); state.setAttribute(STATE_SELECTED_USER_LIST, removals); for (int i = 0; i < removals.size(); i++) { String rId = (String) removals.get(i); try { User user = UserDirectoryService.getUser(rId); Participant selected = new Participant(); selected.name = user.getDisplayName(); selected.uniqname = user.getId(); realmEdit.removeMember(user.getId()); } catch (UserNotDefinedException e) { M_log.warn(this + " IdUnusedException " + rId + ". "); } } } if (hadMaintainUser && realmEdit.getUsersHasRole(maintainRoleString) .isEmpty()) { // if after update, the "had maintain type user" status // changed, show alert message and don't save the update addAlert(state, rb .getString("sitegen.siteinfolist.nomaintainuser") + maintainRoleString + "."); } else { // post event about the participant update EventTrackingService.post(EventTrackingService.newEvent(SiteService.SECURE_UPDATE_SITE_MEMBERSHIP, realmEdit.getId(),false)); AuthzGroupService.save(realmEdit); // then update all related group realms for the role doUpdate_related_group_participants(s, realmId); } } catch (GroupNotDefinedException e) { addAlert(state, rb.getString("java.problem2")); M_log.warn(this + " IdUnusedException " + s.getTitle() + "(" + realmId + "). "); } catch (AuthzPermissionException e) { addAlert(state, rb.getString("java.changeroles")); M_log.warn(this + " PermissionException " + s.getTitle() + "(" + realmId + "). "); } } } // doUpdate_participant /** * update realted group realm setting according to parent site realm changes * @param s * @param realmId */ private void doUpdate_related_group_participants(Site s, String realmId) { Collection groups = s.getGroups(); if (groups != null) { for (Iterator iGroups = groups.iterator(); iGroups.hasNext();) { Group g = (Group) iGroups.next(); try { Set gMembers = g.getMembers(); for (Iterator iGMembers = gMembers.iterator(); iGMembers.hasNext();) { Member gMember = (Member) iGMembers.next(); String gMemberId = gMember.getUserId(); Member siteMember = s.getMember(gMemberId); if ( siteMember == null) { // user has been removed from the site g.removeMember(gMemberId); } else { // if there is a difference between the role setting, remove the entry from group and add it back with correct role, all are marked "not provided" if (!g.getUserRole(gMemberId).equals(siteMember.getRole())) { g.removeMember(gMemberId); g.addMember(gMemberId, siteMember.getRole().getId(), siteMember.isActive(), false); } } } // commit // post event about the participant update EventTrackingService.post(EventTrackingService.newEvent(SiteService.SECURE_UPDATE_GROUP_MEMBERSHIP, g.getId(),false)); SiteService.save(s); } catch (Exception ee) { M_log.warn(this + ee.getMessage() + g.getId()); } } } } /** * doUpdate_site_access * */ public void doUpdate_site_access(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); Site sEdit = getStateSite(state); ParameterParser params = data.getParameters(); String publishUnpublish = params.getString("publishunpublish"); String include = params.getString("include"); String joinable = params.getString("joinable"); if (sEdit != null) { // editing existing site // publish site or not if (publishUnpublish != null && publishUnpublish.equalsIgnoreCase("publish")) { sEdit.setPublished(true); } else { sEdit.setPublished(false); } // site public choice if (include != null) { // if there is pubview input, use it sEdit.setPubView(include.equalsIgnoreCase("true") ? true : false); } else if (state.getAttribute(STATE_SITE_TYPE) != null) { String type = (String) state.getAttribute(STATE_SITE_TYPE); List publicSiteTypes = (List) state .getAttribute(STATE_PUBLIC_SITE_TYPES); List privateSiteTypes = (List) state .getAttribute(STATE_PRIVATE_SITE_TYPES); if (publicSiteTypes.contains(type)) { // sites are always public sEdit.setPubView(true); } else if (privateSiteTypes.contains(type)) { // site are always private sEdit.setPubView(false); } } else { sEdit.setPubView(false); } // publish site or not if (joinable != null && joinable.equalsIgnoreCase("true")) { state.setAttribute(STATE_JOINABLE, Boolean.TRUE); sEdit.setJoinable(true); String joinerRole = StringUtil.trimToNull(params .getString("joinerRole")); if (joinerRole != null) { state.setAttribute(STATE_JOINERROLE, joinerRole); sEdit.setJoinerRole(joinerRole); } else { state.setAttribute(STATE_JOINERROLE, ""); addAlert(state, rb.getString("java.joinsite") + " "); } } else { state.setAttribute(STATE_JOINABLE, Boolean.FALSE); state.removeAttribute(STATE_JOINERROLE); sEdit.setJoinable(false); sEdit.setJoinerRole(null); } if (state.getAttribute(STATE_MESSAGE) == null) { commitSite(sEdit); state.setAttribute(STATE_TEMPLATE_INDEX, "12"); // TODO: hard coding this frame id is fragile, portal dependent, // and needs to be fixed -ggolden // schedulePeerFrameRefresh("sitenav"); scheduleTopRefresh(); state.removeAttribute(STATE_JOINABLE); state.removeAttribute(STATE_JOINERROLE); } } else { // adding new site if (state.getAttribute(STATE_SITE_INFO) != null) { SiteInfo siteInfo = (SiteInfo) state .getAttribute(STATE_SITE_INFO); if (publishUnpublish != null && publishUnpublish.equalsIgnoreCase("publish")) { siteInfo.published = true; } else { siteInfo.published = false; } // site public choice if (include != null) { siteInfo.include = include.equalsIgnoreCase("true") ? true : false; } else if (StringUtil.trimToNull(siteInfo.site_type) != null) { String type = StringUtil.trimToNull(siteInfo.site_type); List publicSiteTypes = (List) state .getAttribute(STATE_PUBLIC_SITE_TYPES); List privateSiteTypes = (List) state .getAttribute(STATE_PRIVATE_SITE_TYPES); if (publicSiteTypes.contains(type)) { // sites are always public siteInfo.include = true; } else if (privateSiteTypes.contains(type)) { // site are always private siteInfo.include = false; } } else { siteInfo.include = false; } // joinable site or not if (joinable != null && joinable.equalsIgnoreCase("true")) { siteInfo.joinable = true; String joinerRole = StringUtil.trimToNull(params .getString("joinerRole")); if (joinerRole != null) { siteInfo.joinerRole = joinerRole; } else { addAlert(state, rb.getString("java.joinsite") + " "); } } else { siteInfo.joinable = false; siteInfo.joinerRole = null; } state.setAttribute(STATE_SITE_INFO, siteInfo); } if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_TEMPLATE_INDEX, "10"); updateCurrentStep(state, true); } } } // doUpdate_site_access /** * remove related state variable for changing participants roles * * @param state * SessionState object */ private void removeChangeRoleContext(SessionState state) { // remove related state variables state.removeAttribute(STATE_CHANGEROLE_SAMEROLE); state.removeAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE); state.removeAttribute(STATE_ADD_PARTICIPANTS); state.removeAttribute(STATE_SELECTED_USER_LIST); state.removeAttribute(STATE_SELECTED_PARTICIPANT_ROLES); } // removeChangeRoleContext /** * /* Actions for vm templates under the "chef_site" root. This method is * called by doContinue. Each template has a hidden field with the value of * template-index that becomes the value of index for the switch statement * here. Some cases not implemented. */ private void actionForTemplate(String direction, int index, ParameterParser params, SessionState state) { // Continue - make any permanent changes, Back - keep any data entered // on the form boolean forward = direction.equals("continue") ? true : false; SiteInfo siteInfo = new SiteInfo(); switch (index) { case 0: /* * actionForTemplate chef_site-list.vm * */ break; case 1: /* * actionForTemplate chef_site-type.vm * */ break; case 2: /* * actionForTemplate chef_site-newSiteInformation.vm * */ if (state.getAttribute(STATE_SITE_INFO) != null) { siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); } // defaults to be true siteInfo.include = true; state.setAttribute(STATE_SITE_INFO, siteInfo); updateSiteInfo(params, state); // alerts after clicking Continue but not Back if (forward) { if (StringUtil.trimToNull(siteInfo.title) == null) { addAlert(state, rb.getString("java.reqfields")); state.setAttribute(STATE_TEMPLATE_INDEX, "2"); return; } } updateSiteAttributes(state); if (state.getAttribute(STATE_MESSAGE) == null) { updateCurrentStep(state, forward); } break; case 3: /* * actionForTemplate chef_site-newSiteFeatures.vm * */ if (forward) { getFeatures(params, state); } if (state.getAttribute(STATE_MESSAGE) == null) { updateCurrentStep(state, forward); } break; case 4: /* * actionForTemplate chef_site-addRemoveFeature.vm * */ break; case 5: /* * actionForTemplate chef_site-addParticipant.vm * */ if (forward) { checkAddParticipant(params, state); } else { // remove related state variables removeAddParticipantContext(state); } break; case 6: /* * actionForTemplate chef_site-removeParticipants.vm * */ break; case 7: /* * actionForTemplate chef_site-changeRoles.vm * */ if (forward) { if (!((Boolean) state.getAttribute(STATE_CHANGEROLE_SAMEROLE)) .booleanValue()) { getSelectedRoles(state, params, STATE_SELECTED_USER_LIST); } else { String role = params.getString("role_to_all"); if (role == null) { addAlert(state, rb.getString("java.pleasechoose") + " "); } else { state .setAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE, role); } } } else { removeChangeRoleContext(state); } break; case 8: /* * actionForTemplate chef_site-siteDeleteConfirm.vm * */ break; case 9: /* * actionForTemplate chef_site-publishUnpublish.vm * */ updateSiteInfo(params, state); break; case 10: /* * actionForTemplate chef_site-newSiteConfirm.vm * */ if (!forward) { if (state.getAttribute(STATE_MESSAGE) == null) { updateCurrentStep(state, false); } } break; case 11: /* * actionForTemplate chef_site_newsitePublishUnpublish.vm * */ break; case 12: /* * actionForTemplate chef_site_siteInfo-list.vm * */ break; case 13: /* * actionForTemplate chef_site_siteInfo-editInfo.vm * */ if (forward) { Site Site = getStateSite(state); if (Site.getType() != null && !Site.getType().equals((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { // site titel is editable and could not be null String title = StringUtil.trimToNull(params .getString("title")); state.setAttribute(FORM_SITEINFO_TITLE, title); if (title == null) { addAlert(state, rb.getString("java.specify") + " "); } } String description = StringUtil.trimToNull(params .getString("description")); state.setAttribute(FORM_SITEINFO_DESCRIPTION, description); String short_description = StringUtil.trimToNull(params .getString("short_description")); state.setAttribute(FORM_SITEINFO_SHORT_DESCRIPTION, short_description); String skin = params.getString("skin"); if (skin != null) { // if there is a skin input for course site skin = StringUtil.trimToNull(skin); state.setAttribute(FORM_SITEINFO_SKIN, skin); } else { // if ther is a icon input for non-course site String icon = StringUtil.trimToNull(params .getString("icon")); if (icon != null) { if (icon.endsWith(PROTOCOL_STRING)) { addAlert(state, rb.getString("alert.protocol")); } state.setAttribute(FORM_SITEINFO_ICON_URL, icon); } else { state.removeAttribute(FORM_SITEINFO_ICON_URL); } } // site contact information String contactName = StringUtil.trimToZero(params .getString("siteContactName")); state.setAttribute(FORM_SITEINFO_CONTACT_NAME, contactName); String email = StringUtil.trimToZero(params .getString("siteContactEmail")); String[] parts = email.split("@"); if (email.length() > 0 && (email.indexOf("@") == -1 || parts.length != 2 || parts[0].length() == 0 || !Validator .checkEmailLocal(parts[0]))) { // invalid email addAlert(state, email + " " + rb.getString("java.invalid") + rb.getString("java.theemail")); } state.setAttribute(FORM_SITEINFO_CONTACT_EMAIL, email); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_TEMPLATE_INDEX, "14"); } } break; case 14: /* * actionForTemplate chef_site_siteInfo-editInfoConfirm.vm * */ break; case 15: /* * actionForTemplate chef_site_siteInfo-addRemoveFeatureConfirm.vm * */ break; case 16: /* * actionForTemplate * chef_site_siteInfo-publishUnpublish-sendEmail.vm * */ if (forward) { String notify = params.getString("notify"); if (notify != null) { state.setAttribute(FORM_WILL_NOTIFY, new Boolean(notify)); } } break; case 17: /* * actionForTemplate chef_site_siteInfo--publishUnpublish-confirm.vm * */ if (forward) { boolean oldStatus = getStateSite(state).isPublished(); boolean newStatus = ((SiteInfo) state .getAttribute(STATE_SITE_INFO)).getPublished(); saveSiteStatus(state, newStatus); if (oldStatus == false || newStatus == true) { // if site's status been changed from unpublish to publish // and notification is selected, send out notification to // participants. if (((Boolean) state.getAttribute(FORM_WILL_NOTIFY)) .booleanValue()) { // %%% place holder for sending email } } // commit site edit Site site = getStateSite(state); try { SiteService.save(site); } catch (IdUnusedException e) { // TODO: } catch (PermissionException e) { // TODO: } // TODO: hard coding this frame id is fragile, portal dependent, // and needs to be fixed -ggolden // schedulePeerFrameRefresh("sitenav"); scheduleTopRefresh(); } break; case 18: /* * actionForTemplate chef_siteInfo-editAccess.vm * */ if (!forward) { if (state.getAttribute(STATE_MESSAGE) == null) { updateCurrentStep(state, false); } } case 19: /* * actionForTemplate chef_site-addParticipant-sameRole.vm * */ String roleId = StringUtil.trimToNull(params .getString("selectRole")); if (roleId == null && forward) { addAlert(state, rb.getString("java.pleasesel") + " "); } else { state.setAttribute("form_selectedRole", params .getString("selectRole")); } break; case 20: /* * actionForTemplate chef_site-addParticipant-differentRole.vm * */ if (forward) { getSelectedRoles(state, params, STATE_ADD_PARTICIPANTS); } break; case 21: /* * actionForTemplate chef_site-addParticipant-notification.vm ' */ if (params.getString("notify") == null) { if (forward) addAlert(state, rb.getString("java.pleasechoice") + " "); } else { state.setAttribute("form_selectedNotify", new Boolean(params .getString("notify"))); } break; case 22: /* * actionForTemplate chef_site-addParticipant-confirm.vm * */ break; case 23: /* * actionForTemplate chef_siteInfo-editAccess-globalAccess.vm * */ if (forward) { String joinable = params.getString("joinable"); state.setAttribute("form_joinable", Boolean.valueOf(joinable)); String joinerRole = params.getString("joinerRole"); state.setAttribute("form_joinerRole", joinerRole); if (joinable.equals("true")) { if (joinerRole == null) { addAlert(state, rb.getString("java.pleasesel") + " "); } } } else { } break; case 24: /* * actionForTemplate * chef_site-siteInfo-editAccess-globalAccess-confirm.vm * */ break; case 25: /* * actionForTemplate chef_site-changeRoles-confirm.vm * */ break; case 26: /* * actionForTemplate chef_site-modifyENW.vm * */ updateSelectedToolList(state, params, forward); if (state.getAttribute(STATE_MESSAGE) == null) { updateCurrentStep(state, forward); } break; case 27: /* * actionForTemplate chef_site-importSites.vm * */ if (forward) { Site existingSite = getStateSite(state); if (existingSite != null) { // revising a existing site's tool if (select_import_tools(params, state)) { Hashtable importTools = (Hashtable) state .getAttribute(STATE_IMPORT_SITE_TOOL); List selectedTools = (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); importToolIntoSite(selectedTools, importTools, existingSite); existingSite = getStateSite(state); // refresh site for // WC and News if (state.getAttribute(STATE_MESSAGE) == null) { commitSite(existingSite); state.removeAttribute(STATE_IMPORT_SITE_TOOL); state.removeAttribute(STATE_IMPORT_SITES); } } else { // show alert and remain in current page addAlert(state, rb.getString("java.toimporttool")); } } else { // new site select_import_tools(params, state); } } else { // read form input about import tools select_import_tools(params, state); } if (state.getAttribute(STATE_MESSAGE) == null) { updateCurrentStep(state, forward); } break; case 28: /* * actionForTemplate chef_siteinfo-import.vm * */ if (forward) { if (params.getStrings("importSites") == null) { addAlert(state, rb.getString("java.toimport") + " "); state.removeAttribute(STATE_IMPORT_SITES); } else { List importSites = new ArrayList(Arrays.asList(params .getStrings("importSites"))); Hashtable sites = new Hashtable(); for (index = 0; index < importSites.size(); index++) { try { Site s = SiteService.getSite((String) importSites .get(index)); sites.put(s, new Vector()); } catch (IdUnusedException e) { } } state.setAttribute(STATE_IMPORT_SITES, sites); } } break; case 29: /* * actionForTemplate chef_siteinfo-duplicate.vm * */ if (forward) { if (state.getAttribute(SITE_DUPLICATED) == null) { if (StringUtil.trimToNull(params.getString("title")) == null) { addAlert(state, rb.getString("java.dupli") + " "); } else { String title = params.getString("title"); state.setAttribute(SITE_DUPLICATED_NAME, title); try { String oSiteId = (String) state .getAttribute(STATE_SITE_INSTANCE_ID); String nSiteId = IdManager.createUuid(); Site site = SiteService.addSite(nSiteId, getStateSite(state)); try { SiteService.save(site); } catch (IdUnusedException e) { // TODO: } catch (PermissionException e) { // TODO: } try { site = SiteService.getSite(nSiteId); // set title site.setTitle(title); // import tool content List pageList = site.getPages(); if (!((pageList == null) || (pageList.size() == 0))) { for (ListIterator i = pageList .listIterator(); i.hasNext();) { SitePage page = (SitePage) i.next(); List pageToolList = page.getTools(); String toolId = ((ToolConfiguration) pageToolList .get(0)).getTool().getId(); if (toolId .equalsIgnoreCase("sakai.resources")) { // handle // resource // tool // specially transferCopyEntities( toolId, ContentHostingService .getSiteCollection(oSiteId), ContentHostingService .getSiteCollection(nSiteId)); } else { // other // tools transferCopyEntities(toolId, oSiteId, nSiteId); } } } } catch (Exception e1) { // if goes here, IdService // or SiteService has done // something wrong. M_log.warn(this + "Exception" + e1 + ":" + nSiteId + "when duplicating site"); } if (site.getType().equals((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { // for course site, need to // read in the input for // term information String termId = StringUtil.trimToNull(params .getString("selectTerm")); if (termId != null) { AcademicSession term = cms.getAcademicSession(termId); if (term != null) { ResourcePropertiesEdit rp = site.getPropertiesEdit(); rp.addProperty(PROP_SITE_TERM, term.getTitle()); rp.addProperty(PROP_SITE_TERM_EID, term.getEid()); } else { M_log.warn("termId=" + termId + " not found"); } } } try { SiteService.save(site); } catch (IdUnusedException e) { // TODO: } catch (PermissionException e) { // TODO: } // TODO: hard coding this frame id // is fragile, portal dependent, and // needs to be fixed -ggolden // schedulePeerFrameRefresh("sitenav"); scheduleTopRefresh(); state.setAttribute(SITE_DUPLICATED, Boolean.TRUE); } catch (IdInvalidException e) { addAlert(state, rb.getString("java.siteinval")); } catch (IdUsedException e) { addAlert(state, rb.getString("java.sitebeenused") + " "); } catch (PermissionException e) { addAlert(state, rb.getString("java.allowcreate") + " "); } } } if (state.getAttribute(STATE_MESSAGE) == null) { // site duplication confirmed state.removeAttribute(SITE_DUPLICATED); state.removeAttribute(SITE_DUPLICATED_NAME); // return to the list view state.setAttribute(STATE_TEMPLATE_INDEX, "12"); } } break; case 33: break; case 36: /* * actionForTemplate chef_site-newSiteCourse.vm */ if (forward) { List providerChosenList = new Vector(); if (params.getStrings("providerCourseAdd") == null) { state.removeAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN); if (params.getString("manualAdds") == null) { addAlert(state, rb.getString("java.manual") + " "); } } if (state.getAttribute(STATE_MESSAGE) == null) { // The list of courses selected from provider listing if (params.getStrings("providerCourseAdd") != null) { providerChosenList = new ArrayList(Arrays.asList(params .getStrings("providerCourseAdd"))); // list of // course // ids String userId = (String) state .getAttribute(STATE_INSTRUCTOR_SELECTED); String currentUserId = (String) state .getAttribute(STATE_CM_CURRENT_USERID); if (userId == null || (userId != null && userId .equals(currentUserId))) { state.setAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN, providerChosenList); state.removeAttribute(STATE_CM_AUTHORIZER_SECTIONS); state.removeAttribute(FORM_ADDITIONAL); state.removeAttribute(STATE_CM_AUTHORIZER_LIST); } else { // STATE_CM_AUTHORIZER_SECTIONS are SectionObject, // so need to prepare it // also in this page, u can pick either section from // current user OR // sections from another users but not both. - // daisy's note 1 for now // till we are ready to add more complexity List sectionObjectList = prepareSectionObject( providerChosenList, userId); state.setAttribute(STATE_CM_AUTHORIZER_SECTIONS, sectionObjectList); state .removeAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN); // set special instruction & we will keep // STATE_CM_AUTHORIZER_LIST String additional = StringUtil.trimToZero(params .getString("additional")); state.setAttribute(FORM_ADDITIONAL, additional); } } collectNewSiteInfo(siteInfo, state, params, providerChosenList); } // next step state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer(2)); } break; case 38: break; case 39: break; case 42: /* * actionForTemplate chef_site-gradtoolsConfirm.vm * */ break; case 43: /* * actionForTemplate chef_site-editClass.vm * */ if (forward) { if (params.getStrings("providerClassDeletes") == null && params.getStrings("manualClassDeletes") == null && params.getStrings("cmRequestedClassDeletes") == null && !direction.equals("back")) { addAlert(state, rb.getString("java.classes")); } if (params.getStrings("providerClassDeletes") != null) { // build the deletions list List providerCourseList = (List) state .getAttribute(SITE_PROVIDER_COURSE_LIST); List providerCourseDeleteList = new ArrayList(Arrays .asList(params.getStrings("providerClassDeletes"))); for (ListIterator i = providerCourseDeleteList .listIterator(); i.hasNext();) { providerCourseList.remove((String) i.next()); } state.setAttribute(SITE_PROVIDER_COURSE_LIST, providerCourseList); } if (params.getStrings("manualClassDeletes") != null) { // build the deletions list List manualCourseList = (List) state .getAttribute(SITE_MANUAL_COURSE_LIST); List manualCourseDeleteList = new ArrayList(Arrays .asList(params.getStrings("manualClassDeletes"))); for (ListIterator i = manualCourseDeleteList.listIterator(); i .hasNext();) { manualCourseList.remove((String) i.next()); } state.setAttribute(SITE_MANUAL_COURSE_LIST, manualCourseList); } if (params.getStrings("cmRequestedClassDeletes") != null) { // build the deletions list List<SectionObject> cmRequestedCourseList = (List) state.getAttribute(STATE_CM_REQUESTED_SECTIONS); List<String> cmRequestedCourseDeleteList = new ArrayList(Arrays.asList(params.getStrings("cmRequestedClassDeletes"))); for (ListIterator i = cmRequestedCourseDeleteList.listIterator(); i .hasNext();) { String sectionId = (String) i.next(); try { SectionObject so = new SectionObject(cms.getSection(sectionId)); SectionObject soFound = null; for (Iterator j = cmRequestedCourseList.iterator(); soFound == null && j.hasNext();) { SectionObject k = (SectionObject) j.next(); if (k.eid.equals(sectionId)) { soFound = k; } } if (soFound != null) cmRequestedCourseList.remove(soFound); } catch (Exception e) { M_log.warn(e.getMessage() + sectionId); } } state.setAttribute(STATE_CM_REQUESTED_SECTIONS, cmRequestedCourseList); } updateCourseClasses(state, new Vector(), new Vector()); } break; case 44: if (forward) { AcademicSession a = (AcademicSession) state.getAttribute(STATE_TERM_SELECTED); Site site = getStateSite(state); ResourcePropertiesEdit pEdit = site.getPropertiesEdit(); // update the course site property and realm based on the selection updateCourseSiteSections(state, site.getId(), pEdit, a); try { SiteService.save(site); } catch (Exception e) { M_log.warn(e.getMessage() + site.getId()); } removeAddClassContext(state); } break; case 49: if (!forward) { state.removeAttribute(SORTED_BY); state.removeAttribute(SORTED_ASC); } break; } }// actionFor Template /** * update current step index within the site creation wizard * * @param state * The SessionState object * @param forward * Moving forward or backward? */ private void updateCurrentStep(SessionState state, boolean forward) { if (state.getAttribute(SITE_CREATE_CURRENT_STEP) != null) { int currentStep = ((Integer) state .getAttribute(SITE_CREATE_CURRENT_STEP)).intValue(); if (forward) { state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer( currentStep + 1)); } else { state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer( currentStep - 1)); } } } /** * remove related state variable for adding class * * @param state * SessionState object */ private void removeAddClassContext(SessionState state) { // remove related state variables state.removeAttribute(STATE_ADD_CLASS_MANUAL); state.removeAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN); state.removeAttribute(STATE_MANUAL_ADD_COURSE_NUMBER); state.removeAttribute(STATE_MANUAL_ADD_COURSE_FIELDS); state.removeAttribute(STATE_SITE_QUEST_UNIQNAME); state.removeAttribute(STATE_AUTO_ADD); state.removeAttribute(SITE_CREATE_TOTAL_STEPS); state.removeAttribute(SITE_CREATE_CURRENT_STEP); state.removeAttribute(STATE_IMPORT_SITE_TOOL); state.removeAttribute(STATE_IMPORT_SITES); state.removeAttribute(STATE_CM_REQUESTED_SECTIONS); state.removeAttribute(STATE_CM_SELECTED_SECTIONS); sitePropertiesIntoState(state); } // removeAddClassContext private void updateCourseClasses(SessionState state, List notifyClasses, List requestClasses) { List providerCourseSectionList = (List) state.getAttribute(SITE_PROVIDER_COURSE_LIST); List manualCourseSectionList = (List) state.getAttribute(SITE_MANUAL_COURSE_LIST); List<SectionObject> cmRequestedCourseList = (List) state.getAttribute(STATE_CM_REQUESTED_SECTIONS); Site site = getStateSite(state); String id = site.getId(); String realmId = SiteService.siteReference(id); if ((providerCourseSectionList == null) || (providerCourseSectionList.size() == 0)) { // no section access so remove Provider Id try { AuthzGroup realmEdit1 = AuthzGroupService .getAuthzGroup(realmId); realmEdit1.setProviderGroupId(NULL_STRING); AuthzGroupService.save(realmEdit1); } catch (GroupNotDefinedException e) { M_log.warn(this + " IdUnusedException, " + site.getTitle() + "(" + realmId + ") not found, or not an AuthzGroup object"); addAlert(state, rb.getString("java.cannotedit")); return; } catch (AuthzPermissionException e) { M_log .warn(this + " PermissionException, user does not have permission to edit AuthzGroup object " + site.getTitle() + "(" + realmId + "). "); addAlert(state, rb.getString("java.notaccess")); return; } } if ((providerCourseSectionList != null) && (providerCourseSectionList.size() != 0)) { // section access so rewrite Provider Id String externalRealm = buildExternalRealm(id, state, providerCourseSectionList); try { AuthzGroup realmEdit2 = AuthzGroupService .getAuthzGroup(realmId); realmEdit2.setProviderGroupId(externalRealm); AuthzGroupService.save(realmEdit2); } catch (GroupNotDefinedException e) { M_log.warn(this + " IdUnusedException, " + site.getTitle() + "(" + realmId + ") not found, or not an AuthzGroup object"); addAlert(state, rb.getString("java.cannotclasses")); return; } catch (AuthzPermissionException e) { M_log .warn(this + " PermissionException, user does not have permission to edit AuthzGroup object " + site.getTitle() + "(" + realmId + "). "); addAlert(state, rb.getString("java.notaccess")); return; } } // the manual request course into properties setSiteSectionProperty(manualCourseSectionList, site, PROP_SITE_REQUEST_COURSE); // the cm request course into properties setSiteSectionProperty(cmRequestedCourseList, site, STATE_CM_REQUESTED_SECTIONS); if (state.getAttribute(STATE_MESSAGE) == null) { commitSite(site); } else { } if (requestClasses != null && requestClasses.size() > 0 && state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { try { // send out class request notifications sendSiteRequest(state, "change", ((Integer) state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue(), (List<SectionObject>) state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS), "manual"); } catch (Exception e) { M_log.warn(this + e.toString()); } } if (notifyClasses != null && notifyClasses.size() > 0) { try { // send out class access confirmation notifications sendSiteNotification(state, notifyClasses); } catch (Exception e) { M_log.warn(this + e.toString()); } } } // updateCourseClasses private void setSiteSectionProperty(List courseSectionList, Site site, String propertyName) { if ((courseSectionList != null) && (courseSectionList.size() != 0)) { // store the requested sections in one site property String sections = ""; for (int j = 0; j < courseSectionList.size();) { sections = sections + (String) courseSectionList.get(j); j++; if (j < courseSectionList.size()) { sections = sections + "+"; } } ResourcePropertiesEdit rp = site.getPropertiesEdit(); rp.addProperty(propertyName, sections); } else { ResourcePropertiesEdit rp = site.getPropertiesEdit(); rp.removeProperty(propertyName); } } /** * Sets selected roles for multiple users * * @param params * The ParameterParser object * @param listName * The state variable */ private void getSelectedRoles(SessionState state, ParameterParser params, String listName) { Hashtable pSelectedRoles = (Hashtable) state .getAttribute(STATE_SELECTED_PARTICIPANT_ROLES); if (pSelectedRoles == null) { pSelectedRoles = new Hashtable(); } List userList = (List) state.getAttribute(listName); for (int i = 0; i < userList.size(); i++) { String userId = null; if (listName.equalsIgnoreCase(STATE_ADD_PARTICIPANTS)) { userId = ((Participant) userList.get(i)).getUniqname(); } else if (listName.equalsIgnoreCase(STATE_SELECTED_USER_LIST)) { userId = (String) userList.get(i); } if (userId != null) { String rId = StringUtil.trimToNull(params.getString("role" + userId)); if (rId == null) { addAlert(state, rb.getString("java.rolefor") + " " + userId + ". "); pSelectedRoles.remove(userId); } else { pSelectedRoles.put(userId, rId); } } } state.setAttribute(STATE_SELECTED_PARTICIPANT_ROLES, pSelectedRoles); } // getSelectedRoles /** * dispatch function for changing participants roles */ public void doSiteinfo_edit_role(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String option = params.getString("option"); // dispatch if (option.equalsIgnoreCase("same_role_true")) { state.setAttribute(STATE_CHANGEROLE_SAMEROLE, Boolean.TRUE); state.setAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE, params .getString("role_to_all")); } else if (option.equalsIgnoreCase("same_role_false")) { state.setAttribute(STATE_CHANGEROLE_SAMEROLE, Boolean.FALSE); state.removeAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE); if (state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES) == null) { state.setAttribute(STATE_SELECTED_PARTICIPANT_ROLES, new Hashtable()); } } else if (option.equalsIgnoreCase("continue")) { doContinue(data); } else if (option.equalsIgnoreCase("back")) { doBack(data); } else if (option.equalsIgnoreCase("cancel")) { doCancel(data); } } // doSiteinfo_edit_globalAccess /** * dispatch function for changing site global access */ public void doSiteinfo_edit_globalAccess(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String option = params.getString("option"); // dispatch if (option.equalsIgnoreCase("joinable")) { state.setAttribute("form_joinable", Boolean.TRUE); state.setAttribute("form_joinerRole", getStateSite(state) .getJoinerRole()); } else if (option.equalsIgnoreCase("unjoinable")) { state.setAttribute("form_joinable", Boolean.FALSE); state.removeAttribute("form_joinerRole"); } else if (option.equalsIgnoreCase("continue")) { doContinue(data); } else if (option.equalsIgnoreCase("cancel")) { doCancel(data); } } // doSiteinfo_edit_globalAccess /** * save changes to site global access */ public void doSiteinfo_save_globalAccess(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); Site s = getStateSite(state); boolean joinable = ((Boolean) state.getAttribute("form_joinable")) .booleanValue(); s.setJoinable(joinable); if (joinable) { // set the joiner role String joinerRole = (String) state.getAttribute("form_joinerRole"); s.setJoinerRole(joinerRole); } if (state.getAttribute(STATE_MESSAGE) == null) { // release site edit commitSite(s); state.setAttribute(STATE_TEMPLATE_INDEX, "18"); } } // doSiteinfo_save_globalAccess /** * updateSiteAttributes * */ private void updateSiteAttributes(SessionState state) { SiteInfo siteInfo = new SiteInfo(); if (state.getAttribute(STATE_SITE_INFO) != null) { siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); } else { M_log .warn("SiteAction.updateSiteAttributes STATE_SITE_INFO == null"); return; } Site site = getStateSite(state); if (site != null) { if (StringUtil.trimToNull(siteInfo.title) != null) { site.setTitle(siteInfo.title); } if (siteInfo.description != null) { site.setDescription(siteInfo.description); } site.setPublished(siteInfo.published); setAppearance(state, site, siteInfo.iconUrl); site.setJoinable(siteInfo.joinable); if (StringUtil.trimToNull(siteInfo.joinerRole) != null) { site.setJoinerRole(siteInfo.joinerRole); } // Make changes and then put changed site back in state String id = site.getId(); try { SiteService.save(site); } catch (IdUnusedException e) { // TODO: } catch (PermissionException e) { // TODO: } if (SiteService.allowUpdateSite(id)) { try { SiteService.getSite(id); state.setAttribute(STATE_SITE_INSTANCE_ID, id); } catch (IdUnusedException e) { M_log.warn("SiteAction.commitSite IdUnusedException " + siteInfo.getTitle() + "(" + id + ") not found"); } } // no permission else { addAlert(state, rb.getString("java.makechanges")); M_log.warn("SiteAction.commitSite PermissionException " + siteInfo.getTitle() + "(" + id + ")"); } } } // updateSiteAttributes /** * %%% legacy properties, to be removed */ private void updateSiteInfo(ParameterParser params, SessionState state) { SiteInfo siteInfo = new SiteInfo(); if (state.getAttribute(STATE_SITE_INFO) != null) { siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); } siteInfo.site_type = (String) state.getAttribute(STATE_SITE_TYPE); if (params.getString("title") != null) { siteInfo.title = params.getString("title"); } if (params.getString("description") != null) { siteInfo.description = params.getString("description"); } if (params.getString("short_description") != null) { siteInfo.short_description = params.getString("short_description"); } if (params.getString("additional") != null) { siteInfo.additional = params.getString("additional"); } if (params.getString("iconUrl") != null) { siteInfo.iconUrl = params.getString("iconUrl"); } else { siteInfo.iconUrl = params.getString("skin"); } if (params.getString("joinerRole") != null) { siteInfo.joinerRole = params.getString("joinerRole"); } if (params.getString("joinable") != null) { boolean joinable = params.getBoolean("joinable"); siteInfo.joinable = joinable; if (!joinable) siteInfo.joinerRole = NULL_STRING; } if (params.getString("itemStatus") != null) { siteInfo.published = Boolean .valueOf(params.getString("itemStatus")).booleanValue(); } // site contact information String name = StringUtil .trimToZero(params.getString("siteContactName")); siteInfo.site_contact_name = name; String email = StringUtil.trimToZero(params .getString("siteContactEmail")); if (email != null) { String[] parts = email.split("@"); if (email.length() > 0 && (email.indexOf("@") == -1 || parts.length != 2 || parts[0].length() == 0 || !Validator .checkEmailLocal(parts[0]))) { // invalid email addAlert(state, email + " " + rb.getString("java.invalid") + rb.getString("java.theemail")); } siteInfo.site_contact_email = email; } state.setAttribute(STATE_SITE_INFO, siteInfo); } // updateSiteInfo /** * getExternalRealmId * */ private String getExternalRealmId(SessionState state) { String realmId = SiteService.siteReference((String) state .getAttribute(STATE_SITE_INSTANCE_ID)); String rv = null; try { AuthzGroup realm = AuthzGroupService.getAuthzGroup(realmId); rv = realm.getProviderGroupId(); } catch (GroupNotDefinedException e) { M_log.warn("SiteAction.getExternalRealmId, site realm not found"); } return rv; } // getExternalRealmId /** * getParticipantList * */ private Collection getParticipantList(SessionState state) { List members = new Vector(); String realmId = SiteService.siteReference((String) state .getAttribute(STATE_SITE_INSTANCE_ID)); List providerCourseList = null; providerCourseList = getProviderCourseList(StringUtil .trimToNull(getExternalRealmId(state))); if (providerCourseList != null && providerCourseList.size() > 0) { state.setAttribute(SITE_PROVIDER_COURSE_LIST, providerCourseList); } Collection participants = prepareParticipants(realmId, providerCourseList); state.setAttribute(STATE_PARTICIPANT_LIST, participants); return participants; } // getParticipantList private Collection prepareParticipants(String realmId, List providerCourseList) { Map participantsMap = new ConcurrentHashMap(); try { AuthzGroup realm = AuthzGroupService.getAuthzGroup(realmId); realm.getProviderGroupId(); // iterate through the provider list first for (Iterator i=providerCourseList.iterator(); i.hasNext();) { String providerCourseEid = (String) i.next(); try { Section section = cms.getSection(providerCourseEid); if (cms.isSectionDefined(providerCourseEid)) { // in case of Section eid EnrollmentSet enrollmentSet = section.getEnrollmentSet(); addParticipantsFromEnrollmentSet(participantsMap, realm, providerCourseEid, enrollmentSet, section.getTitle()); // add memberships Set memberships = cms.getSectionMemberships(providerCourseEid); addParticipantsFromMemberships(participantsMap, realm, providerCourseEid, memberships, section.getTitle()); } } catch (IdNotFoundException e) { M_log.warn("SiteAction prepareParticipants " + e.getMessage() + " sectionId=" + providerCourseEid); } } // now for those not provided users Set grants = realm.getMembers(); for (Iterator i = grants.iterator(); i.hasNext();) { Member g = (Member) i.next(); if (!g.isProvided()) { try { User user = UserDirectoryService.getUserByEid(g.getUserEid()); String userId = user.getId(); Participant participant; if (participantsMap.containsKey(userId)) { participant = (Participant) participantsMap.get(userId); } else { participant = new Participant(); } participant.name = user.getSortName(); participant.uniqname = userId; participant.role = g.getRole()!=null?g.getRole().getId():""; participant.removeable = true; participantsMap.put(userId, participant); } catch (UserNotDefinedException e) { // deal with missing user quietly without throwing a // warning message M_log.warn(e.getMessage()); } } } } catch (GroupNotDefinedException ee) { M_log.warn(this + " IdUnusedException " + realmId); } return participantsMap.values(); } /** * Add participant from provider-defined membership set * @param participants * @param realm * @param providerCourseEid * @param memberships */ private void addParticipantsFromMemberships(Map participantsMap, AuthzGroup realm, String providerCourseEid, Set memberships, String sectionTitle) { if (memberships != null) { for (Iterator mIterator = memberships.iterator();mIterator.hasNext();) { Membership m = (Membership) mIterator.next(); try { User user = UserDirectoryService.getUserByEid(m.getUserId()); String userId = user.getId(); Member member = realm.getMember(userId); if (member != null && member.isProvided()) { // get or add provided participant Participant participant; if (participantsMap.containsKey(userId)) { participant = (Participant) participantsMap.get(userId); participant.section = participant.section.concat(", <br />" + sectionTitle); } else { participant = new Participant(); participant.credits = ""; participant.name = user.getSortName(); participant.providerRole = member.getRole()!=null?member.getRole().getId():""; participant.regId = ""; participant.removeable = false; participant.role = member.getRole()!=null?member.getRole().getId():""; participant.section = sectionTitle; participant.uniqname = userId; } participantsMap.put(userId, participant); } } catch (UserNotDefinedException exception) { // deal with missing user quietly without throwing a // warning message M_log.warn(exception.getMessage()); } } } } /** * Add participant from provider-defined enrollment set * @param participants * @param realm * @param providerCourseEid * @param enrollmentSet */ private void addParticipantsFromEnrollmentSet(Map participantsMap, AuthzGroup realm, String providerCourseEid, EnrollmentSet enrollmentSet, String sectionTitle) { if (enrollmentSet != null) { Set enrollments = cms.getEnrollments(enrollmentSet.getEid()); for (Iterator eIterator = enrollments.iterator();eIterator.hasNext();) { Enrollment e = (Enrollment) eIterator.next(); try { User user = UserDirectoryService.getUserByEid(e.getUserId()); String userId = user.getId(); Member member = realm.getMember(userId); if (member != null && member.isProvided()) { try { // get or add provided participant Participant participant; if (participantsMap.containsKey(userId)) { participant = (Participant) participantsMap.get(userId); participant.section = participant.section.concat(", <br />" + sectionTitle); participant.credits = participant.credits.concat(", <br />" + e.getCredits()); } else { participant = new Participant(); participant.credits = e.getCredits(); participant.name = user.getSortName(); participant.providerRole = member.getRole()!=null?member.getRole().getId():""; participant.regId = ""; participant.removeable = false; participant.role = member.getRole()!=null?member.getRole().getId():""; participant.section = sectionTitle; participant.uniqname = userId; } participantsMap.put(userId, participant); } catch (Exception ee) { M_log.warn(ee.getMessage()); } } } catch (UserNotDefinedException exception) { // deal with missing user quietly without throwing a // warning message M_log.warn(exception.getMessage()); } } } } /** * getRoles * */ private List getRoles(SessionState state) { List roles = new Vector(); String realmId = SiteService.siteReference((String) state .getAttribute(STATE_SITE_INSTANCE_ID)); try { AuthzGroup realm = AuthzGroupService.getAuthzGroup(realmId); roles.addAll(realm.getRoles()); Collections.sort(roles); } catch (GroupNotDefinedException e) { M_log.warn("SiteAction.getRoles IdUnusedException " + realmId); } return roles; } // getRoles private void addSynopticTool(SitePage page, String toolId, String toolTitle, String layoutHint) { // Add synoptic announcements tool ToolConfiguration tool = page.addTool(); Tool reg = ToolManager.getTool(toolId); tool.setTool(toolId, reg); tool.setTitle(toolTitle); tool.setLayoutHints(layoutHint); } private void getRevisedFeatures(ParameterParser params, SessionState state) { Site site = getStateSite(state); // get the list of Worksite Setup configured pages List wSetupPageList = (List) state .getAttribute(STATE_WORKSITE_SETUP_PAGE_LIST); WorksiteSetupPage wSetupPage = new WorksiteSetupPage(); WorksiteSetupPage wSetupHome = new WorksiteSetupPage(); List pageList = new Vector(); // declare some flags used in making decisions about Home, whether to // add, remove, or do nothing boolean homeInChosenList = false; boolean homeInWSetupPageList = false; List chosenList = (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); // if features were selected, diff wSetupPageList and chosenList to get // page adds and removes // boolean values for adding synoptic views boolean hasAnnouncement = false; boolean hasSchedule = false; boolean hasChat = false; boolean hasDiscussion = false; boolean hasEmail = false; boolean hasNewSiteInfo = false; boolean hasMessageCenter = false; // Special case - Worksite Setup Home comes from a hardcoded checkbox on // the vm template rather than toolRegistrationList // see if Home was chosen for (ListIterator j = chosenList.listIterator(); j.hasNext();) { String choice = (String) j.next(); if (choice.equalsIgnoreCase(HOME_TOOL_ID)) { homeInChosenList = true; } else if (choice.equals("sakai.mailbox")) { hasEmail = true; String alias = StringUtil.trimToNull((String) state .getAttribute(STATE_TOOL_EMAIL_ADDRESS)); if (alias != null) { if (!Validator.checkEmailLocal(alias)) { addAlert(state, rb.getString("java.theemail")); } else { try { String channelReference = mailArchiveChannelReference(site .getId()); // first, clear any alias set to this channel AliasService.removeTargetAliases(channelReference); // check // to // see // whether // the // alias // has // been // used try { String target = AliasService.getTarget(alias); if (target != null) { addAlert(state, rb .getString("java.emailinuse") + " "); } } catch (IdUnusedException ee) { try { AliasService.setAlias(alias, channelReference); } catch (IdUsedException exception) { } catch (IdInvalidException exception) { } catch (PermissionException exception) { } } } catch (PermissionException exception) { } } } } else if (choice.equals("sakai.announcements")) { hasAnnouncement = true; } else if (choice.equals("sakai.schedule")) { hasSchedule = true; } else if (choice.equals("sakai.chat")) { hasChat = true; } else if (choice.equals("sakai.discussion")) { hasDiscussion = true; } else if (choice.equals("sakai.messages") || choice.equals("sakai.forums") || choice.equals("sakai.messagecenter")) { hasMessageCenter = true; } } // see if Home and/or Help in the wSetupPageList (can just check title // here, because we checked patterns before adding to the list) for (ListIterator i = wSetupPageList.listIterator(); i.hasNext();) { wSetupPage = (WorksiteSetupPage) i.next(); if (wSetupPage.getToolId().equals(HOME_TOOL_ID)) { homeInWSetupPageList = true; } } if (homeInChosenList) { SitePage page = null; // Were the synoptic views of Announcement, Discussioin, Chat // existing before the editing boolean hadAnnouncement = false, hadDiscussion = false, hadChat = false, hadSchedule = false, hadMessageCenter = false; if (homeInWSetupPageList) { if (!SiteService.isUserSite(site.getId())) { // for non-myworkspace site, if Home is chosen and Home is // in the wSetupPageList, remove synoptic tools WorksiteSetupPage homePage = new WorksiteSetupPage(); for (ListIterator i = wSetupPageList.listIterator(); i .hasNext();) { WorksiteSetupPage comparePage = (WorksiteSetupPage) i .next(); if ((comparePage.getToolId()).equals(HOME_TOOL_ID)) { homePage = comparePage; } } page = site.getPage(homePage.getPageId()); List toolList = page.getTools(); List removeToolList = new Vector(); // get those synoptic tools for (ListIterator iToolList = toolList.listIterator(); iToolList .hasNext();) { ToolConfiguration tool = (ToolConfiguration) iToolList .next(); Tool t = tool.getTool(); if (t!= null) { if (t.getId().equals("sakai.synoptic.announcement")) { hadAnnouncement = true; if (!hasAnnouncement) { removeToolList.add(tool);// if Announcement // tool isn't // selected, remove // the synotic // Announcement } } else if (t.getId().equals(TOOL_ID_SUMMARY_CALENDAR)) { hadSchedule = true; if (!hasSchedule || !notStealthOrHiddenTool(TOOL_ID_SUMMARY_CALENDAR)) { // if Schedule tool isn't selected, or the summary calendar tool is stealthed or hidden, remove the synotic Schedule removeToolList.add(tool); } } else if (t.getId().equals("sakai.synoptic.discussion")) { hadDiscussion = true; if (!hasDiscussion) { removeToolList.add(tool);// if Discussion // tool isn't // selected, remove // the synoptic // Discussion } } else if (t.getId().equals("sakai.synoptic.chat")) { hadChat = true; if (!hasChat) { removeToolList.add(tool);// if Chat tool // isn't selected, // remove the // synoptic Chat } } else if (t.getId().equals("sakai.synoptic.messagecenter")) { hadMessageCenter = true; if (!hasMessageCenter) { removeToolList.add(tool);// if Messages and/or Forums tools // isn't selected, // remove the // synoptic Message Center tool } } } } // remove those synoptic tools for (ListIterator rToolList = removeToolList.listIterator(); rToolList .hasNext();) { page.removeTool((ToolConfiguration) rToolList.next()); } } } else { // if Home is chosen and Home is not in wSetupPageList, add Home // to site and wSetupPageList page = site.addPage(); page.setTitle(rb.getString("java.home")); wSetupHome.pageId = page.getId(); wSetupHome.pageTitle = page.getTitle(); wSetupHome.toolId = HOME_TOOL_ID; wSetupPageList.add(wSetupHome); // Add worksite information tool ToolConfiguration tool = page.addTool(); Tool reg = ToolManager.getTool("sakai.iframe.site"); tool.setTool("sakai.iframe.site", reg); tool.setTitle(reg.getTitle()); tool.setLayoutHints("0,0"); } if (!SiteService.isUserSite(site.getId())) { // add synoptical tools to home tool in non-myworkspace site try { if (hasAnnouncement && !hadAnnouncement) { // Add synoptic announcements tool addSynopticTool(page, "sakai.synoptic.announcement", rb .getString("java.recann"), "0,1"); } if (hasDiscussion && !hadDiscussion) { // Add synoptic discussion tool addSynopticTool(page, "sakai.synoptic.discussion", rb .getString("java.recdisc"), "1,1"); } if (hasChat && !hadChat) { // Add synoptic chat tool addSynopticTool(page, "sakai.synoptic.chat", rb .getString("java.recent"), "2,1"); } if (hasSchedule && !hadSchedule) { // Add synoptic schedule tool if not stealth or hidden if (notStealthOrHiddenTool(TOOL_ID_SUMMARY_CALENDAR)) addSynopticTool(page, TOOL_ID_SUMMARY_CALENDAR, rb .getString("java.reccal"), "3,1"); } if (hasMessageCenter && !hadMessageCenter) { // Add synoptic Message Center addSynopticTool(page, "sakai.synoptic.messagecenter", rb .getString("java.recmsg"), "4,1"); } if (hasAnnouncement || hasDiscussion || hasChat || hasSchedule || hasMessageCenter) { page.setLayout(SitePage.LAYOUT_DOUBLE_COL); } else { page.setLayout(SitePage.LAYOUT_SINGLE_COL); } } catch (Exception e) { M_log.warn("SiteAction getRevisedFeatures Exception: " + e.getMessage()); } } } // add Home // if Home is in wSetupPageList and not chosen, remove Home feature from // wSetupPageList and site if (!homeInChosenList && homeInWSetupPageList) { // remove Home from wSetupPageList WorksiteSetupPage removePage = new WorksiteSetupPage(); for (ListIterator i = wSetupPageList.listIterator(); i.hasNext();) { WorksiteSetupPage comparePage = (WorksiteSetupPage) i.next(); if (comparePage.getToolId().equals(HOME_TOOL_ID)) { removePage = comparePage; } } SitePage siteHome = site.getPage(removePage.getPageId()); site.removePage(siteHome); wSetupPageList.remove(removePage); } // declare flags used in making decisions about whether to add, remove, // or do nothing boolean inChosenList; boolean inWSetupPageList; Hashtable newsTitles = (Hashtable) state .getAttribute(STATE_NEWS_TITLES); Hashtable wcTitles = (Hashtable) state .getAttribute(STATE_WEB_CONTENT_TITLES); Hashtable newsUrls = (Hashtable) state.getAttribute(STATE_NEWS_URLS); Hashtable wcUrls = (Hashtable) state .getAttribute(STATE_WEB_CONTENT_URLS); Set categories = new HashSet(); categories.add((String) state.getAttribute(STATE_SITE_TYPE)); Set toolRegistrationList = ToolManager.findTools(categories, null); // first looking for any tool for removal Vector removePageIds = new Vector(); for (ListIterator k = wSetupPageList.listIterator(); k.hasNext();) { wSetupPage = (WorksiteSetupPage) k.next(); String pageToolId = wSetupPage.getToolId(); // use page id + tool id for multiple News and Web Content tool if (pageToolId.indexOf("sakai.news") != -1 || pageToolId.indexOf("sakai.iframe") != -1) { pageToolId = wSetupPage.getPageId() + pageToolId; } inChosenList = false; for (ListIterator j = chosenList.listIterator(); j.hasNext();) { String toolId = (String) j.next(); if (pageToolId.equals(toolId)) { inChosenList = true; } } if (!inChosenList) { removePageIds.add(wSetupPage.getPageId()); } } for (int i = 0; i < removePageIds.size(); i++) { // if the tool exists in the wSetupPageList, remove it from the site String removeId = (String) removePageIds.get(i); SitePage sitePage = site.getPage(removeId); site.removePage(sitePage); // and remove it from wSetupPageList for (ListIterator k = wSetupPageList.listIterator(); k.hasNext();) { wSetupPage = (WorksiteSetupPage) k.next(); if (!wSetupPage.getPageId().equals(removeId)) { wSetupPage = null; } } if (wSetupPage != null) { wSetupPageList.remove(wSetupPage); } } // then looking for any tool to add for (ListIterator j = orderToolIds(state, (String) state.getAttribute(STATE_SITE_TYPE), chosenList) .listIterator(); j.hasNext();) { String toolId = (String) j.next(); // Is the tool in the wSetupPageList? inWSetupPageList = false; for (ListIterator k = wSetupPageList.listIterator(); k.hasNext();) { wSetupPage = (WorksiteSetupPage) k.next(); String pageToolId = wSetupPage.getToolId(); // use page Id + toolId for multiple News and Web Content tool if (pageToolId.indexOf("sakai.news") != -1 || pageToolId.indexOf("sakai.iframe") != -1) { pageToolId = wSetupPage.getPageId() + pageToolId; } if (pageToolId.equals(toolId)) { inWSetupPageList = true; // but for News and Web Content tool, need to change the // title if (toolId.indexOf("sakai.news") != -1) { SitePage pEdit = (SitePage) site .getPage(wSetupPage.pageId); pEdit.setTitle((String) newsTitles.get(toolId)); List toolList = pEdit.getTools(); for (ListIterator jTool = toolList.listIterator(); jTool .hasNext();) { ToolConfiguration tool = (ToolConfiguration) jTool .next(); if (tool.getTool().getId().equals("sakai.news")) { // set News tool title tool.setTitle((String) newsTitles.get(toolId)); // set News tool url String urlString = (String) newsUrls .get(toolId); try { URL url = new URL(urlString); // update the tool config tool.getPlacementConfig().setProperty( "channel-url", (String) url.toExternalForm()); } catch (MalformedURLException e) { addAlert(state, rb.getString("java.invurl") + " " + urlString + ". "); } } } } else if (toolId.indexOf("sakai.iframe") != -1) { SitePage pEdit = (SitePage) site .getPage(wSetupPage.pageId); pEdit.setTitle((String) wcTitles.get(toolId)); List toolList = pEdit.getTools(); for (ListIterator jTool = toolList.listIterator(); jTool .hasNext();) { ToolConfiguration tool = (ToolConfiguration) jTool .next(); if (tool.getTool().getId().equals("sakai.iframe")) { // set Web Content tool title tool.setTitle((String) wcTitles.get(toolId)); // set Web Content tool url String wcUrl = StringUtil .trimToNull((String) wcUrls.get(toolId)); if (wcUrl != null && !wcUrl .equals(WEB_CONTENT_DEFAULT_URL)) { // if url is not empty and not consists only // of "http://" tool.getPlacementConfig().setProperty( "source", wcUrl); } } } } } } if (inWSetupPageList) { // if the tool already in the list, do nothing so to save the // option settings } else { // if in chosen list but not in wSetupPageList, add it to the // site (one tool on a page) // if Site Info tool is being newly added if (toolId.equals("sakai.siteinfo")) { hasNewSiteInfo = true; } Tool toolRegFound = null; for (Iterator i = toolRegistrationList.iterator(); i.hasNext();) { Tool toolReg = (Tool) i.next(); if ((toolId.indexOf("assignment") != -1 && toolId .equals(toolReg.getId())) || (toolId.indexOf("assignment") == -1 && toolId .indexOf(toolReg.getId()) != -1)) { toolRegFound = toolReg; } } if (toolRegFound != null) { // we know such a tool, so add it WorksiteSetupPage addPage = new WorksiteSetupPage(); SitePage page = site.addPage(); addPage.pageId = page.getId(); if (toolId.indexOf("sakai.news") != -1) { // set News tool title page.setTitle((String) newsTitles.get(toolId)); } else if (toolId.indexOf("sakai.iframe") != -1) { // set Web Content tool title page.setTitle((String) wcTitles.get(toolId)); } else { // other tools with default title page.setTitle(toolRegFound.getTitle()); } page.setLayout(SitePage.LAYOUT_SINGLE_COL); ToolConfiguration tool = page.addTool(); tool.setTool(toolRegFound.getId(), toolRegFound); addPage.toolId = toolId; wSetupPageList.add(addPage); // set tool title if (toolId.indexOf("sakai.news") != -1) { // set News tool title tool.setTitle((String) newsTitles.get(toolId)); // set News tool url String urlString = (String) newsUrls.get(toolId); try { URL url = new URL(urlString); // update the tool config tool.getPlacementConfig().setProperty( "channel-url", (String) url.toExternalForm()); } catch (MalformedURLException e) { // display message addAlert(state, "Invalid URL " + urlString + ". "); // remove the page because of invalid url site.removePage(page); } } else if (toolId.indexOf("sakai.iframe") != -1) { // set Web Content tool title tool.setTitle((String) wcTitles.get(toolId)); // set Web Content tool url String wcUrl = StringUtil.trimToNull((String) wcUrls .get(toolId)); if (wcUrl != null && !wcUrl.equals(WEB_CONTENT_DEFAULT_URL)) { // if url is not empty and not consists only of // "http://" tool.getPlacementConfig().setProperty("source", wcUrl); } } else { tool.setTitle(toolRegFound.getTitle()); } } } } // for if (homeInChosenList) { // Order tools - move Home to the top - first find it SitePage homePage = null; pageList = site.getPages(); if (pageList != null && pageList.size() != 0) { for (ListIterator i = pageList.listIterator(); i.hasNext();) { SitePage page = (SitePage) i.next(); if (rb.getString("java.home").equals(page.getTitle()))// if // ("Home".equals(page.getTitle())) { homePage = page; break; } } } // if found, move it if (homePage != null) { // move home from it's index to the first position int homePosition = pageList.indexOf(homePage); for (int n = 0; n < homePosition; n++) { homePage.moveUp(); } } } // if Site Info is newly added, more it to the last if (hasNewSiteInfo) { SitePage siteInfoPage = null; pageList = site.getPages(); String[] toolIds = { "sakai.siteinfo" }; if (pageList != null && pageList.size() != 0) { for (ListIterator i = pageList.listIterator(); siteInfoPage == null && i.hasNext();) { SitePage page = (SitePage) i.next(); int s = page.getTools(toolIds).size(); if (s > 0) { siteInfoPage = page; } } } // if found, move it if (siteInfoPage != null) { // move home from it's index to the first position int siteInfoPosition = pageList.indexOf(siteInfoPage); for (int n = siteInfoPosition; n < pageList.size(); n++) { siteInfoPage.moveDown(); } } } // if there is no email tool chosen if (!hasEmail) { state.removeAttribute(STATE_TOOL_EMAIL_ADDRESS); } // commit commitSite(site); } // getRevisedFeatures /** * Is the tool stealthed or hidden * @param toolId * @return */ private boolean notStealthOrHiddenTool(String toolId) { return (ToolManager.getTool(toolId) != null && !ServerConfigurationService .getString( "[email protected]") .contains(toolId) && !ServerConfigurationService .getString( "[email protected]") .contains(toolId)); } /** * getFeatures gets features for a new site * */ private void getFeatures(ParameterParser params, SessionState state) { List idsSelected = new Vector(); boolean goToENWPage = false; boolean homeSelected = false; // Add new pages and tools, if any if (params.getStrings("selectedTools") == null) { addAlert(state, rb.getString("atleastonetool")); } else { List l = new ArrayList(Arrays.asList(params .getStrings("selectedTools"))); // toolId's & titles of // chosen tools for (int i = 0; i < l.size(); i++) { String toolId = (String) l.get(i); if (toolId.equals("sakai.mailbox") || toolId.indexOf("sakai.news") != -1 || toolId.indexOf("sakai.iframe") != -1) { goToENWPage = true; } else if (toolId.equals(HOME_TOOL_ID)) { homeSelected = true; } idsSelected.add(toolId); } state.setAttribute(STATE_TOOL_HOME_SELECTED, new Boolean( homeSelected)); } String importString = params.getString("import"); if (importString != null && importString.equalsIgnoreCase(Boolean.TRUE.toString())) { state.setAttribute(STATE_IMPORT, Boolean.TRUE); List importSites = new Vector(); if (params.getStrings("importSites") != null) { importSites = new ArrayList(Arrays.asList(params .getStrings("importSites"))); } if (importSites.size() == 0) { addAlert(state, rb.getString("java.toimport") + " "); } else { Hashtable sites = new Hashtable(); for (int index = 0; index < importSites.size(); index++) { try { Site s = SiteService.getSite((String) importSites .get(index)); if (!sites.containsKey(s)) { sites.put(s, new Vector()); } } catch (IdUnusedException e) { } } state.setAttribute(STATE_IMPORT_SITES, sites); } } else { state.removeAttribute(STATE_IMPORT); } state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, idsSelected); // List // of // ToolRegistration // toolId's if (state.getAttribute(STATE_MESSAGE) == null) { if (state.getAttribute(STATE_IMPORT) != null) { // go to import tool page state.setAttribute(STATE_TEMPLATE_INDEX, "27"); } else if (goToENWPage) { // go to the configuration page for Email Archive, News and Web // Content tools state.setAttribute(STATE_TEMPLATE_INDEX, "26"); } else { // go to edit access page state.setAttribute(STATE_TEMPLATE_INDEX, "18"); } int totalSteps = 4; if (state.getAttribute(STATE_SITE_TYPE) != null && ((String) state.getAttribute(STATE_SITE_TYPE)) .equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { totalSteps = 5; if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null && state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { totalSteps++; } } if (state.getAttribute(STATE_IMPORT) != null) { totalSteps++; } if (goToENWPage) { totalSteps++; } state .setAttribute(SITE_CREATE_TOTAL_STEPS, new Integer( totalSteps)); } } // getFeatures /** * addFeatures adds features to a new site * */ private void addFeatures(SessionState state) { List toolRegistrationList = (Vector) state .getAttribute(STATE_TOOL_REGISTRATION_LIST); Site site = getStateSite(state); List pageList = new Vector(); int moves = 0; boolean hasHome = false; boolean hasAnnouncement = false; boolean hasSchedule = false; boolean hasChat = false; boolean hasDiscussion = false; boolean hasSiteInfo = false; boolean hasMessageCenter = false; List chosenList = (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); // tools to be imported from other sites? Hashtable importTools = null; if (state.getAttribute(STATE_IMPORT_SITE_TOOL) != null) { importTools = (Hashtable) state .getAttribute(STATE_IMPORT_SITE_TOOL); } // for tools other than home if (chosenList.contains(HOME_TOOL_ID)) { // add home tool later hasHome = true; } // order the id list chosenList = orderToolIds(state, site.getType(), chosenList); // titles for news tools Hashtable newsTitles = (Hashtable) state .getAttribute(STATE_NEWS_TITLES); // urls for news tools Hashtable newsUrls = (Hashtable) state.getAttribute(STATE_NEWS_URLS); // titles for web content tools Hashtable wcTitles = (Hashtable) state .getAttribute(STATE_WEB_CONTENT_TITLES); // urls for web content tools Hashtable wcUrls = (Hashtable) state .getAttribute(STATE_WEB_CONTENT_URLS); if (chosenList.size() > 0) { Tool toolRegFound = null; for (ListIterator i = chosenList.listIterator(); i.hasNext();) { String toolId = (String) i.next(); // find the tool in the tool registration list toolRegFound = null; for (int j = 0; j < toolRegistrationList.size() && toolRegFound == null; j++) { MyTool tool = (MyTool) toolRegistrationList.get(j); if ((toolId.indexOf("assignment") != -1 && toolId .equals(tool.getId())) || (toolId.indexOf("assignment") == -1 && toolId .indexOf(tool.getId()) != -1)) { toolRegFound = ToolManager.getTool(tool.getId()); } } if (toolRegFound != null) { if (toolId.indexOf("sakai.news") != -1) { // adding multiple news tool String newsTitle = (String) newsTitles.get(toolId); SitePage page = site.addPage(); page.setTitle(newsTitle); // the visible label on the // tool menu page.setLayout(SitePage.LAYOUT_SINGLE_COL); ToolConfiguration tool = page.addTool(); tool.setTool("sakai.news", ToolManager .getTool("sakai.news")); tool.setTitle(newsTitle); tool.setLayoutHints("0,0"); String urlString = (String) newsUrls.get(toolId); // update the tool config tool.getPlacementConfig().setProperty("channel-url", urlString); } else if (toolId.indexOf("sakai.iframe") != -1) { // adding multiple web content tool String wcTitle = (String) wcTitles.get(toolId); SitePage page = site.addPage(); page.setTitle(wcTitle); // the visible label on the tool // menu page.setLayout(SitePage.LAYOUT_SINGLE_COL); ToolConfiguration tool = page.addTool(); tool.setTool("sakai.iframe", ToolManager .getTool("sakai.iframe")); tool.setTitle(wcTitle); tool.setLayoutHints("0,0"); String wcUrl = StringUtil.trimToNull((String) wcUrls .get(toolId)); if (wcUrl != null && !wcUrl.equals(WEB_CONTENT_DEFAULT_URL)) { // if url is not empty and not consists only of // "http://" tool.getPlacementConfig().setProperty("source", wcUrl); } } else { SitePage page = site.addPage(); page.setTitle(toolRegFound.getTitle()); // the visible // label on the // tool menu page.setLayout(SitePage.LAYOUT_SINGLE_COL); ToolConfiguration tool = page.addTool(); tool.setTool(toolRegFound.getId(), toolRegFound); tool.setLayoutHints("0,0"); } // Other features } // booleans for synoptic views if (toolId.equals("sakai.announcements")) { hasAnnouncement = true; } else if (toolId.equals("sakai.schedule")) { hasSchedule = true; } else if (toolId.equals("sakai.chat")) { hasChat = true; } else if (toolId.equals("sakai.discussion")) { hasDiscussion = true; } else if (toolId.equals("sakai.siteinfo")) { hasSiteInfo = true; } else if (toolId.equals("sakai.messages") || toolId.equals("sakai.forums") || toolId.equals("sakai.messagecenter")) { hasMessageCenter = true; } } // for // add home tool if (hasHome) { // Home is a special case, with several tools on the page. // "home" is hard coded in chef_site-addRemoveFeatures.vm. try { SitePage page = site.addPage(); page.setTitle(rb.getString("java.home")); // the visible // label on the // tool menu if (hasAnnouncement || hasDiscussion || hasChat || hasSchedule) { page.setLayout(SitePage.LAYOUT_DOUBLE_COL); } else { page.setLayout(SitePage.LAYOUT_SINGLE_COL); } // Add worksite information tool ToolConfiguration tool = page.addTool(); Tool wsInfoTool = ToolManager.getTool("sakai.iframe.site"); tool.setTool("sakai.iframe.site", wsInfoTool); tool.setTitle(wsInfoTool != null?wsInfoTool.getTitle():""); tool.setLayoutHints("0,0"); if (hasAnnouncement) { // Add synoptic announcements tool tool = page.addTool(); tool.setTool("sakai.synoptic.announcement", ToolManager .getTool("sakai.synoptic.announcement")); tool.setTitle(rb.getString("java.recann")); tool.setLayoutHints("0,1"); } if (hasDiscussion) { // Add synoptic announcements tool tool = page.addTool(); tool.setTool("sakai.synoptic.discussion", ToolManager .getTool("sakai.synoptic.discussion")); tool.setTitle("Recent Discussion Items"); tool.setLayoutHints("1,1"); } if (hasChat) { // Add synoptic chat tool tool = page.addTool(); tool.setTool("sakai.synoptic.chat", ToolManager .getTool("sakai.synoptic.chat")); tool.setTitle("Recent Chat Messages"); tool.setLayoutHints("2,1"); } if (hasSchedule && notStealthOrHiddenTool(TOOL_ID_SUMMARY_CALENDAR)) { // Add synoptic schedule tool tool = page.addTool(); tool.setTool(TOOL_ID_SUMMARY_CALENDAR, ToolManager .getTool(TOOL_ID_SUMMARY_CALENDAR)); tool.setTitle(rb.getString("java.reccal")); tool.setLayoutHints("3,1"); } if (hasMessageCenter) { // Add synoptic Message Center tool tool = page.addTool(); tool.setTool("sakai.synoptic.messagecenter", ToolManager .getTool("sakai.synoptic.messagecenter")); tool.setTitle(rb.getString("java.recmsg")); tool.setLayoutHints("4,1"); } } catch (Exception e) { M_log.warn("SiteAction addFeatures Exception:" + e.getMessage()); } state.setAttribute(STATE_TOOL_HOME_SELECTED, Boolean.TRUE); // Order tools - move Home to the top pageList = site.getPages(); if (pageList != null && pageList.size() != 0) { for (ListIterator i = pageList.listIterator(); i.hasNext();) { SitePage page = (SitePage) i.next(); if ((page.getTitle()).equals(rb.getString("java.home"))) { moves = pageList.indexOf(page); for (int n = 0; n < moves; n++) { page.moveUp(); } } } } } // Home feature // move Site Info tool, if selected, to the end of tool list if (hasSiteInfo) { SitePage siteInfoPage = null; pageList = site.getPages(); String[] toolIds = { "sakai.siteinfo" }; if (pageList != null && pageList.size() != 0) { for (ListIterator i = pageList.listIterator(); siteInfoPage == null && i.hasNext();) { SitePage page = (SitePage) i.next(); int s = page.getTools(toolIds).size(); if (s > 0) { siteInfoPage = page; } } } // if found, move it if (siteInfoPage != null) { // move home from it's index to the first position int siteInfoPosition = pageList.indexOf(siteInfoPage); for (int n = siteInfoPosition; n < pageList.size(); n++) { siteInfoPage.moveDown(); } } } // Site Info } // commit commitSite(site); // import importToolIntoSite(chosenList, importTools, site); } // addFeatures // import tool content into site private void importToolIntoSite(List toolIds, Hashtable importTools, Site site) { if (importTools != null) { // import resources first boolean resourcesImported = false; for (int i = 0; i < toolIds.size() && !resourcesImported; i++) { String toolId = (String) toolIds.get(i); if (toolId.equalsIgnoreCase("sakai.resources") && importTools.containsKey(toolId)) { List importSiteIds = (List) importTools.get(toolId); for (int k = 0; k < importSiteIds.size(); k++) { String fromSiteId = (String) importSiteIds.get(k); String toSiteId = site.getId(); String fromSiteCollectionId = ContentHostingService .getSiteCollection(fromSiteId); String toSiteCollectionId = ContentHostingService .getSiteCollection(toSiteId); transferCopyEntities(toolId, fromSiteCollectionId, toSiteCollectionId); resourcesImported = true; } } } // ijmport other tools then for (int i = 0; i < toolIds.size(); i++) { String toolId = (String) toolIds.get(i); if (!toolId.equalsIgnoreCase("sakai.resources") && importTools.containsKey(toolId)) { List importSiteIds = (List) importTools.get(toolId); for (int k = 0; k < importSiteIds.size(); k++) { String fromSiteId = (String) importSiteIds.get(k); String toSiteId = site.getId(); transferCopyEntities(toolId, fromSiteId, toSiteId); } } } } } // importToolIntoSite public void saveSiteStatus(SessionState state, boolean published) { Site site = getStateSite(state); site.setPublished(published); } // saveSiteStatus public void commitSite(Site site, boolean published) { site.setPublished(published); try { SiteService.save(site); } catch (IdUnusedException e) { // TODO: } catch (PermissionException e) { // TODO: } } // commitSite public void commitSite(Site site) { try { SiteService.save(site); } catch (IdUnusedException e) { // TODO: } catch (PermissionException e) { // TODO: } }// commitSite private boolean isValidDomain(String email) { String invalidNonOfficialAccountString = ServerConfigurationService .getString("invalidNonOfficialAccountString", null); if (invalidNonOfficialAccountString != null) { String[] invalidDomains = invalidNonOfficialAccountString.split(","); for (int i = 0; i < invalidDomains.length; i++) { String domain = invalidDomains[i].trim(); if (email.toLowerCase().indexOf(domain.toLowerCase()) != -1) { return false; } } } return true; } private void checkAddParticipant(ParameterParser params, SessionState state) { // get the participants to be added int i; Vector pList = new Vector(); HashSet existingUsers = new HashSet(); Site site = null; String siteId = (String) state.getAttribute(STATE_SITE_INSTANCE_ID); try { site = SiteService.getSite(siteId); } catch (IdUnusedException e) { addAlert(state, rb.getString("java.specif") + " " + siteId); } // accept officialAccounts and/or nonOfficialAccount account names String officialAccounts = ""; String nonOfficialAccounts = ""; // check that there is something with which to work officialAccounts = StringUtil.trimToNull((params .getString("officialAccount"))); nonOfficialAccounts = StringUtil.trimToNull(params .getString("nonOfficialAccount")); state.setAttribute("officialAccountValue", officialAccounts); state.setAttribute("nonOfficialAccountValue", nonOfficialAccounts); // if there is no uniquname or nonOfficialAccount entered if (officialAccounts == null && nonOfficialAccounts == null) { addAlert(state, rb.getString("java.guest")); state.setAttribute(STATE_TEMPLATE_INDEX, "5"); return; } String at = "@"; if (officialAccounts != null) { // adding officialAccounts String[] officialAccountArray = officialAccounts .split("\r\n"); for (i = 0; i < officialAccountArray.length; i++) { String officialAccount = StringUtil .trimToNull(officialAccountArray[i].replaceAll( "[\t\r\n]", "")); // if there is some text, try to use it if (officialAccount != null) { // automaticially add nonOfficialAccount account Participant participant = new Participant(); try { //Changed user lookup to satisfy BSP-1010 (jholtzman) User u = null; // First try looking for the user by their email address Collection usersWithEmail = UserDirectoryService.findUsersByEmail(officialAccount); if(usersWithEmail != null) { if(usersWithEmail.size() == 0) { // If the collection is empty, we didn't find any users with this email address M_log.info("Unable to fund users with email " + officialAccount); } else if (usersWithEmail.size() == 1) { // We found one user with this email address. Use it. u = (User)usersWithEmail.iterator().next(); } else if (usersWithEmail.size() > 1) { // If we have multiple users with this email address, pick one and log this error condition // TODO Should we not pick a user? Throw an exception? M_log.warn("Found multiple user with email " + officialAccount); u = (User)usersWithEmail.iterator().next(); } } // We didn't find anyone via email address, so try getting the user by EID if(u == null) { u = UserDirectoryService.getUserByEid(officialAccount); } if (site != null && site.getUserRole(u.getId()) != null) { // user already exists in the site, cannot be added // again existingUsers.add(officialAccount); } else { participant.name = u.getDisplayName(); participant.uniqname = u.getEid(); pList.add(participant); } } catch (UserNotDefinedException e) { addAlert(state, officialAccount + " " + rb.getString("java.username") + " "); } } } } // officialAccounts if (nonOfficialAccounts != null) { String[] nonOfficialAccountArray = nonOfficialAccounts.split("\r\n"); for (i = 0; i < nonOfficialAccountArray.length; i++) { String nonOfficialAccount = nonOfficialAccountArray[i]; // if there is some text, try to use it nonOfficialAccount.replaceAll("[ \t\r\n]", ""); // remove the trailing dots and empty space while (nonOfficialAccount.endsWith(".") || nonOfficialAccount.endsWith(" ")) { nonOfficialAccount = nonOfficialAccount.substring(0, nonOfficialAccount.length() - 1); } if (nonOfficialAccount != null && nonOfficialAccount.length() > 0) { String[] parts = nonOfficialAccount.split(at); if (nonOfficialAccount.indexOf(at) == -1) { // must be a valid email address addAlert(state, nonOfficialAccount + " " + rb.getString("java.emailaddress")); } else if ((parts.length != 2) || (parts[0].length() == 0)) { // must have both id and address part addAlert(state, nonOfficialAccount + " " + rb.getString("java.notemailid")); } else if (!Validator.checkEmailLocal(parts[0])) { addAlert(state, nonOfficialAccount + " " + rb.getString("java.emailaddress") + rb.getString("java.theemail")); } else if (nonOfficialAccount != null && !isValidDomain(nonOfficialAccount)) { // wrong string inside nonOfficialAccount id addAlert(state, nonOfficialAccount + " " + rb.getString("java.emailaddress") + " "); } else { Participant participant = new Participant(); try { // if the nonOfficialAccount user already exists User u = UserDirectoryService .getUserByEid(nonOfficialAccount); if (site != null && site.getUserRole(u.getId()) != null) { // user already exists in the site, cannot be // added again existingUsers.add(nonOfficialAccount); } else { participant.name = u.getDisplayName(); participant.uniqname = nonOfficialAccount; pList.add(participant); } } catch (UserNotDefinedException e) { // if the nonOfficialAccount user is not in the system // yet participant.name = nonOfficialAccount; participant.uniqname = nonOfficialAccount; // TODO: // what // would // the // UDS // case // this // name // to? // -ggolden pList.add(participant); } } } // if } // } // nonOfficialAccounts boolean same_role = true; if (params.getString("same_role") == null) { addAlert(state, rb.getString("java.roletype") + " "); } else { same_role = params.getString("same_role").equals("true") ? true : false; state.setAttribute("form_same_role", new Boolean(same_role)); } if (state.getAttribute(STATE_MESSAGE) != null) { state.setAttribute(STATE_TEMPLATE_INDEX, "5"); } else { if (same_role) { state.setAttribute(STATE_TEMPLATE_INDEX, "19"); } else { state.setAttribute(STATE_TEMPLATE_INDEX, "20"); } } // remove duplicate or existing user from participant list pList = removeDuplicateParticipants(pList, state); state.setAttribute(STATE_ADD_PARTICIPANTS, pList); // if the add participant list is empty after above removal, stay in the // current page if (pList.size() == 0) { state.setAttribute(STATE_TEMPLATE_INDEX, "5"); } // add alert for attempting to add existing site user(s) if (!existingUsers.isEmpty()) { int count = 0; String accounts = ""; for (Iterator eIterator = existingUsers.iterator(); eIterator .hasNext();) { if (count == 0) { accounts = (String) eIterator.next(); } else { accounts = accounts + ", " + (String) eIterator.next(); } count++; } addAlert(state, rb.getString("add.existingpart.1") + accounts + rb.getString("add.existingpart.2")); } return; } // checkAddParticipant private Vector removeDuplicateParticipants(List pList, SessionState state) { // check the uniqness of list member Set s = new HashSet(); Set uniqnameSet = new HashSet(); Vector rv = new Vector(); for (int i = 0; i < pList.size(); i++) { Participant p = (Participant) pList.get(i); if (!uniqnameSet.contains(p.getUniqname())) { // no entry for the account yet rv.add(p); uniqnameSet.add(p.getUniqname()); } else { // found duplicates s.add(p.getUniqname()); } } if (!s.isEmpty()) { int count = 0; String accounts = ""; for (Iterator i = s.iterator(); i.hasNext();) { if (count == 0) { accounts = (String) i.next(); } else { accounts = accounts + ", " + (String) i.next(); } count++; } if (count == 1) { addAlert(state, rb.getString("add.duplicatedpart.single") + accounts + "."); } else { addAlert(state, rb.getString("add.duplicatedpart") + accounts + "."); } } return rv; } public void doAdd_participant(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); String siteTitle = getStateSite(state).getTitle(); String nonOfficialAccountLabel = ServerConfigurationService.getString( "nonOfficialAccountLabel", ""); Hashtable selectedRoles = (Hashtable) state .getAttribute(STATE_SELECTED_PARTICIPANT_ROLES); boolean notify = false; if (state.getAttribute("form_selectedNotify") != null) { notify = ((Boolean) state.getAttribute("form_selectedNotify")) .booleanValue(); } boolean same_role = ((Boolean) state.getAttribute("form_same_role")) .booleanValue(); Hashtable eIdRoles = new Hashtable(); List addParticipantList = (List) state .getAttribute(STATE_ADD_PARTICIPANTS); for (int i = 0; i < addParticipantList.size(); i++) { Participant p = (Participant) addParticipantList.get(i); String eId = p.getEid(); // role defaults to same role String role = (String) state.getAttribute("form_selectedRole"); if (!same_role) { // if all added participants have different role role = (String) selectedRoles.get(eId); } boolean officialAccount = eId.indexOf(EMAIL_CHAR) == -1; if (officialAccount) { // if this is a officialAccount // update the hashtable eIdRoles.put(eId, role); } else { // if this is an nonOfficialAccount try { UserDirectoryService.getUserByEid(eId); } catch (UserNotDefinedException e) { // if there is no such user yet, add the user try { UserEdit uEdit = UserDirectoryService .addUser(null, eId); // set email address uEdit.setEmail(eId); // set the guest user type uEdit.setType("guest"); // set password to a positive random number Random generator = new Random(System .currentTimeMillis()); Integer num = new Integer(generator .nextInt(Integer.MAX_VALUE)); if (num.intValue() < 0) num = new Integer(num.intValue() * -1); String pw = num.toString(); uEdit.setPassword(pw); // and save UserDirectoryService.commitEdit(uEdit); boolean notifyNewUserEmail = (ServerConfigurationService .getString("notifyNewUserEmail", Boolean.TRUE .toString())) .equalsIgnoreCase(Boolean.TRUE.toString()); if (notifyNewUserEmail) { notifyNewUserEmail(uEdit.getEid(), uEdit.getEmail(), pw, siteTitle); } } catch (UserIdInvalidException ee) { addAlert(state, nonOfficialAccountLabel + " id " + eId + " " + rb.getString("java.isinval")); M_log.warn(this + " UserDirectoryService addUser exception " + e.getMessage()); } catch (UserAlreadyDefinedException ee) { addAlert(state, "The " + nonOfficialAccountLabel + " " + eId + " " + rb.getString("java.beenused")); M_log.warn(this + " UserDirectoryService addUser exception " + e.getMessage()); } catch (UserPermissionException ee) { addAlert(state, rb.getString("java.haveadd") + " " + eId); M_log.warn(this + " UserDirectoryService addUser exception " + e.getMessage()); } } if (state.getAttribute(STATE_MESSAGE) == null) { eIdRoles.put(eId, role); } } } // batch add and updates the successful added list List addedParticipantEIds = addUsersRealm(state, eIdRoles, notify, false); // update the not added user list String notAddedOfficialAccounts = null; String notAddedNonOfficialAccounts = null; for (Iterator iEIds = eIdRoles.keySet().iterator(); iEIds.hasNext();) { String iEId = (String) iEIds.next(); if (!addedParticipantEIds.contains(iEId)) { if (iEId.indexOf(EMAIL_CHAR) == -1) { // no email in eid notAddedOfficialAccounts = notAddedOfficialAccounts .concat(iEId + "\n"); } else { // email in eid notAddedNonOfficialAccounts = notAddedNonOfficialAccounts .concat(iEId + "\n"); } } } if (addedParticipantEIds.size() != 0 && (notAddedOfficialAccounts != null || notAddedNonOfficialAccounts != null)) { // at lease one officialAccount account or an nonOfficialAccount // account added, and there are also failures addAlert(state, rb.getString("java.allusers")); } if (notAddedOfficialAccounts == null && notAddedNonOfficialAccounts == null) { // all account has been added successfully removeAddParticipantContext(state); } else { state.setAttribute("officialAccountValue", notAddedOfficialAccounts); state.setAttribute("nonOfficialAccountValue", notAddedNonOfficialAccounts); } if (state.getAttribute(STATE_MESSAGE) != null) { state.setAttribute(STATE_TEMPLATE_INDEX, "22"); } else { state.setAttribute(STATE_TEMPLATE_INDEX, "12"); } return; } // doAdd_participant /** * remove related state variable for adding participants * * @param state * SessionState object */ private void removeAddParticipantContext(SessionState state) { // remove related state variables state.removeAttribute("form_selectedRole"); state.removeAttribute("officialAccountValue"); state.removeAttribute("nonOfficialAccountValue"); state.removeAttribute("form_same_role"); state.removeAttribute("form_selectedNotify"); state.removeAttribute(STATE_ADD_PARTICIPANTS); state.removeAttribute(STATE_SELECTED_USER_LIST); state.removeAttribute(STATE_SELECTED_PARTICIPANT_ROLES); } // removeAddParticipantContext /** * Send an email to newly added user informing password * * @param newnonOfficialAccount * @param emailId * @param userName * @param siteTitle */ private void notifyNewUserEmail(String userName, String newUserEmail, String newUserPassword, String siteTitle) { String from = getSetupRequestEmailAddress(); String productionSiteName = ServerConfigurationService.getString( "ui.service", ""); String productionSiteUrl = ServerConfigurationService.getPortalUrl(); String to = newUserEmail; String headerTo = newUserEmail; String replyTo = newUserEmail; String message_subject = productionSiteName + " " + rb.getString("java.newusernoti"); String content = ""; if (from != null && newUserEmail != null) { StringBuilder buf = new StringBuilder(); buf.setLength(0); // email body buf.append(userName + ":\n\n"); buf.append(rb.getString("java.addedto") + " " + productionSiteName + " (" + productionSiteUrl + ") "); buf.append(rb.getString("java.simpleby") + " "); buf.append(UserDirectoryService.getCurrentUser().getDisplayName() + ". \n\n"); buf.append(rb.getString("java.passwordis1") + "\n" + newUserPassword + "\n\n"); buf.append(rb.getString("java.passwordis2") + "\n\n"); content = buf.toString(); EmailService.send(from, to, message_subject, content, headerTo, replyTo, null); } } // notifyNewUserEmail private String getSetupRequestEmailAddress() { String from = ServerConfigurationService.getString("setup.request", null); if (from == null) { M_log.warn(this + " - no 'setup.request' in configuration"); from = "postmaster@".concat(ServerConfigurationService .getServerName()); } return from; } /** * send email notification to added participant */ private void notifyAddedParticipant(boolean newNonOfficialAccount, String emailId, String userName, String siteTitle) { String from = getSetupRequestEmailAddress(); if (from != null) { String productionSiteName = ServerConfigurationService.getString( "ui.service", ""); String productionSiteUrl = ServerConfigurationService .getPortalUrl(); String nonOfficialAccountUrl = ServerConfigurationService.getString( "nonOfficialAccount.url", null); String to = emailId; String headerTo = emailId; String replyTo = emailId; String message_subject = productionSiteName + " " + rb.getString("java.sitenoti"); String content = ""; StringBuilder buf = new StringBuilder(); buf.setLength(0); // email bnonOfficialAccounteen newly added nonOfficialAccount account // and other users buf.append(userName + ":\n\n"); buf.append(rb.getString("java.following") + " " + productionSiteName + " " + rb.getString("java.simplesite") + "\n"); buf.append(siteTitle + "\n"); buf.append(rb.getString("java.simpleby") + " "); buf.append(UserDirectoryService.getCurrentUser().getDisplayName() + ". \n\n"); if (newNonOfficialAccount) { buf.append(ServerConfigurationService.getString( "nonOfficialAccountInstru", "") + "\n"); if (nonOfficialAccountUrl != null) { buf.append(rb.getString("java.togeta1") + "\n" + nonOfficialAccountUrl + "\n"); buf.append(rb.getString("java.togeta2") + "\n\n"); } buf.append(rb.getString("java.once") + " " + productionSiteName + ": \n"); buf.append(rb.getString("java.loginhow1") + " " + productionSiteName + ": " + productionSiteUrl + "\n"); buf.append(rb.getString("java.loginhow2") + "\n"); buf.append(rb.getString("java.loginhow3") + "\n"); } else { buf.append(rb.getString("java.tolog") + "\n"); buf.append(rb.getString("java.loginhow1") + " " + productionSiteName + ": " + productionSiteUrl + "\n"); buf.append(rb.getString("java.loginhow2") + "\n"); buf.append(rb.getString("java.loginhow3u") + "\n"); } buf.append(rb.getString("java.tabscreen")); content = buf.toString(); EmailService.send(from, to, message_subject, content, headerTo, replyTo, null); } // if } // notifyAddedParticipant /* * Given a list of user eids, add users to realm If the user account does * not exist yet inside the user directory, assign role to it @return A list * of eids for successfully added users */ private List addUsersRealm(SessionState state, Hashtable eIdRoles, boolean notify, boolean nonOfficialAccount) { // return the list of user eids for successfully added user List addedUserEIds = new Vector(); StringBuilder message = new StringBuilder(); if (eIdRoles != null && !eIdRoles.isEmpty()) { // get the current site Site sEdit = getStateSite(state); if (sEdit != null) { // get realm object String realmId = sEdit.getReference(); try { AuthzGroup realmEdit = AuthzGroupService .getAuthzGroup(realmId); for (Iterator eIds = eIdRoles.keySet().iterator(); eIds .hasNext();) { String eId = (String) eIds.next(); String role = (String) eIdRoles.get(eId); try { User user = UserDirectoryService.getUserByEid(eId); if (AuthzGroupService.allowUpdate(realmId) || SiteService .allowUpdateSiteMembership(sEdit .getId())) { realmEdit.addMember(user.getId(), role, true, false); addedUserEIds.add(eId); // send notification if (notify) { String emailId = user.getEmail(); String userName = user.getDisplayName(); // send notification email notifyAddedParticipant(nonOfficialAccount, emailId, userName, sEdit.getTitle()); } } } catch (UserNotDefinedException e) { message.append(eId + " " + rb.getString("java.account") + " \n"); } // try } // for try { AuthzGroupService.save(realmEdit); } catch (GroupNotDefinedException ee) { message.append(rb.getString("java.realm") + realmId); } catch (AuthzPermissionException ee) { message.append(rb.getString("java.permeditsite") + realmId); } } catch (GroupNotDefinedException eee) { message.append(rb.getString("java.realm") + realmId); } catch (Exception eee) { M_log.warn("SiteActionaddUsersRealm " + eee.getMessage() + " realmId=" + realmId); } } } if (message.length() != 0) { addAlert(state, message.toString()); } // if return addedUserEIds; } // addUsersRealm /** * addNewSite is called when the site has enough information to create a new * site * */ private void addNewSite(ParameterParser params, SessionState state) { if (getStateSite(state) != null) { // There is a Site in state already, so use it rather than creating // a new Site return; } // If cleanState() has removed SiteInfo, get a new instance into state SiteInfo siteInfo = new SiteInfo(); if (state.getAttribute(STATE_SITE_INFO) != null) { siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); } String id = StringUtil.trimToNull(siteInfo.getSiteId()); if (id == null) { // get id id = IdManager.createUuid(); siteInfo.site_id = id; } state.setAttribute(STATE_SITE_INFO, siteInfo); if (state.getAttribute(STATE_MESSAGE) == null) { try { Site site = SiteService.addSite(id, siteInfo.site_type); String title = StringUtil.trimToNull(siteInfo.title); String description = siteInfo.description; setAppearance(state, site, siteInfo.iconUrl); site.setDescription(description); if (title != null) { site.setTitle(title); } site.setType(siteInfo.site_type); ResourcePropertiesEdit rp = site.getPropertiesEdit(); site.setShortDescription(siteInfo.short_description); site.setPubView(siteInfo.include); site.setJoinable(siteInfo.joinable); site.setJoinerRole(siteInfo.joinerRole); site.setPublished(siteInfo.published); // site contact information rp.addProperty(PROP_SITE_CONTACT_NAME, siteInfo.site_contact_name); rp.addProperty(PROP_SITE_CONTACT_EMAIL, siteInfo.site_contact_email); state.setAttribute(STATE_SITE_INSTANCE_ID, site.getId()); // commit newly added site in order to enable related realm commitSite(site); } catch (IdUsedException e) { addAlert(state, rb.getString("java.sitewithid") + " " + id + " " + rb.getString("java.exists")); state.setAttribute(STATE_TEMPLATE_INDEX, params .getString("template-index")); return; } catch (IdInvalidException e) { addAlert(state, rb.getString("java.thesiteid") + " " + id + " " + rb.getString("java.notvalid")); state.setAttribute(STATE_TEMPLATE_INDEX, params .getString("template-index")); return; } catch (PermissionException e) { addAlert(state, rb.getString("java.permission") + " " + id + "."); state.setAttribute(STATE_TEMPLATE_INDEX, params .getString("template-index")); return; } } } // addNewSite /** * %%% legacy properties, to be cleaned up * */ private void sitePropertiesIntoState(SessionState state) { try { Site site = getStateSite(state); SiteInfo siteInfo = new SiteInfo(); // set from site attributes siteInfo.title = site.getTitle(); siteInfo.description = site.getDescription(); siteInfo.iconUrl = site.getIconUrl(); siteInfo.infoUrl = site.getInfoUrl(); siteInfo.joinable = site.isJoinable(); siteInfo.joinerRole = site.getJoinerRole(); siteInfo.published = site.isPublished(); siteInfo.include = site.isPubView(); siteInfo.additional = ""; siteInfo.short_description = site.getShortDescription(); state.setAttribute(STATE_SITE_TYPE, siteInfo.site_type); state.setAttribute(STATE_SITE_INFO, siteInfo); } catch (Exception e) { M_log.warn("SiteAction.sitePropertiesIntoState " + e.getMessage()); } } // sitePropertiesIntoState /** * pageMatchesPattern returns true if a SitePage matches a WorkSite Setup * pattern * */ private boolean pageMatchesPattern(SessionState state, SitePage page) { List pageToolList = page.getTools(); // if no tools on the page, return false if (pageToolList == null || pageToolList.size() == 0) { return false; } // for the case where the page has one tool ToolConfiguration toolConfiguration = (ToolConfiguration) pageToolList .get(0); // don't compare tool properties, which may be changed using Options List toolList = new Vector(); int count = pageToolList.size(); boolean match = false; // check Worksite Setup Home pattern if (page.getTitle() != null && page.getTitle().equals(rb.getString("java.home"))) { return true; } // Home else if (page.getTitle() != null && page.getTitle().equals(rb.getString("java.help"))) { // if the count of tools on the page doesn't match, return false if (count != 1) { return false; } // if the page layout doesn't match, return false if (page.getLayout() != SitePage.LAYOUT_SINGLE_COL) { return false; } // if tooId isn't sakai.contactSupport, return false if (!(toolConfiguration.getTool().getId()) .equals("sakai.contactSupport")) { return false; } return true; } // Help else if (page.getTitle() != null && page.getTitle().equals("Chat")) { // if the count of tools on the page doesn't match, return false if (count != 1) { return false; } // if the page layout doesn't match, return false if (page.getLayout() != SitePage.LAYOUT_SINGLE_COL) { return false; } // if the tool doesn't match, return false if (!(toolConfiguration.getTool().getId()).equals("sakai.chat")) { return false; } // if the channel doesn't match value for main channel, return false String channel = toolConfiguration.getPlacementConfig() .getProperty("channel"); if (channel == null) { return false; } if (!(channel.equals(NULL_STRING))) { return false; } return true; } // Chat else { // if the count of tools on the page doesn't match, return false if (count != 1) { return false; } // if the page layout doesn't match, return false if (page.getLayout() != SitePage.LAYOUT_SINGLE_COL) { return false; } toolList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_LIST); if (pageToolList != null || pageToolList.size() != 0) { // if tool attributes don't match, return false match = false; for (ListIterator i = toolList.listIterator(); i.hasNext();) { MyTool tool = (MyTool) i.next(); if (toolConfiguration.getTitle() != null) { if (toolConfiguration.getTool() != null && toolConfiguration.getTool().getId().indexOf( tool.getId()) != -1) { match = true; } } } if (!match) { return false; } } } // Others return true; } // pageMatchesPattern /** * siteToolsIntoState is the replacement for siteToolsIntoState_ Make a list * of pages and tools that match WorkSite Setup configurations into state */ private void siteToolsIntoState(SessionState state) { String wSetupTool = NULL_STRING; List wSetupPageList = new Vector(); Site site = getStateSite(state); List pageList = site.getPages(); // Put up tool lists filtered by category String type = site.getType(); if (type == null) { if (SiteService.isUserSite(site.getId())) { type = "myworkspace"; } else if (state.getAttribute(STATE_DEFAULT_SITE_TYPE) != null) { // for those sites without type, use the tool set for default // site type type = (String) state.getAttribute(STATE_DEFAULT_SITE_TYPE); } } List toolRegList = new Vector(); if (type != null) { Set categories = new HashSet(); categories.add(type); Set toolRegistrations = ToolManager.findTools(categories, null); SortedIterator i = new SortedIterator(toolRegistrations.iterator(), new ToolComparator()); for (; i.hasNext();) { // form a new Tool Tool tr = (Tool) i.next(); MyTool newTool = new MyTool(); newTool.title = tr.getTitle(); newTool.id = tr.getId(); newTool.description = tr.getDescription(); toolRegList.add(newTool); } } if (toolRegList.size() == 0 && state.getAttribute(STATE_DEFAULT_SITE_TYPE) != null) { // use default site type and try getting tools again type = (String) state.getAttribute(STATE_DEFAULT_SITE_TYPE); Set nCategories = new HashSet(); nCategories.add(type); Set toolRegistrations = ToolManager.findTools(nCategories, null); SortedIterator i = new SortedIterator(toolRegistrations.iterator(), new ToolComparator()); for (; i.hasNext();) { // form a new Tool Tool tr = (Tool) i.next(); MyTool newTool = new MyTool(); newTool.title = tr.getTitle(); newTool.id = tr.getId(); newTool.description = tr.getDescription(); toolRegList.add(newTool); } } state.setAttribute(STATE_TOOL_REGISTRATION_LIST, toolRegList); state.setAttribute(STATE_SITE_TYPE, type); if (type == null) { M_log.warn(this + ": - unknown STATE_SITE_TYPE"); } else { state.setAttribute(STATE_SITE_TYPE, type); } boolean check_home = false; boolean hasNews = false; boolean hasWebContent = false; int newsToolNum = 0; int wcToolNum = 0; Hashtable newsTitles = new Hashtable(); Hashtable wcTitles = new Hashtable(); Hashtable newsUrls = new Hashtable(); Hashtable wcUrls = new Hashtable(); Vector idSelected = new Vector(); if (!((pageList == null) || (pageList.size() == 0))) { for (ListIterator i = pageList.listIterator(); i.hasNext();) { SitePage page = (SitePage) i.next(); // collect the pages consistent with Worksite Setup patterns if (pageMatchesPattern(state, page)) { if (page.getTitle().equals(rb.getString("java.home"))) { wSetupTool = HOME_TOOL_ID; check_home = true; } else { List pageToolList = page.getTools(); wSetupTool = ((ToolConfiguration) pageToolList.get(0)) .getTool().getId(); if (wSetupTool.indexOf("sakai.news") != -1) { String newsToolId = page.getId() + wSetupTool; idSelected.add(newsToolId); newsTitles.put(newsToolId, page.getTitle()); String channelUrl = ((ToolConfiguration) pageToolList .get(0)).getPlacementConfig().getProperty( "channel-url"); newsUrls.put(newsToolId, channelUrl != null ? channelUrl : ""); newsToolNum++; // insert the News tool into the list hasNews = false; int j = 0; MyTool newTool = new MyTool(); newTool.title = NEWS_DEFAULT_TITLE; newTool.id = newsToolId; newTool.selected = false; for (; j < toolRegList.size() && !hasNews; j++) { MyTool t = (MyTool) toolRegList.get(j); if (t.getId().equals("sakai.news")) { hasNews = true; newTool.description = t.getDescription(); } } if (hasNews) { toolRegList.add(j - 1, newTool); } else { toolRegList.add(newTool); } } else if ((wSetupTool).indexOf("sakai.iframe") != -1) { String wcToolId = page.getId() + wSetupTool; idSelected.add(wcToolId); wcTitles.put(wcToolId, page.getTitle()); String wcUrl = StringUtil .trimToNull(((ToolConfiguration) pageToolList .get(0)).getPlacementConfig() .getProperty("source")); if (wcUrl == null) { // if there is no source URL, seed it with the // Web Content default URL wcUrl = WEB_CONTENT_DEFAULT_URL; } wcUrls.put(wcToolId, wcUrl); wcToolNum++; MyTool newTool = new MyTool(); newTool.title = WEB_CONTENT_DEFAULT_TITLE; newTool.id = wcToolId; newTool.selected = false; hasWebContent = false; int j = 0; for (; j < toolRegList.size() && !hasWebContent; j++) { MyTool t = (MyTool) toolRegList.get(j); if (t.getId().equals("sakai.iframe")) { hasWebContent = true; newTool.description = t.getDescription(); } } if (hasWebContent) { toolRegList.add(j - 1, newTool); } else { toolRegList.add(newTool); } } /* * else if(wSetupTool.indexOf("sakai.syllabus") != -1) { * //add only one instance of tool per site if * (!(idSelected.contains(wSetupTool))) { * idSelected.add(wSetupTool); } } */ else { idSelected.add(wSetupTool); } } WorksiteSetupPage wSetupPage = new WorksiteSetupPage(); wSetupPage.pageId = page.getId(); wSetupPage.pageTitle = page.getTitle(); wSetupPage.toolId = wSetupTool; wSetupPageList.add(wSetupPage); } } } newsTitles.put("sakai.news", NEWS_DEFAULT_TITLE); newsUrls.put("sakai.news", NEWS_DEFAULT_URL); wcTitles.put("sakai.iframe", WEB_CONTENT_DEFAULT_TITLE); wcUrls.put("sakai.iframe", WEB_CONTENT_DEFAULT_URL); state.setAttribute(STATE_TOOL_REGISTRATION_LIST, toolRegList); state.setAttribute(STATE_TOOL_HOME_SELECTED, new Boolean(check_home)); state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, idSelected); // List // of // ToolRegistration // toolId's state.setAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST, idSelected); // List of ToolRegistration toolId's state.setAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME, Boolean .valueOf(check_home)); state.setAttribute(STATE_NEWS_TITLES, newsTitles); state.setAttribute(STATE_WEB_CONTENT_TITLES, wcTitles); state.setAttribute(STATE_NEWS_URLS, newsUrls); state.setAttribute(STATE_WEB_CONTENT_URLS, wcUrls); state.setAttribute(STATE_WORKSITE_SETUP_PAGE_LIST, wSetupPageList); } // siteToolsIntoState /** * reset the state variables used in edit tools mode * * @state The SessionState object */ private void removeEditToolState(SessionState state) { state.removeAttribute(STATE_TOOL_HOME_SELECTED); state.removeAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); // List // of // ToolRegistration // toolId's state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST); // List // of // ToolRegistration // toolId's state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME); state.removeAttribute(STATE_NEWS_TITLES); state.removeAttribute(STATE_NEWS_URLS); state.removeAttribute(STATE_WEB_CONTENT_TITLES); state.removeAttribute(STATE_WEB_CONTENT_URLS); state.removeAttribute(STATE_WORKSITE_SETUP_PAGE_LIST); } private List orderToolIds(SessionState state, String type, List toolIdList) { List rv = new Vector(); if (state.getAttribute(STATE_TOOL_HOME_SELECTED) != null && ((Boolean) state.getAttribute(STATE_TOOL_HOME_SELECTED)) .booleanValue()) { rv.add(HOME_TOOL_ID); } // look for null site type if (type != null && toolIdList != null) { Set categories = new HashSet(); categories.add(type); Set tools = ToolManager.findTools(categories, null); SortedIterator i = new SortedIterator(tools.iterator(), new ToolComparator()); for (; i.hasNext();) { String tool_id = ((Tool) i.next()).getId(); for (ListIterator j = toolIdList.listIterator(); j.hasNext();) { String toolId = (String) j.next(); if (toolId.indexOf("assignment") != -1 && toolId.equals(tool_id) || toolId.indexOf("assignment") == -1 && toolId.indexOf(tool_id) != -1) { rv.add(toolId); } } } } return rv; } // orderToolIds private void setupFormNamesAndConstants(SessionState state) { TimeBreakdown timeBreakdown = (TimeService.newTime()).breakdownLocal(); String mycopyright = COPYRIGHT_SYMBOL + " " + timeBreakdown.getYear() + ", " + UserDirectoryService.getCurrentUser().getDisplayName() + ". All Rights Reserved. "; state.setAttribute(STATE_MY_COPYRIGHT, mycopyright); state.setAttribute(STATE_SITE_INSTANCE_ID, null); state.setAttribute(STATE_INITIALIZED, Boolean.TRUE.toString()); SiteInfo siteInfo = new SiteInfo(); Participant participant = new Participant(); participant.name = NULL_STRING; participant.uniqname = NULL_STRING; state.setAttribute(STATE_SITE_INFO, siteInfo); state.setAttribute("form_participantToAdd", participant); state.setAttribute(FORM_ADDITIONAL, NULL_STRING); // legacy state.setAttribute(FORM_HONORIFIC, "0"); state.setAttribute(FORM_REUSE, "0"); state.setAttribute(FORM_RELATED_CLASS, "0"); state.setAttribute(FORM_RELATED_PROJECT, "0"); state.setAttribute(FORM_INSTITUTION, "0"); // sundry form variables state.setAttribute(FORM_PHONE, ""); state.setAttribute(FORM_EMAIL, ""); state.setAttribute(FORM_SUBJECT, ""); state.setAttribute(FORM_DESCRIPTION, ""); state.setAttribute(FORM_TITLE, ""); state.setAttribute(FORM_NAME, ""); state.setAttribute(FORM_SHORT_DESCRIPTION, ""); } // setupFormNamesAndConstants /** * setupSkins * */ private void setupIcons(SessionState state) { List icons = new Vector(); String[] iconNames = null; String[] iconUrls = null; String[] iconSkins = null; // get icon information if (ServerConfigurationService.getStrings("iconNames") != null) { iconNames = ServerConfigurationService.getStrings("iconNames"); } if (ServerConfigurationService.getStrings("iconUrls") != null) { iconUrls = ServerConfigurationService.getStrings("iconUrls"); } if (ServerConfigurationService.getStrings("iconSkins") != null) { iconSkins = ServerConfigurationService.getStrings("iconSkins"); } if ((iconNames != null) && (iconUrls != null) && (iconSkins != null) && (iconNames.length == iconUrls.length) && (iconNames.length == iconSkins.length)) { for (int i = 0; i < iconNames.length; i++) { MyIcon s = new MyIcon(StringUtil.trimToNull((String) iconNames[i]), StringUtil.trimToNull((String) iconUrls[i]), StringUtil .trimToNull((String) iconSkins[i])); icons.add(s); } } state.setAttribute(STATE_ICONS, icons); } private void setAppearance(SessionState state, Site edit, String iconUrl) { // set the icon edit.setIconUrl(iconUrl); if (iconUrl == null) { // this is the default case - no icon, no (default) skin edit.setSkin(null); return; } // if this icon is in the config appearance list, find a skin to set List icons = (List) state.getAttribute(STATE_ICONS); for (Iterator i = icons.iterator(); i.hasNext();) { Object icon = (Object) i.next(); if (icon instanceof MyIcon && !StringUtil.different(((MyIcon) icon).getUrl(), iconUrl)) { edit.setSkin(((MyIcon) icon).getSkin()); return; } } } /** * A dispatch funtion when selecting course features */ public void doAdd_features(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String option = params.getString("option"); if (option.equalsIgnoreCase("addNews")) { updateSelectedToolList(state, params, false); insertTool(state, "sakai.news", STATE_NEWS_TITLES, NEWS_DEFAULT_TITLE, STATE_NEWS_URLS, NEWS_DEFAULT_URL, Integer.parseInt(params.getString("newsNum"))); state.setAttribute(STATE_TEMPLATE_INDEX, "26"); } else if (option.equalsIgnoreCase("addWC")) { updateSelectedToolList(state, params, false); insertTool(state, "sakai.iframe", STATE_WEB_CONTENT_TITLES, WEB_CONTENT_DEFAULT_TITLE, STATE_WEB_CONTENT_URLS, WEB_CONTENT_DEFAULT_URL, Integer.parseInt(params .getString("wcNum"))); state.setAttribute(STATE_TEMPLATE_INDEX, "26"); } else if (option.equalsIgnoreCase("import")) { // import or not updateSelectedToolList(state, params, false); String importSites = params.getString("import"); if (importSites != null && importSites.equalsIgnoreCase(Boolean.TRUE.toString())) { state.setAttribute(STATE_IMPORT, Boolean.TRUE); if (importSites.equalsIgnoreCase(Boolean.TRUE.toString())) { state.removeAttribute(STATE_IMPORT); state.removeAttribute(STATE_IMPORT_SITES); state.removeAttribute(STATE_IMPORT_SITE_TOOL); } } else { state.removeAttribute(STATE_IMPORT); } } else if (option.equalsIgnoreCase("continue")) { // continue doContinue(data); } else if (option.equalsIgnoreCase("back")) { // back doBack(data); } else if (option.equalsIgnoreCase("cancel")) { // cancel doCancel_create(data); } } // doAdd_features /** * update the selected tool list * * @param params * The ParameterParser object * @param verifyData * Need to verify input data or not */ private void updateSelectedToolList(SessionState state, ParameterParser params, boolean verifyData) { List selectedTools = new ArrayList(Arrays.asList(params .getStrings("selectedTools"))); Hashtable titles = (Hashtable) state.getAttribute(STATE_NEWS_TITLES); Hashtable urls = (Hashtable) state.getAttribute(STATE_NEWS_URLS); Hashtable wcTitles = (Hashtable) state .getAttribute(STATE_WEB_CONTENT_TITLES); Hashtable wcUrls = (Hashtable) state .getAttribute(STATE_WEB_CONTENT_URLS); boolean has_home = false; String emailId = null; for (int i = 0; i < selectedTools.size(); i++) { String id = (String) selectedTools.get(i); if (id.indexOf("sakai.news") != -1) { String title = StringUtil.trimToNull(params .getString("titlefor" + id)); if (title == null) { // if there is no input, make the title for news tool // default to NEWS_DEFAULT_TITLE title = NEWS_DEFAULT_TITLE; } titles.put(id, title); String url = StringUtil.trimToNull(params.getString("urlfor" + id)); if (url == null) { // if there is no input, make the title for news tool // default to NEWS_DEFAULT_URL url = NEWS_DEFAULT_URL; } urls.put(id, url); try { new URL(url); } catch (MalformedURLException e) { addAlert(state, rb.getString("java.invurl") + " " + url + ". "); } } else if (id.indexOf("sakai.iframe") != -1) { String wcTitle = StringUtil.trimToNull(params .getString("titlefor" + id)); if (wcTitle == null) { // if there is no input, make the title for Web Content tool // default to WEB_CONTENT_DEFAULT_TITLE wcTitle = WEB_CONTENT_DEFAULT_TITLE; } wcTitles.put(id, wcTitle); String wcUrl = StringUtil.trimToNull(params.getString("urlfor" + id)); if (wcUrl == null) { // if there is no input, make the title for Web Content tool // default to WEB_CONTENT_DEFAULT_URL wcUrl = WEB_CONTENT_DEFAULT_URL; } else { if ((wcUrl.length() > 0) && (!wcUrl.startsWith("/")) && (wcUrl.indexOf("://") == -1)) { wcUrl = "http://" + wcUrl; } } wcUrls.put(id, wcUrl); } else if (id.equalsIgnoreCase(HOME_TOOL_ID)) { has_home = true; } else if (id.equalsIgnoreCase("sakai.mailbox")) { // if Email archive tool is selected, check the email alias emailId = StringUtil.trimToNull(params.getString("emailId")); if (verifyData) { if (emailId == null) { addAlert(state, rb.getString("java.emailarchive") + " "); } else { if (!Validator.checkEmailLocal(emailId)) { addAlert(state, rb.getString("java.theemail")); } else { // check to see whether the alias has been used by // other sites try { String target = AliasService.getTarget(emailId); if (target != null) { if (state .getAttribute(STATE_SITE_INSTANCE_ID) != null) { String siteId = (String) state .getAttribute(STATE_SITE_INSTANCE_ID); String channelReference = mailArchiveChannelReference(siteId); if (!target.equals(channelReference)) { // the email alias is not used by // current site addAlert(state, rb.getString("java.emailinuse") + " "); } } else { addAlert(state, rb.getString("java.emailinuse") + " "); } } } catch (IdUnusedException ee) { } } } } } } state.setAttribute(STATE_TOOL_HOME_SELECTED, new Boolean(has_home)); state.setAttribute(STATE_TOOL_EMAIL_ADDRESS, emailId); state.setAttribute(STATE_NEWS_TITLES, titles); state.setAttribute(STATE_NEWS_URLS, urls); state.setAttribute(STATE_WEB_CONTENT_TITLES, wcTitles); state.setAttribute(STATE_WEB_CONTENT_URLS, wcUrls); } // updateSelectedToolList /** * find the tool in the tool list and insert another tool instance to the * list * * @param state * SessionState object * @param toolId * The id for the inserted tool * @param stateTitlesVariable * The titles * @param defaultTitle * The default title for the inserted tool * @param stateUrlsVariable * The urls * @param defaultUrl * The default url for the inserted tool * @param insertTimes * How many tools need to be inserted */ private void insertTool(SessionState state, String toolId, String stateTitlesVariable, String defaultTitle, String stateUrlsVariable, String defaultUrl, int insertTimes) { // the list of available tools List toolList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_LIST); int toolListedTimes = 0; int index = 0; int insertIndex = 0; while (index < toolList.size()) { MyTool tListed = (MyTool) toolList.get(index); if (tListed.getId().indexOf(toolId) != -1) { toolListedTimes++; } if (toolListedTimes > 0 && insertIndex == 0) { // update the insert index insertIndex = index; } index++; } List toolSelected = (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); // the titles Hashtable titles = (Hashtable) state.getAttribute(stateTitlesVariable); if (titles == null) { titles = new Hashtable(); } // the urls Hashtable urls = (Hashtable) state.getAttribute(stateUrlsVariable); if (urls == null) { urls = new Hashtable(); } // insert multiple tools for (int i = 0; i < insertTimes; i++) { toolListedTimes = toolListedTimes + i; toolSelected.add(toolId + toolListedTimes); // We need to insert a specific tool entry only if all the specific // tool entries have been selected MyTool newTool = new MyTool(); newTool.title = defaultTitle; newTool.id = toolId + toolListedTimes; toolList.add(insertIndex, newTool); titles.put(newTool.id, defaultTitle); urls.put(newTool.id, defaultUrl); } state.setAttribute(STATE_TOOL_REGISTRATION_LIST, toolList); state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolSelected); state.setAttribute(stateTitlesVariable, titles); state.setAttribute(stateUrlsVariable, urls); } // insertTool /** * * set selected participant role Hashtable */ private void setSelectedParticipantRoles(SessionState state) { List selectedUserIds = (List) state .getAttribute(STATE_SELECTED_USER_LIST); List participantList = collectionToList((Collection) state.getAttribute(STATE_PARTICIPANT_LIST)); List selectedParticipantList = new Vector(); Hashtable selectedParticipantRoles = new Hashtable(); if (!selectedUserIds.isEmpty() && participantList != null) { for (int i = 0; i < participantList.size(); i++) { String id = ""; Object o = (Object) participantList.get(i); if (o.getClass().equals(Participant.class)) { // get participant roles id = ((Participant) o).getUniqname(); selectedParticipantRoles.put(id, ((Participant) o) .getRole()); } else if (o.getClass().equals(Student.class)) { // get participant from roster role id = ((Student) o).getUniqname(); selectedParticipantRoles.put(id, ((Student) o).getRole()); } if (selectedUserIds.contains(id)) { selectedParticipantList.add(participantList.get(i)); } } } state.setAttribute(STATE_SELECTED_PARTICIPANT_ROLES, selectedParticipantRoles); state .setAttribute(STATE_SELECTED_PARTICIPANTS, selectedParticipantList); } // setSelectedParticipantRol3es /** * the SiteComparator class */ private class SiteComparator implements Comparator { Collator collator = Collator.getInstance(); /** * the criteria */ String m_criterion = null; String m_asc = null; /** * constructor * * @param criteria * The sort criteria string * @param asc * The sort order string. TRUE_STRING if ascending; "false" * otherwise. */ public SiteComparator(String criterion, String asc) { m_criterion = criterion; m_asc = asc; } // constructor /** * implementing the Comparator compare function * * @param o1 * The first object * @param o2 * The second object * @return The compare result. 1 is o1 < o2; -1 otherwise */ public int compare(Object o1, Object o2) { int result = -1; if (m_criterion == null) m_criterion = SORTED_BY_TITLE; /** *********** for sorting site list ****************** */ if (m_criterion.equals(SORTED_BY_TITLE)) { // sorted by the worksite title String s1 = ((Site) o1).getTitle(); String s2 = ((Site) o2).getTitle(); result = compareString(s1, s2); } else if (m_criterion.equals(SORTED_BY_DESCRIPTION)) { // sorted by the site short description String s1 = ((Site) o1).getShortDescription(); String s2 = ((Site) o2).getShortDescription(); result = compareString(s1, s2); } else if (m_criterion.equals(SORTED_BY_TYPE)) { // sorted by the site type String s1 = ((Site) o1).getType(); String s2 = ((Site) o2).getType(); result = compareString(s1, s2); } else if (m_criterion.equals(SortType.CREATED_BY_ASC.toString())) { // sorted by the site creator String s1 = ((Site) o1).getProperties().getProperty( "CHEF:creator"); String s2 = ((Site) o2).getProperties().getProperty( "CHEF:creator"); result = compareString(s1, s2); } else if (m_criterion.equals(SORTED_BY_STATUS)) { // sort by the status, published or unpublished int i1 = ((Site) o1).isPublished() ? 1 : 0; int i2 = ((Site) o2).isPublished() ? 1 : 0; if (i1 > i2) { result = 1; } else { result = -1; } } else if (m_criterion.equals(SORTED_BY_JOINABLE)) { // sort by whether the site is joinable or not boolean b1 = ((Site) o1).isJoinable(); boolean b2 = ((Site) o2).isJoinable(); if (b1 == b2) { result = 0; } else if (b1 == true) { result = 1; } else { result = -1; } } else if (m_criterion.equals(SORTED_BY_PARTICIPANT_NAME)) { // sort by whether the site is joinable or not String s1 = null; if (o1.getClass().equals(Participant.class)) { s1 = ((Participant) o1).getName(); } String s2 = null; if (o2.getClass().equals(Participant.class)) { s2 = ((Participant) o2).getName(); } result = compareString(s1, s2); } else if (m_criterion.equals(SORTED_BY_PARTICIPANT_UNIQNAME)) { // sort by whether the site is joinable or not String s1 = null; if (o1.getClass().equals(Participant.class)) { s1 = ((Participant) o1).getUniqname(); } String s2 = null; if (o2.getClass().equals(Participant.class)) { s2 = ((Participant) o2).getUniqname(); } result = compareString(s1, s2); } else if (m_criterion.equals(SORTED_BY_PARTICIPANT_ROLE)) { String s1 = ""; if (o1.getClass().equals(Participant.class)) { s1 = ((Participant) o1).getRole(); } String s2 = ""; if (o2.getClass().equals(Participant.class)) { s2 = ((Participant) o2).getRole(); } result = compareString(s1, s2); } else if (m_criterion.equals(SORTED_BY_PARTICIPANT_COURSE)) { // sort by whether the site is joinable or not String s1 = null; if (o1.getClass().equals(Participant.class)) { s1 = ((Participant) o1).getSection(); } String s2 = null; if (o2.getClass().equals(Participant.class)) { s2 = ((Participant) o2).getSection(); } result = compareString(s1, s2); } else if (m_criterion.equals(SORTED_BY_PARTICIPANT_ID)) { String s1 = null; if (o1.getClass().equals(Participant.class)) { s1 = ((Participant) o1).getRegId(); } String s2 = null; if (o2.getClass().equals(Participant.class)) { s2 = ((Participant) o2).getRegId(); } result = compareString(s1, s2); } else if (m_criterion.equals(SORTED_BY_PARTICIPANT_CREDITS)) { String s1 = null; if (o1.getClass().equals(Participant.class)) { s1 = ((Participant) o1).getCredits(); } String s2 = null; if (o2.getClass().equals(Participant.class)) { s2 = ((Participant) o2).getCredits(); } result = compareString(s1, s2); } else if (m_criterion.equals(SORTED_BY_CREATION_DATE)) { // sort by the site's creation date Time t1 = null; Time t2 = null; // get the times try { t1 = ((Site) o1).getProperties().getTimeProperty( ResourceProperties.PROP_CREATION_DATE); } catch (EntityPropertyNotDefinedException e) { } catch (EntityPropertyTypeException e) { } try { t2 = ((Site) o2).getProperties().getTimeProperty( ResourceProperties.PROP_CREATION_DATE); } catch (EntityPropertyNotDefinedException e) { } catch (EntityPropertyTypeException e) { } if (t1 == null) { result = -1; } else if (t2 == null) { result = 1; } else if (t1.before(t2)) { result = -1; } else { result = 1; } } else if (m_criterion.equals(rb.getString("group.title"))) { // sorted by the group title String s1 = ((Group) o1).getTitle(); String s2 = ((Group) o2).getTitle(); result = compareString(s1, s2); } else if (m_criterion.equals(rb.getString("group.number"))) { // sorted by the group title int n1 = ((Group) o1).getMembers().size(); int n2 = ((Group) o2).getMembers().size(); result = (n1 > n2) ? 1 : -1; } else if (m_criterion.equals(SORTED_BY_MEMBER_NAME)) { // sorted by the member name String s1 = null; String s2 = null; try { s1 = UserDirectoryService .getUser(((Member) o1).getUserId()).getSortName(); } catch (Exception ignore) { } try { s2 = UserDirectoryService .getUser(((Member) o2).getUserId()).getSortName(); } catch (Exception ignore) { } result = compareString(s1, s2); } if (m_asc == null) m_asc = Boolean.TRUE.toString(); // sort ascending or descending if (m_asc.equals(Boolean.FALSE.toString())) { result = -result; } return result; } // compare private int compareString(String s1, String s2) { int result; if (s1 == null && s2 == null) { result = 0; } else if (s2 == null) { result = 1; } else if (s1 == null) { result = -1; } else { result = collator.compare(s1, s2); } return result; } } // SiteComparator private class ToolComparator implements Comparator { /** * implementing the Comparator compare function * * @param o1 * The first object * @param o2 * The second object * @return The compare result. 1 is o1 < o2; 0 is o1.equals(o2); -1 * otherwise */ public int compare(Object o1, Object o2) { try { return ((Tool) o1).getTitle().compareTo(((Tool) o2).getTitle()); } catch (Exception e) { } return -1; } // compare } // ToolComparator public class MyIcon { protected String m_name = null; protected String m_url = null; protected String m_skin = null; public MyIcon(String name, String url, String skin) { m_name = name; m_url = url; m_skin = skin; } public String getName() { return m_name; } public String getUrl() { return m_url; } public String getSkin() { return m_skin; } } // a utility class for form select options public class IdAndText { public int id; public String text; public int getId() { return id; } public String getText() { return text; } } // IdAndText // a utility class for working with ToolConfigurations and ToolRegistrations // %%% convert featureList from IdAndText to Tool so getFeatures item.id = // chosen-feature.id is a direct mapping of data public class MyTool { public String id = NULL_STRING; public String title = NULL_STRING; public String description = NULL_STRING; public boolean selected = false; public String getId() { return id; } public String getTitle() { return title; } public String getDescription() { return description; } public boolean getSelected() { return selected; } } /* * WorksiteSetupPage is a utility class for working with site pages * configured by Worksite Setup * */ public class WorksiteSetupPage { public String pageId = NULL_STRING; public String pageTitle = NULL_STRING; public String toolId = NULL_STRING; public String getPageId() { return pageId; } public String getPageTitle() { return pageTitle; } public String getToolId() { return toolId; } } // WorksiteSetupPage /** * Participant in site access roles * */ public class Participant { public String name = NULL_STRING; // Note: uniqname is really a user ID public String uniqname = NULL_STRING; public String role = NULL_STRING; /** role from provider */ public String providerRole = NULL_STRING; /** The member credits */ protected String credits = NULL_STRING; /** The section */ public String section = NULL_STRING; /** The regestration id */ public String regId = NULL_STRING; /** removeable if not from provider */ public boolean removeable = true; public String getName() { return name; } public String getUniqname() { return uniqname; } public String getRole() { return role; } // cast to Role public String getProviderRole() { return providerRole; } public boolean isRemoveable() { return removeable; } // extra info from provider public String getCredits() { return credits; } // getCredits public String getSection() { return section; } // getSection public String getRegId() { return regId; } // getRegId /** * Access the user eid, if we can find it - fall back to the id if not. * * @return The user eid. */ public String getEid() { try { return UserDirectoryService.getUserEid(uniqname); } catch (UserNotDefinedException e) { return uniqname; } } /** * Access the user display id, if we can find it - fall back to the id * if not. * * @return The user display id. */ public String getDisplayId() { try { User user = UserDirectoryService.getUser(uniqname); return user.getDisplayId(); } catch (UserNotDefinedException e) { return uniqname; } } } // Participant /** * Student in roster * */ public class Student { public String name = NULL_STRING; public String uniqname = NULL_STRING; public String id = NULL_STRING; public String level = NULL_STRING; public String credits = NULL_STRING; public String role = NULL_STRING; public String course = NULL_STRING; public String section = NULL_STRING; public String getName() { return name; } public String getUniqname() { return uniqname; } public String getId() { return id; } public String getLevel() { return level; } public String getCredits() { return credits; } public String getRole() { return role; } public String getCourse() { return course; } public String getSection() { return section; } } // Student public class SiteInfo { public String site_id = NULL_STRING; // getId of Resource public String external_id = NULL_STRING; // if matches site_id // connects site with U-M // course information public String site_type = ""; public String iconUrl = NULL_STRING; public String infoUrl = NULL_STRING; public boolean joinable = false; public String joinerRole = NULL_STRING; public String title = NULL_STRING; // the short name of the site public String short_description = NULL_STRING; // the short (20 char) // description of the // site public String description = NULL_STRING; // the longer description of // the site public String additional = NULL_STRING; // additional information on // crosslists, etc. public boolean published = false; public boolean include = true; // include the site in the Sites index; // default is true. public String site_contact_name = NULL_STRING; // site contact name public String site_contact_email = NULL_STRING; // site contact email public String getSiteId() { return site_id; } public String getSiteType() { return site_type; } public String getTitle() { return title; } public String getDescription() { return description; } public String getIconUrl() { return iconUrl; } public String getInfoUrll() { return infoUrl; } public boolean getJoinable() { return joinable; } public String getJoinerRole() { return joinerRole; } public String getAdditional() { return additional; } public boolean getPublished() { return published; } public boolean getInclude() { return include; } public String getSiteContactName() { return site_contact_name; } public String getSiteContactEmail() { return site_contact_email; } } // SiteInfo // dissertation tool related /** * doFinish_grad_tools is called when creation of a Grad Tools site is * confirmed */ public void doFinish_grad_tools(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); // set up for the coming template state.setAttribute(STATE_TEMPLATE_INDEX, params.getString("continue")); int index = Integer.valueOf(params.getString("template-index")) .intValue(); actionForTemplate("continue", index, params, state); // add the pre-configured Grad Tools tools to a new site addGradToolsFeatures(state); // TODO: hard coding this frame id is fragile, portal dependent, and // needs to be fixed -ggolden // schedulePeerFrameRefresh("sitenav"); scheduleTopRefresh(); resetPaging(state); }// doFinish_grad_tools /** * addGradToolsFeatures adds features to a new Grad Tools student site * */ private void addGradToolsFeatures(SessionState state) { Site edit = null; Site template = null; // get a unique id String id = IdManager.createUuid(); // get the Grad Tools student site template try { template = SiteService.getSite(SITE_GTS_TEMPLATE); } catch (Exception e) { if (Log.isWarnEnabled()) M_log.warn("addGradToolsFeatures template " + e); } if (template != null) { // create a new site based on the template try { edit = SiteService.addSite(id, template); } catch (Exception e) { if (Log.isWarnEnabled()) M_log.warn("addGradToolsFeatures add/edit site " + e); } // set the tab, etc. if (edit != null) { SiteInfo siteInfo = (SiteInfo) state .getAttribute(STATE_SITE_INFO); edit.setShortDescription(siteInfo.short_description); edit.setTitle(siteInfo.title); edit.setPublished(true); edit.setPubView(false); edit.setType(SITE_TYPE_GRADTOOLS_STUDENT); // ResourcePropertiesEdit rpe = edit.getPropertiesEdit(); try { SiteService.save(edit); } catch (Exception e) { if (Log.isWarnEnabled()) M_log.warn("addGradToolsFeartures commitEdit " + e); } // now that the site and realm exist, we can set the email alias // set the GradToolsStudent site alias as: // gradtools-uniqname@servername String alias = "gradtools-" + SessionManager.getCurrentSessionUserId(); String channelReference = mailArchiveChannelReference(id); try { AliasService.setAlias(alias, channelReference); } catch (IdUsedException ee) { addAlert(state, rb.getString("java.alias") + " " + alias + " " + rb.getString("java.exists")); } catch (IdInvalidException ee) { addAlert(state, rb.getString("java.alias") + " " + alias + " " + rb.getString("java.isinval")); } catch (PermissionException ee) { M_log.warn(SessionManager.getCurrentSessionUserId() + " does not have permission to add alias. "); } } } } // addGradToolsFeatures /** * handle with add site options * */ public void doAdd_site_option(RunData data) { String option = data.getParameters().getString("option"); if (option.equals("finish")) { doFinish(data); } else if (option.equals("cancel")) { doCancel_create(data); } else if (option.equals("back")) { doBack(data); } } // doAdd_site_option /** * handle with duplicate site options * */ public void doDuplicate_site_option(RunData data) { String option = data.getParameters().getString("option"); if (option.equals("duplicate")) { doContinue(data); } else if (option.equals("cancel")) { doCancel(data); } else if (option.equals("finish")) { doContinue(data); } } // doDuplicate_site_option /** * Special check against the Dissertation service, which might not be * here... * * @return */ protected boolean isGradToolsCandidate(String userId) { // DissertationService.isCandidate(userId) - but the hard way Object service = ComponentManager .get("org.sakaiproject.api.app.dissertation.DissertationService"); if (service == null) return false; // the method signature Class[] signature = new Class[1]; signature[0] = String.class; // the method name String methodName = "isCandidate"; // find a method of this class with this name and signature try { Method method = service.getClass().getMethod(methodName, signature); // the parameters Object[] args = new Object[1]; args[0] = userId; // make the call Boolean rv = (Boolean) method.invoke(service, args); return rv.booleanValue(); } catch (Throwable t) { } return false; } /** * User has a Grad Tools student site * * @return */ protected boolean hasGradToolsStudentSite(String userId) { boolean has = false; int n = 0; try { n = SiteService.countSites( org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, SITE_TYPE_GRADTOOLS_STUDENT, null, null); if (n > 0) has = true; } catch (Exception e) { if (Log.isWarnEnabled()) M_log.warn("hasGradToolsStudentSite " + e); } return has; }// hasGradToolsStudentSite /** * Get the mail archive channel reference for the main container placement * for this site. * * @param siteId * The site id. * @return The mail archive channel reference for this site. */ protected String mailArchiveChannelReference(String siteId) { Object m = ComponentManager .get("org.sakaiproject.mailarchive.api.MailArchiveService"); if (m != null) { return "/mailarchive"+Entity.SEPARATOR+"channel"+Entity.SEPARATOR+siteId+Entity.SEPARATOR+SiteService.MAIN_CONTAINER; } else { return ""; } } /** * Transfer a copy of all entites from another context for any entity * producer that claims this tool id. * * @param toolId * The tool id. * @param fromContext * The context to import from. * @param toContext * The context to import into. */ protected void transferCopyEntities(String toolId, String fromContext, String toContext) { // TODO: used to offer to resources first - why? still needed? -ggolden // offer to all EntityProducers for (Iterator i = EntityManager.getEntityProducers().iterator(); i .hasNext();) { EntityProducer ep = (EntityProducer) i.next(); if (ep instanceof EntityTransferrer) { try { EntityTransferrer et = (EntityTransferrer) ep; // if this producer claims this tool id if (ArrayUtil.contains(et.myToolIds(), toolId)) { et.transferCopyEntities(fromContext, toContext, new Vector()); } } catch (Throwable t) { M_log.warn( "Error encountered while asking EntityTransfer to transferCopyEntities from: " + fromContext + " to: " + toContext, t); } } } } /** * @return Get a list of all tools that support the import (transfer copy) * option */ protected Set importTools() { HashSet rv = new HashSet(); // offer to all EntityProducers for (Iterator i = EntityManager.getEntityProducers().iterator(); i .hasNext();) { EntityProducer ep = (EntityProducer) i.next(); if (ep instanceof EntityTransferrer) { EntityTransferrer et = (EntityTransferrer) ep; String[] tools = et.myToolIds(); if (tools != null) { for (int t = 0; t < tools.length; t++) { rv.add(tools[t]); } } } } return rv; } /** * @param state * @return Get a list of all tools that should be included as options for * import */ protected List getToolsAvailableForImport(SessionState state) { // The Web Content and News tools do not follow the standard rules for // import // Even if the current site does not contain the tool, News and WC will // be // an option if the imported site contains it boolean displayWebContent = false; boolean displayNews = false; Set importSites = ((Hashtable) state.getAttribute(STATE_IMPORT_SITES)) .keySet(); Iterator sitesIter = importSites.iterator(); while (sitesIter.hasNext()) { Site site = (Site) sitesIter.next(); if (site.getToolForCommonId("sakai.iframe") != null) displayWebContent = true; if (site.getToolForCommonId("sakai.news") != null) displayNews = true; } List toolsOnImportList = (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); if (displayWebContent && !toolsOnImportList.contains("sakai.iframe")) toolsOnImportList.add("sakai.iframe"); if (displayNews && !toolsOnImportList.contains("sakai.news")) toolsOnImportList.add("sakai.news"); return toolsOnImportList; } // getToolsAvailableForImport private void setTermListForContext(Context context, SessionState state, boolean upcomingOnly) { List terms; if (upcomingOnly) { terms = cms != null?cms.getCurrentAcademicSessions():null; } else { // get all terms = cms != null?cms.getAcademicSessions():null; } if (terms != null && terms.size() > 0) { context.put("termList", terms); } } // setTermListForContext private void setSelectedTermForContext(Context context, SessionState state, String stateAttribute) { if (state.getAttribute(stateAttribute) != null) { context.put("selectedTerm", state.getAttribute(stateAttribute)); } } // setSelectedTermForContext /** * rewrote for 2.4 * * @param userId * @param academicSessionEid * @param courseOfferingHash * @param sectionHash */ private void prepareCourseAndSectionMap(String userId, String academicSessionEid, HashMap courseOfferingHash, HashMap sectionHash) { // looking for list of courseOffering and sections that should be // included in // the selection list. The course offering must be offered // 1. in the specific academic Session // 2. that the specified user has right to attach its section to a // course site // map = (section.eid, sakai rolename) if (groupProvider == null) { M_log.warn("Group provider not found"); return; } Map map = groupProvider.getGroupRolesForUser(userId); if (map == null) return; Set keys = map.keySet(); Set roleSet = getRolesAllowedToAttachSection(); for (Iterator i = keys.iterator(); i.hasNext();) { String sectionEid = (String) i.next(); String role = (String) map.get(sectionEid); if (includeRole(role, roleSet)) { Section section = null; getCourseOfferingAndSectionMap(academicSessionEid, courseOfferingHash, sectionHash, sectionEid, section); } } // now consider those user with affiliated sections List affiliatedSectionEids = affiliatedSectionProvider.getAffiliatedSectionEids(userId, academicSessionEid); if (affiliatedSectionEids != null) { for (int k = 0; k < affiliatedSectionEids.size(); k++) { String sectionEid = (String) affiliatedSectionEids.get(k); Section section = null; getCourseOfferingAndSectionMap(academicSessionEid, courseOfferingHash, sectionHash, sectionEid, section); } } } // prepareCourseAndSectionMap private void getCourseOfferingAndSectionMap(String academicSessionEid, HashMap courseOfferingHash, HashMap sectionHash, String sectionEid, Section section) { try { section = cms.getSection(sectionEid); } catch (IdNotFoundException e) { M_log.warn(e.getMessage()); } if (section != null) { String courseOfferingEid = section.getCourseOfferingEid(); CourseOffering courseOffering = cms .getCourseOffering(courseOfferingEid); String sessionEid = courseOffering.getAcademicSession() .getEid(); if (academicSessionEid.equals(sessionEid)) { // a long way to the conclusion that yes, this course // offering // should be included in the selected list. Sigh... // -daisyf ArrayList sectionList = (ArrayList) sectionHash .get(courseOffering.getEid()); if (sectionList == null) { sectionList = new ArrayList(); } sectionList.add(new SectionObject(section)); sectionHash.put(courseOffering.getEid(), sectionList); courseOfferingHash.put(courseOffering.getEid(), courseOffering); } } } /** * for 2.4 * * @param role * @return */ private boolean includeRole(String role, Set roleSet) { boolean includeRole = false; for (Iterator i = roleSet.iterator(); i.hasNext();) { String r = (String) i.next(); if (r.equals(role)) { includeRole = true; break; } } return includeRole; } // includeRole protected Set getRolesAllowedToAttachSection() { // Use !site.template.[site_type] String azgId = "!site.template.course"; AuthzGroup azgTemplate; try { azgTemplate = AuthzGroupService.getAuthzGroup(azgId); } catch (GroupNotDefinedException e) { M_log.warn("Could not find authz group " + azgId); return new HashSet(); } Set roles = azgTemplate.getRolesIsAllowed("site.upd"); roles.addAll(azgTemplate.getRolesIsAllowed("realm.upd")); return roles; } // getRolesAllowedToAttachSection /** * Here, we will preapre two HashMap: 1. courseOfferingHash stores * courseOfferingId and CourseOffering 2. sectionHash stores * courseOfferingId and a list of its Section We sorted the CourseOffering * by its eid & title and went through them one at a time to construct the * CourseObject that is used for the displayed in velocity. Each * CourseObject will contains a list of CourseOfferingObject(again used for * vm display). Usually, a CourseObject would only contain one * CourseOfferingObject. A CourseObject containing multiple * CourseOfferingObject implies that this is a cross-listing situation. * * @param userId * @param academicSessionEid * @return */ private List prepareCourseAndSectionListing(String userId, String academicSessionEid, SessionState state) { // courseOfferingHash = (courseOfferingEid, vourseOffering) // sectionHash = (courseOfferingEid, list of sections) HashMap courseOfferingHash = new HashMap(); HashMap sectionHash = new HashMap(); prepareCourseAndSectionMap(userId, academicSessionEid, courseOfferingHash, sectionHash); // courseOfferingHash & sectionHash should now be filled with stuffs // put section list in state for later use state.setAttribute(STATE_PROVIDER_SECTION_LIST, getSectionList(sectionHash)); ArrayList offeringList = new ArrayList(); Set keys = courseOfferingHash.keySet(); for (Iterator i = keys.iterator(); i.hasNext();) { CourseOffering o = (CourseOffering) courseOfferingHash .get((String) i.next()); offeringList.add(o); } Collection offeringListSorted = sortOffering(offeringList); ArrayList resultedList = new ArrayList(); // use this to keep track of courseOffering that we have dealt with // already // this is important 'cos cross-listed offering is dealt with together // with its // equivalents ArrayList dealtWith = new ArrayList(); for (Iterator j = offeringListSorted.iterator(); j.hasNext();) { CourseOffering o = (CourseOffering) j.next(); if (!dealtWith.contains(o.getEid())) { // 1. construct list of CourseOfferingObject for CourseObject ArrayList l = new ArrayList(); CourseOfferingObject coo = new CourseOfferingObject(o, (ArrayList) sectionHash.get(o.getEid())); l.add(coo); // 2. check if course offering is cross-listed Set set = cms.getEquivalentCourseOfferings(o.getEid()); if (set != null) { for (Iterator k = set.iterator(); k.hasNext();) { CourseOffering eo = (CourseOffering) k.next(); if (courseOfferingHash.containsKey(eo.getEid())) { // => cross-listed, then list them together CourseOfferingObject coo_equivalent = new CourseOfferingObject( eo, (ArrayList) sectionHash.get(eo.getEid())); l.add(coo_equivalent); dealtWith.add(eo.getEid()); } } } CourseObject co = new CourseObject(o, l); dealtWith.add(o.getEid()); resultedList.add(co); } } return resultedList; } // prepareCourseAndSectionListing /** * Sort CourseOffering by order of eid, title uisng velocity SortTool * * @param offeringList * @return */ private Collection sortOffering(ArrayList offeringList) { return sortCmObject(offeringList); /* * List propsList = new ArrayList(); propsList.add("eid"); * propsList.add("title"); SortTool sort = new SortTool(); return * sort.sort(offeringList, propsList); */ } // sortOffering /** * sort any Cm object such as CourseOffering, CourseOfferingObject, * SectionObject provided object has getter & setter for eid & title * * @param list * @return */ private Collection sortCmObject(List list) { if (list != null) { List propsList = new ArrayList(); propsList.add("eid"); propsList.add("title"); SortTool sort = new SortTool(); return sort.sort(list, propsList); } else { return list; } } // sortCmObject /** * this object is used for displaying purposes in chef_site-newSiteCourse.vm */ public class SectionObject { public Section section; public String eid; public String title; public String category; public String categoryDescription; public boolean isLecture; public boolean attached; public String authorizer; public SectionObject(Section section) { this.section = section; this.eid = section.getEid(); this.title = section.getTitle(); this.category = section.getCategory(); this.categoryDescription = cms .getSectionCategoryDescription(section.getCategory()); if ("01.lct".equals(section.getCategory())) { this.isLecture = true; } else { this.isLecture = false; } Set set = authzGroupService.getAuthzGroupIds(section.getEid()); if (set != null && !set.isEmpty()) { this.attached = true; } else { this.attached = false; } } public Section getSection() { return section; } public String getEid() { return eid; } public String getTitle() { return title; } public String getCategory() { return category; } public String getCategoryDescription() { return categoryDescription; } public boolean getIsLecture() { return isLecture; } public boolean getAttached() { return attached; } public String getAuthorizer() { return authorizer; } public void setAuthorizer(String authorizer) { this.authorizer = authorizer; } } // SectionObject constructor /** * this object is used for displaying purposes in chef_site-newSiteCourse.vm */ public class CourseObject { public String eid; public String title; public List courseOfferingObjects; public CourseObject(CourseOffering offering, List courseOfferingObjects) { this.eid = offering.getEid(); this.title = offering.getTitle(); this.courseOfferingObjects = courseOfferingObjects; } public String getEid() { return eid; } public String getTitle() { return title; } public List getCourseOfferingObjects() { return courseOfferingObjects; } } // CourseObject constructor /** * this object is used for displaying purposes in chef_site-newSiteCourse.vm */ public class CourseOfferingObject { public String eid; public String title; public List sections; public CourseOfferingObject(CourseOffering offering, List unsortedSections) { List propsList = new ArrayList(); propsList.add("category"); propsList.add("eid"); SortTool sort = new SortTool(); this.sections = new ArrayList(); if (unsortedSections != null) { this.sections = (List) sort.sort(unsortedSections, propsList); } this.eid = offering.getEid(); this.title = offering.getTitle(); } public String getEid() { return eid; } public String getTitle() { return title; } public List getSections() { return sections; } } // CourseOfferingObject constructor /** * get campus user directory for dispaly in chef_newSiteCourse.vm * * @return */ private String getCampusDirectory() { return ServerConfigurationService.getString( "site-manage.campusUserDirectory", null); } // getCampusDirectory private void removeAnyFlagedSection(SessionState state, ParameterParser params) { List all = new ArrayList(); List providerCourseList = (List) state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN); if (providerCourseList != null && providerCourseList.size() > 0) { all.addAll(providerCourseList); } List manualCourseList = (List) state .getAttribute(SITE_MANUAL_COURSE_LIST); if (manualCourseList != null && manualCourseList.size() > 0) { all.addAll(manualCourseList); } for (int i = 0; i < all.size(); i++) { String eid = (String) all.get(i); String field = "removeSection" + eid; String toRemove = params.getString(field); if ("true".equals(toRemove)) { // eid is in either providerCourseList or manualCourseList // either way, just remove it if (providerCourseList != null) providerCourseList.remove(eid); if (manualCourseList != null) manualCourseList.remove(eid); } } List<SectionObject> requestedCMSections = (List<SectionObject>) state .getAttribute(STATE_CM_REQUESTED_SECTIONS); if (requestedCMSections != null) { for (int i = 0; i < requestedCMSections.size(); i++) { SectionObject so = (SectionObject) requestedCMSections.get(i); String field = "removeSection" + so.getEid(); String toRemove = params.getString(field); if ("true".equals(toRemove)) { requestedCMSections.remove(so); } } if (requestedCMSections.size() == 0) state.removeAttribute(STATE_CM_REQUESTED_SECTIONS); } List<SectionObject> authorizerSections = (List<SectionObject>) state .getAttribute(STATE_CM_AUTHORIZER_SECTIONS); if (authorizerSections != null) { for (int i = 0; i < authorizerSections.size(); i++) { SectionObject so = (SectionObject) authorizerSections.get(i); String field = "removeSection" + so.getEid(); String toRemove = params.getString(field); if ("true".equals(toRemove)) { authorizerSections.remove(so); } } if (authorizerSections.size() == 0) state.removeAttribute(STATE_CM_AUTHORIZER_SECTIONS); } // if list is empty, set to null. This is important 'cos null is // the indication that the list is empty in the code. See case 2 on line // 1081 if (manualCourseList != null && manualCourseList.size() == 0) manualCourseList = null; if (providerCourseList != null && providerCourseList.size() == 0) providerCourseList = null; } private void collectNewSiteInfo(SiteInfo siteInfo, SessionState state, ParameterParser params, List providerChosenList) { if (state.getAttribute(STATE_MESSAGE) == null) { siteInfo = new SiteInfo(); if (state.getAttribute(STATE_SITE_INFO) != null) { siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); } // site title is the title of the 1st section selected - // daisyf's note if (providerChosenList != null && providerChosenList.size() >= 1) { String title = prepareTitle((List) state .getAttribute(STATE_PROVIDER_SECTION_LIST), providerChosenList); siteInfo.title = title; } state.setAttribute(STATE_SITE_INFO, siteInfo); if (params.getString("manualAdds") != null && ("true").equals(params.getString("manualAdds"))) { // if creating a new site state.setAttribute(STATE_TEMPLATE_INDEX, "37"); state.setAttribute(STATE_MANUAL_ADD_COURSE_NUMBER, new Integer( 1)); } else if (params.getString("findCourse") != null && ("true").equals(params.getString("findCourse"))) { state.setAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN, providerChosenList); prepFindPage(state); } else { // no manual add state.removeAttribute(STATE_MANUAL_ADD_COURSE_NUMBER); state.removeAttribute(STATE_MANUAL_ADD_COURSE_FIELDS); state.removeAttribute(STATE_SITE_QUEST_UNIQNAME); if (getStateSite(state) != null) { // if revising a site, go to the confirmation // page of adding classes //state.setAttribute(STATE_TEMPLATE_INDEX, "37"); } else { // if creating a site, go the the site // information entry page state.setAttribute(STATE_TEMPLATE_INDEX, "2"); } } } } /** * By default, courseManagement is implemented * * @return */ private boolean courseManagementIsImplemented() { boolean returnValue = true; String isImplemented = ServerConfigurationService.getString( "site-manage.courseManagementSystemImplemented", "true"); if (("false").equals(isImplemented)) returnValue = false; return returnValue; } private List getCMSubjects() { String subjectCategory = getCMSubjectCategory(); if (cms == null || subjectCategory == null) { return new ArrayList(0); } Collection c = sortCmObject(cms.findCourseSets(subjectCategory)); return (List) c; } private List getCMSections(String offeringEid) { if (offeringEid == null || offeringEid.trim().length() == 0) return null; if (cms != null) { Set sections = cms.getSections(offeringEid); Collection c = sortCmObject(new ArrayList(sections)); return (List) c; } return new ArrayList(0); } private List getCMCourseOfferings(String subjectEid, String termID) { if (subjectEid == null || subjectEid.trim().length() == 0 || termID == null || termID.trim().length() == 0) return null; if (cms != null) { Set offerings = cms.getCourseOfferingsInCourseSet(subjectEid);// , // termID); ArrayList returnList = new ArrayList(); Iterator coIt = offerings.iterator(); while (coIt.hasNext()) { CourseOffering co = (CourseOffering) coIt.next(); AcademicSession as = co.getAcademicSession(); if (as != null && as.getEid().equals(termID)) returnList.add(co); } Collection c = sortCmObject(returnList); return (List) c; } return new ArrayList(0); } private String getCMSubjectCategory() { if (cmSubjectCategory == null) { cmSubjectCategory = ServerConfigurationService .getString("site-manage.cms.subject.category"); if (cmSubjectCategory == null) { if (warnedNoSubjectCategory) M_log .debug(rb .getString("nscourse.cm.configure.log.nosubjectcat")); else { M_log .info(rb .getString("nscourse.cm.configure.log.nosubjectcat")); warnedNoSubjectCategory = true; } } } return cmSubjectCategory; } private List<String> getCMLevelLabels() { List<String> rv = new Vector<String>(); List<SectionField> fields = sectionFieldProvider.getRequiredFields(); for (int k = 0; k < fields.size(); k++) { SectionField sectionField = (SectionField) fields.get(k); rv.add(sectionField.getLabelKey()); } return rv; } private void prepFindPage(SessionState state) { final List cmLevels = getCMLevelLabels(), selections = (List) state .getAttribute(STATE_CM_LEVEL_SELECTIONS); int lvlSz = 0; if (cmLevels == null || (lvlSz = cmLevels.size()) < 1) { // TODO: no cm levels configured, redirect to manual add return; } if (selections != null && selections.size() == lvlSz) { Section sect = cms.getSection((String) selections.get(selections .size() - 1)); SectionObject so = new SectionObject(sect); state.setAttribute(STATE_CM_SELECTED_SECTION, so); } else state.removeAttribute(STATE_CM_SELECTED_SECTION); state.setAttribute(STATE_CM_LEVELS, cmLevels); state.setAttribute(STATE_CM_LEVEL_SELECTIONS, selections); // check the configuration setting for choosing next screen Boolean skipCourseSectionSelection = ServerConfigurationService.getBoolean("wsetup.skipCourseSectionSelection", Boolean.FALSE); if (!skipCourseSectionSelection.booleanValue()) { // go to the course/section selection page state.setAttribute(STATE_TEMPLATE_INDEX, "53"); } else { // skip the course/section selection page, go directly into the manually create course page state.setAttribute(STATE_TEMPLATE_INDEX, "37"); } } private void addRequestedSection(SessionState state) { SectionObject so = (SectionObject) state .getAttribute(STATE_CM_SELECTED_SECTION); String uniqueName = (String) state .getAttribute(STATE_SITE_QUEST_UNIQNAME); if (so == null) return; so.setAuthorizer(uniqueName); if (getStateSite(state) == null) { // creating new site List<SectionObject> requestedSections = (List<SectionObject>) state.getAttribute(STATE_CM_REQUESTED_SECTIONS); if (requestedSections == null) { requestedSections = new ArrayList<SectionObject>(); } // don't add duplicates if (!requestedSections.contains(so)) requestedSections.add(so); // if the title has not yet been set and there is just // one section, set the title to that section's EID if (requestedSections.size() == 1) { SiteInfo siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); if (siteInfo == null) { siteInfo = new SiteInfo(); } if (siteInfo.title == null || siteInfo.title.trim().length() == 0) { siteInfo.title = so.getEid(); } state.setAttribute(STATE_SITE_INFO, siteInfo); } state.setAttribute(STATE_CM_REQUESTED_SECTIONS, requestedSections); state.removeAttribute(STATE_CM_SELECTED_SECTION); } else { // editing site state.setAttribute(STATE_CM_SELECTED_SECTION, so); List<SectionObject> cmSelectedSections = (List<SectionObject>) state.getAttribute(STATE_CM_SELECTED_SECTIONS); if (cmSelectedSections == null) { cmSelectedSections = new ArrayList<SectionObject>(); } // don't add duplicates if (!cmSelectedSections.contains(so)) cmSelectedSections.add(so); state.setAttribute(STATE_CM_SELECTED_SECTIONS, cmSelectedSections); state.removeAttribute(STATE_CM_SELECTED_SECTION); } state.removeAttribute(STATE_CM_LEVEL_SELECTIONS); } public void doFind_course(RunData data) { final SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); final ParameterParser params = data.getParameters(); final String option = params.get("option"); if (option != null) { if ("continue".equals(option)) { String uniqname = StringUtil.trimToNull(params .getString("uniqname")); state.setAttribute(STATE_SITE_QUEST_UNIQNAME, uniqname); if (state.getAttribute(STATE_FUTURE_TERM_SELECTED) != null && !((Boolean) state .getAttribute(STATE_FUTURE_TERM_SELECTED)) .booleanValue()) { // if a future term is selected, do not check authorization // uniqname if (uniqname == null) { addAlert(state, rb.getString("java.author") + " " + ServerConfigurationService .getString("officialAccountName") + ". "); } else { try { UserDirectoryService.getUserByEid(uniqname); addRequestedSection(state); } catch (UserNotDefinedException e) { addAlert( state, rb.getString("java.validAuthor1") + " " + ServerConfigurationService .getString("officialAccountName") + " " + rb.getString("java.validAuthor2")); } } } else { addRequestedSection(state); } if (state.getAttribute(STATE_MESSAGE) == null) { if (getStateSite(state) == null) { state.setAttribute(STATE_TEMPLATE_INDEX, "2"); } else { state.setAttribute(STATE_TEMPLATE_INDEX, "44"); } } doContinue(data); return; } else if ("back".equals(option)) { doBack(data); return; } else if ("cancel".equals(option)) { if (getStateSite(state) == null) { doCancel_create(data);// cancel from new site creation } else { doCancel(data);// cancel from site info editing } return; } else if (option.equals("add")) { addRequestedSection(state); return; } else if (option.equals("manual")) { // TODO: send to case 37 state.setAttribute(STATE_TEMPLATE_INDEX, "37"); state.setAttribute(STATE_MANUAL_ADD_COURSE_NUMBER, new Integer( 1)); return; } else if (option.equals("remove")) removeAnyFlagedSection(state, params); } final List selections = new ArrayList(3); int cmLevel = 3; String deptChanged = params.get("deptChanged"); if ("true".equals(deptChanged)) { // when dept changes, remove selection on courseOffering and // courseSection cmLevel = 1; } for (int i = 0; i < cmLevel; i++) { String val = params.get("idField_" + i); if (val == null || val.trim().length() < 1) { break; } selections.add(val); } state.setAttribute(STATE_CM_LEVEL_SELECTIONS, selections); prepFindPage(state); } /** * return the title of the 1st section in the chosen list that has an * enrollment set. No discrimination on section category * * @param sectionList * @param chosenList * @return */ private String prepareTitle(List sectionList, List chosenList) { String title = null; HashMap map = new HashMap(); for (Iterator i = sectionList.iterator(); i.hasNext();) { SectionObject o = (SectionObject) i.next(); map.put(o.getEid(), o.getSection()); } for (int j = 0; j < chosenList.size(); j++) { String eid = (String) chosenList.get(j); Section s = (Section) map.get(eid); // we will always has a title regardless but we prefer it to be the // 1st section on the chosen list that has an enrollment set if (j == 0) { title = s.getTitle(); } if (s.getEnrollmentSet() != null) { title = s.getTitle(); break; } } return title; } // prepareTitle /** * return an ArrayList of SectionObject * * @param sectionHash * contains an ArrayList collection of SectionObject * @return */ private ArrayList getSectionList(HashMap sectionHash) { ArrayList list = new ArrayList(); // values is an ArrayList of section Collection c = sectionHash.values(); for (Iterator i = c.iterator(); i.hasNext();) { ArrayList l = (ArrayList) i.next(); list.addAll(l); } return list; } private String getAuthorizers(SessionState state) { String authorizers = ""; ArrayList list = (ArrayList) state .getAttribute(STATE_CM_AUTHORIZER_LIST); if (list != null) { for (int i = 0; i < list.size(); i++) { if (i == 0) { authorizers = (String) list.get(i); } else { authorizers = authorizers + ", " + list.get(i); } } } return authorizers; } private List prepareSectionObject(List sectionList, String userId) { ArrayList list = new ArrayList(); if (sectionList != null) { for (int i = 0; i < sectionList.size(); i++) { String sectionEid = (String) sectionList.get(i); Section s = cms.getSection(sectionEid); SectionObject so = new SectionObject(s); so.setAuthorizer(userId); list.add(so); } } return list; } /** * change collection object to list object * @param c * @return */ private List collectionToList(Collection c) { List rv = new Vector(); if (c!=null) { for (Iterator i = c.iterator(); i.hasNext();) { rv.add(i.next()); } } return rv; } }
true
true
private String buildContextForTemplate(int index, VelocityPortlet portlet, Context context, RunData data, SessionState state) { String realmId = ""; String site_type = ""; String sortedBy = ""; String sortedAsc = ""; ParameterParser params = data.getParameters(); context.put("tlang", rb); context.put("alertMessage", state.getAttribute(STATE_MESSAGE)); // If cleanState() has removed SiteInfo, get a new instance into state SiteInfo siteInfo = new SiteInfo(); if (state.getAttribute(STATE_SITE_INFO) != null) { siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); } else { state.setAttribute(STATE_SITE_INFO, siteInfo); } // Lists used in more than one template // Access List roles = new Vector(); // the hashtables for News and Web Content tools Hashtable newsTitles = new Hashtable(); Hashtable newsUrls = new Hashtable(); Hashtable wcTitles = new Hashtable(); Hashtable wcUrls = new Hashtable(); List toolRegistrationList = new Vector(); List toolRegistrationSelectedList = new Vector(); ResourceProperties siteProperties = null; // for showing site creation steps if (state.getAttribute(SITE_CREATE_TOTAL_STEPS) != null) { context.put("totalSteps", state .getAttribute(SITE_CREATE_TOTAL_STEPS)); } if (state.getAttribute(SITE_CREATE_CURRENT_STEP) != null) { context.put("step", state.getAttribute(SITE_CREATE_CURRENT_STEP)); } String hasGradSites = ServerConfigurationService.getString( "withDissertation", Boolean.FALSE.toString()); context.put("cms", cms); // course site type context.put("courseSiteType", state.getAttribute(STATE_COURSE_SITE_TYPE)); Site site = getStateSite(state); switch (index) { case 0: /* * buildContextForTemplate chef_site-list.vm * */ // site types List sTypes = (List) state.getAttribute(STATE_SITE_TYPES); // make sure auto-updates are enabled Hashtable views = new Hashtable(); if (SecurityService.isSuperUser()) { views.put(rb.getString("java.allmy"), rb .getString("java.allmy")); views.put(rb.getString("java.my") + " " + rb.getString("java.sites"), rb.getString("java.my")); for (int sTypeIndex = 0; sTypeIndex < sTypes.size(); sTypeIndex++) { String type = (String) sTypes.get(sTypeIndex); views.put(type + " " + rb.getString("java.sites"), type); } if (hasGradSites.equalsIgnoreCase("true")) { views.put(rb.getString("java.gradtools") + " " + rb.getString("java.sites"), rb .getString("java.gradtools")); } if (state.getAttribute(STATE_VIEW_SELECTED) == null) { state.setAttribute(STATE_VIEW_SELECTED, rb .getString("java.allmy")); } context.put("superUser", Boolean.TRUE); } else { context.put("superUser", Boolean.FALSE); views.put(rb.getString("java.allmy"), rb .getString("java.allmy")); // if there is a GradToolsStudent choice inside boolean remove = false; if (hasGradSites.equalsIgnoreCase("true")) { try { // the Grad Tools site option is only presented to // GradTools Candidates String userId = StringUtil.trimToZero(SessionManager .getCurrentSessionUserId()); // am I a grad student? if (!isGradToolsCandidate(userId)) { // not a gradstudent remove = true; } } catch (Exception e) { remove = true; } } else { // not support for dissertation sites remove = true; } // do not show this site type in views // sTypes.remove(new String(SITE_TYPE_GRADTOOLS_STUDENT)); for (int sTypeIndex = 0; sTypeIndex < sTypes.size(); sTypeIndex++) { String type = (String) sTypes.get(sTypeIndex); if (!type.equals(SITE_TYPE_GRADTOOLS_STUDENT)) { views .put(type + " " + rb.getString("java.sites"), type); } } if (!remove) { views.put(rb.getString("java.gradtools") + " " + rb.getString("java.sites"), rb .getString("java.gradtools")); } // default view if (state.getAttribute(STATE_VIEW_SELECTED) == null) { state.setAttribute(STATE_VIEW_SELECTED, rb .getString("java.allmy")); } } context.put("views", views); if (state.getAttribute(STATE_VIEW_SELECTED) != null) { context.put("viewSelected", (String) state .getAttribute(STATE_VIEW_SELECTED)); } String search = (String) state.getAttribute(STATE_SEARCH); context.put("search_term", search); sortedBy = (String) state.getAttribute(SORTED_BY); if (sortedBy == null) { state.setAttribute(SORTED_BY, SortType.TITLE_ASC.toString()); sortedBy = SortType.TITLE_ASC.toString(); } sortedAsc = (String) state.getAttribute(SORTED_ASC); if (sortedAsc == null) { sortedAsc = Boolean.TRUE.toString(); state.setAttribute(SORTED_ASC, sortedAsc); } if (sortedBy != null) context.put("currentSortedBy", sortedBy); if (sortedAsc != null) context.put("currentSortAsc", sortedAsc); String portalUrl = ServerConfigurationService.getPortalUrl(); context.put("portalUrl", portalUrl); List sites = prepPage(state); state.setAttribute(STATE_SITES, sites); context.put("sites", sites); context.put("totalPageNumber", new Integer(totalPageNumber(state))); context.put("searchString", state.getAttribute(STATE_SEARCH)); context.put("form_search", FORM_SEARCH); context.put("formPageNumber", FORM_PAGE_NUMBER); context.put("prev_page_exists", state .getAttribute(STATE_PREV_PAGE_EXISTS)); context.put("next_page_exists", state .getAttribute(STATE_NEXT_PAGE_EXISTS)); context.put("current_page", state.getAttribute(STATE_CURRENT_PAGE)); // put the service in the context (used for allow update calls on // each site) context.put("service", SiteService.getInstance()); context.put("sortby_title", SortType.TITLE_ASC.toString()); context.put("sortby_type", SortType.TYPE_ASC.toString()); context.put("sortby_createdby", SortType.CREATED_BY_ASC.toString()); context.put("sortby_publish", SortType.PUBLISHED_ASC.toString()); context.put("sortby_createdon", SortType.CREATED_ON_ASC.toString()); // top menu bar Menu bar = new MenuImpl(portlet, data, (String) state .getAttribute(STATE_ACTION)); if (SiteService.allowAddSite(null)) { bar.add(new MenuEntry(rb.getString("java.new"), "doNew_site")); } bar.add(new MenuEntry(rb.getString("java.revise"), null, true, MenuItem.CHECKED_NA, "doGet_site", "sitesForm")); bar.add(new MenuEntry(rb.getString("java.delete"), null, true, MenuItem.CHECKED_NA, "doMenu_site_delete", "sitesForm")); context.put("menu", bar); // default to be no pageing context.put("paged", Boolean.FALSE); Menu bar2 = new MenuImpl(portlet, data, (String) state .getAttribute(STATE_ACTION)); // add the search commands addSearchMenus(bar2, state); context.put("menu2", bar2); pagingInfoToContext(state, context); return (String) getContext(data).get("template") + TEMPLATE[0]; case 1: /* * buildContextForTemplate chef_site-type.vm * */ if (hasGradSites.equalsIgnoreCase("true")) { context.put("withDissertation", Boolean.TRUE); try { // the Grad Tools site option is only presented to UM grad // students String userId = StringUtil.trimToZero(SessionManager .getCurrentSessionUserId()); // am I a UM grad student? Boolean isGradStudent = new Boolean( isGradToolsCandidate(userId)); context.put("isGradStudent", isGradStudent); // if I am a UM grad student, do I already have a Grad Tools // site? boolean noGradToolsSite = true; if (hasGradToolsStudentSite(userId)) noGradToolsSite = false; context .put("noGradToolsSite", new Boolean(noGradToolsSite)); } catch (Exception e) { if (Log.isWarnEnabled()) { M_log.warn("buildContextForTemplate chef_site-type.vm " + e); } } } else { context.put("withDissertation", Boolean.FALSE); } List types = (List) state.getAttribute(STATE_SITE_TYPES); context.put("siteTypes", types); // put selected/default site type into context if (siteInfo.site_type != null && siteInfo.site_type.length() > 0) { context.put("typeSelected", siteInfo.site_type); } else if (types.size() > 0) { context.put("typeSelected", types.get(0)); } setTermListForContext(context, state, true); // true => only // upcoming terms setSelectedTermForContext(context, state, STATE_TERM_SELECTED); return (String) getContext(data).get("template") + TEMPLATE[1]; case 2: /* * buildContextForTemplate chef_site-newSiteInformation.vm * */ context.put("siteTypes", state.getAttribute(STATE_SITE_TYPES)); String siteType = (String) state.getAttribute(STATE_SITE_TYPE); context.put("type", siteType); if (siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); context.put("isProjectSite", Boolean.FALSE); if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) { context.put("selectedProviderCourse", state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN)); } List<SectionObject> cmRequestedList = (List<SectionObject>) state .getAttribute(STATE_CM_REQUESTED_SECTIONS); if (cmRequestedList != null) { context.put("cmRequestedSections", cmRequestedList); context.put("back", "53"); } List<SectionObject> cmAuthorizerSectionList = (List<SectionObject>) state .getAttribute(STATE_CM_AUTHORIZER_SECTIONS); if (cmAuthorizerSectionList != null) { context .put("cmAuthorizerSections", cmAuthorizerSectionList); context.put("back", "36"); } if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { int number = ((Integer) state .getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)) .intValue(); context.put("manualAddNumber", new Integer(number - 1)); context.put("manualAddFields", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); context.put("back", "37"); } else { if (courseManagementIsImplemented()) { context.put("back", "36"); } else { context.put("back", "0"); context.put("template-index", "37"); } } context.put("skins", state.getAttribute(STATE_ICONS)); if (StringUtil.trimToNull(siteInfo.getIconUrl()) != null) { context.put("selectedIcon", siteInfo.getIconUrl()); } } else { context.put("isCourseSite", Boolean.FALSE); if (siteType.equalsIgnoreCase("project")) { context.put("isProjectSite", Boolean.TRUE); } if (StringUtil.trimToNull(siteInfo.iconUrl) != null) { context.put(FORM_ICON_URL, siteInfo.iconUrl); } context.put("back", "1"); } context.put(FORM_TITLE, siteInfo.title); context.put(FORM_SHORT_DESCRIPTION, siteInfo.short_description); context.put(FORM_DESCRIPTION, siteInfo.description); // defalt the site contact person to the site creator if (siteInfo.site_contact_name.equals(NULL_STRING) && siteInfo.site_contact_email.equals(NULL_STRING)) { User user = UserDirectoryService.getCurrentUser(); siteInfo.site_contact_name = user.getDisplayName(); siteInfo.site_contact_email = user.getEmail(); } context.put("form_site_contact_name", siteInfo.site_contact_name); context.put("form_site_contact_email", siteInfo.site_contact_email); // those manual inputs context.put("form_requiredFields", sectionFieldProvider .getRequiredFields()); context.put("fieldValues", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); return (String) getContext(data).get("template") + TEMPLATE[2]; case 3: /* * buildContextForTemplate chef_site-newSiteFeatures.vm * */ siteType = (String) state.getAttribute(STATE_SITE_TYPE); if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); context.put("isProjectSite", Boolean.FALSE); } else { context.put("isCourseSite", Boolean.FALSE); if (siteType.equalsIgnoreCase("project")) { context.put("isProjectSite", Boolean.TRUE); } } context.put("defaultTools", ServerConfigurationService .getToolsRequired(siteType)); toolRegistrationSelectedList = (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); // If this is the first time through, check for tools // which should be selected by default. List defaultSelectedTools = ServerConfigurationService .getDefaultTools(siteType); if (toolRegistrationSelectedList == null) { toolRegistrationSelectedList = new Vector(defaultSelectedTools); } context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); // String toolId's context.put(STATE_TOOL_REGISTRATION_LIST, state .getAttribute(STATE_TOOL_REGISTRATION_LIST)); // %%% use // ToolRegistrations // for // template // list context .put("emailId", state .getAttribute(STATE_TOOL_EMAIL_ADDRESS)); context.put("serverName", ServerConfigurationService .getServerName()); // The "Home" tool checkbox needs special treatment to be selected // by // default. Boolean checkHome = (Boolean) state .getAttribute(STATE_TOOL_HOME_SELECTED); if (checkHome == null) { if ((defaultSelectedTools != null) && defaultSelectedTools.contains(HOME_TOOL_ID)) { checkHome = Boolean.TRUE; } } context.put("check_home", checkHome); // titles for news tools context.put("newsTitles", state.getAttribute(STATE_NEWS_TITLES)); // titles for web content tools context.put("wcTitles", state .getAttribute(STATE_WEB_CONTENT_TITLES)); // urls for news tools context.put("newsUrls", state.getAttribute(STATE_NEWS_URLS)); // urls for web content tools context.put("wcUrls", state.getAttribute(STATE_WEB_CONTENT_URLS)); context.put("sites", SiteService.getSites( org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, null, null, null, SortType.TITLE_ASC, null)); context.put("import", state.getAttribute(STATE_IMPORT)); context.put("importSites", state.getAttribute(STATE_IMPORT_SITES)); return (String) getContext(data).get("template") + TEMPLATE[3]; case 4: /* * buildContextForTemplate chef_site-addRemoveFeatures.vm * */ context.put("SiteTitle", site.getTitle()); String type = (String) state.getAttribute(STATE_SITE_TYPE); context.put("defaultTools", ServerConfigurationService .getToolsRequired(type)); boolean myworkspace_site = false; // Put up tool lists filtered by category List siteTypes = (List) state.getAttribute(STATE_SITE_TYPES); if (siteTypes.contains(type)) { myworkspace_site = false; } if (SiteService.isUserSite(site.getId()) || (type != null && type.equalsIgnoreCase("myworkspace"))) { myworkspace_site = true; type = "myworkspace"; } context.put("myworkspace_site", new Boolean(myworkspace_site)); context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST)); // titles for news tools context.put("newsTitles", state.getAttribute(STATE_NEWS_TITLES)); // titles for web content tools context.put("wcTitles", state .getAttribute(STATE_WEB_CONTENT_TITLES)); // urls for news tools context.put("newsUrls", state.getAttribute(STATE_NEWS_URLS)); // urls for web content tools context.put("wcUrls", state.getAttribute(STATE_WEB_CONTENT_URLS)); context.put(STATE_TOOL_REGISTRATION_LIST, state .getAttribute(STATE_TOOL_REGISTRATION_LIST)); context.put("check_home", state .getAttribute(STATE_TOOL_HOME_SELECTED)); // get the email alias when an Email Archive tool has been selected String channelReference = mailArchiveChannelReference(site.getId()); List aliases = AliasService.getAliases(channelReference, 1, 1); if (aliases.size() > 0) { state.setAttribute(STATE_TOOL_EMAIL_ADDRESS, ((Alias) aliases .get(0)).getId()); } else { state.removeAttribute(STATE_TOOL_EMAIL_ADDRESS); } if (state.getAttribute(STATE_TOOL_EMAIL_ADDRESS) != null) { context.put("emailId", state .getAttribute(STATE_TOOL_EMAIL_ADDRESS)); } context.put("serverName", ServerConfigurationService .getServerName()); context.put("backIndex", "12"); return (String) getContext(data).get("template") + TEMPLATE[4]; case 5: /* * buildContextForTemplate chef_site-addParticipant.vm * */ context.put("title", site.getTitle()); roles = getRoles(state); context.put("roles", roles); // Note that (for now) these strings are in both sakai.properties // and sitesetupgeneric.properties context.put("officialAccountSectionTitle", ServerConfigurationService .getString("officialAccountSectionTitle")); context.put("officialAccountName", ServerConfigurationService .getString("officialAccountName")); context.put("officialAccountLabel", ServerConfigurationService .getString("officialAccountLabel")); context.put("nonOfficialAccountSectionTitle", ServerConfigurationService .getString("nonOfficialAccountSectionTitle")); context.put("nonOfficialAccountName", ServerConfigurationService .getString("nonOfficialAccountName")); context.put("nonOfficialAccountLabel", ServerConfigurationService .getString("nonOfficialAccountLabel")); if (state.getAttribute("officialAccountValue") != null) { context.put("officialAccountValue", (String) state .getAttribute("officialAccountValue")); } if (state.getAttribute("nonOfficialAccountValue") != null) { context.put("nonOfficialAccountValue", (String) state .getAttribute("nonOfficialAccountValue")); } if (state.getAttribute("form_same_role") != null) { context.put("form_same_role", ((Boolean) state .getAttribute("form_same_role")).toString()); } else { context.put("form_same_role", Boolean.TRUE.toString()); } context.put("backIndex", "12"); return (String) getContext(data).get("template") + TEMPLATE[5]; case 6: /* * buildContextForTemplate chef_site-removeParticipants.vm * */ context.put("title", site.getTitle()); realmId = SiteService.siteReference(site.getId()); try { AuthzGroup realm = AuthzGroupService.getAuthzGroup(realmId); try { List removeableList = (List) state .getAttribute(STATE_REMOVEABLE_USER_LIST); List removeableParticipants = new Vector(); for (int k = 0; k < removeableList.size(); k++) { User user = UserDirectoryService .getUser((String) removeableList.get(k)); Participant participant = new Participant(); participant.name = user.getSortName(); participant.uniqname = user.getId(); Role r = realm.getUserRole(user.getId()); if (r != null) { participant.role = r.getId(); } removeableParticipants.add(participant); } context.put("removeableList", removeableParticipants); } catch (UserNotDefinedException ee) { } } catch (GroupNotDefinedException e) { } context.put("backIndex", "18"); return (String) getContext(data).get("template") + TEMPLATE[6]; case 7: /* * buildContextForTemplate chef_site-changeRoles.vm * */ context.put("same_role", state .getAttribute(STATE_CHANGEROLE_SAMEROLE)); roles = getRoles(state); context.put("roles", roles); context.put("currentRole", state .getAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE)); context.put("participantSelectedList", state .getAttribute(STATE_SELECTED_PARTICIPANTS)); context.put("selectedRoles", state .getAttribute(STATE_SELECTED_PARTICIPANT_ROLES)); context.put("siteTitle", site.getTitle()); return (String) getContext(data).get("template") + TEMPLATE[7]; case 8: /* * buildContextForTemplate chef_site-siteDeleteConfirm.vm * */ String site_title = NULL_STRING; String[] removals = (String[]) state .getAttribute(STATE_SITE_REMOVALS); List remove = new Vector(); String user = SessionManager.getCurrentSessionUserId(); String workspace = SiteService.getUserSiteId(user); if (removals != null && removals.length != 0) { for (int i = 0; i < removals.length; i++) { String id = (String) removals[i]; if (!(id.equals(workspace))) { try { site_title = SiteService.getSite(id).getTitle(); } catch (IdUnusedException e) { M_log .warn("SiteAction.doSite_delete_confirmed - IdUnusedException " + id); addAlert(state, rb.getString("java.sitewith") + " " + id + " " + rb.getString("java.couldnt") + " "); } if (SiteService.allowRemoveSite(id)) { try { Site removeSite = SiteService.getSite(id); remove.add(removeSite); } catch (IdUnusedException e) { M_log .warn("SiteAction.buildContextForTemplate chef_site-siteDeleteConfirm.vm: IdUnusedException"); } } else { addAlert(state, site_title + " " + rb.getString("java.couldntdel") + " "); } } else { addAlert(state, rb.getString("java.yourwork")); } } if (remove.size() == 0) { addAlert(state, rb.getString("java.click")); } } context.put("removals", remove); return (String) getContext(data).get("template") + TEMPLATE[8]; case 9: /* * buildContextForTemplate chef_site-publishUnpublish.vm * */ context.put("publish", Boolean.valueOf(((SiteInfo) state .getAttribute(STATE_SITE_INFO)).getPublished())); context.put("backIndex", "12"); return (String) getContext(data).get("template") + TEMPLATE[9]; case 10: /* * buildContextForTemplate chef_site-newSiteConfirm.vm * */ siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); siteType = (String) state.getAttribute(STATE_SITE_TYPE); if (siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); context.put("isProjectSite", Boolean.FALSE); if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) { context.put("selectedProviderCourse", state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN)); } if (state.getAttribute(STATE_CM_AUTHORIZER_SECTIONS) != null) { context.put("selectedAuthorizerCourse", state .getAttribute(STATE_CM_AUTHORIZER_SECTIONS)); } if (state.getAttribute(STATE_CM_REQUESTED_SECTIONS) != null) { context.put("selectedRequestedCourse", state .getAttribute(STATE_CM_REQUESTED_SECTIONS)); } if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { int number = ((Integer) state .getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)) .intValue(); context.put("manualAddNumber", new Integer(number - 1)); context.put("manualAddFields", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); } context.put("skins", state.getAttribute(STATE_ICONS)); if (StringUtil.trimToNull(siteInfo.getIconUrl()) != null) { context.put("selectedIcon", siteInfo.getIconUrl()); } } else { context.put("isCourseSite", Boolean.FALSE); if (siteType != null && siteType.equalsIgnoreCase("project")) { context.put("isProjectSite", Boolean.TRUE); } if (StringUtil.trimToNull(siteInfo.iconUrl) != null) { context.put("iconUrl", siteInfo.iconUrl); } } context.put("title", siteInfo.title); context.put("description", siteInfo.description); context.put("short_description", siteInfo.short_description); context.put("siteContactName", siteInfo.site_contact_name); context.put("siteContactEmail", siteInfo.site_contact_email); siteType = (String) state.getAttribute(STATE_SITE_TYPE); toolRegistrationSelectedList = (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); // String toolId's context.put(STATE_TOOL_REGISTRATION_LIST, state .getAttribute(STATE_TOOL_REGISTRATION_LIST)); // %%% use // Tool context.put("check_home", state .getAttribute(STATE_TOOL_HOME_SELECTED)); context .put("emailId", state .getAttribute(STATE_TOOL_EMAIL_ADDRESS)); context.put("serverName", ServerConfigurationService .getServerName()); context.put("include", new Boolean(siteInfo.include)); context.put("published", new Boolean(siteInfo.published)); context.put("joinable", new Boolean(siteInfo.joinable)); context.put("joinerRole", siteInfo.joinerRole); context.put("newsTitles", (Hashtable) state .getAttribute(STATE_NEWS_TITLES)); context.put("wcTitles", (Hashtable) state .getAttribute(STATE_WEB_CONTENT_TITLES)); // back to edit access page context.put("back", "18"); context.put("importSiteTools", state .getAttribute(STATE_IMPORT_SITE_TOOL)); context.put("siteService", SiteService.getInstance()); // those manual inputs context.put("form_requiredFields", sectionFieldProvider .getRequiredFields()); context.put("fieldValues", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); return (String) getContext(data).get("template") + TEMPLATE[10]; case 11: /* * buildContextForTemplate chef_site-newSitePublishUnpublish.vm * */ return (String) getContext(data).get("template") + TEMPLATE[11]; case 12: /* * buildContextForTemplate chef_site-siteInfo-list.vm * */ context.put("userDirectoryService", UserDirectoryService .getInstance()); try { siteProperties = site.getProperties(); siteType = site.getType(); if (siteType != null) { state.setAttribute(STATE_SITE_TYPE, siteType); } boolean isMyWorkspace = false; if (SiteService.isUserSite(site.getId())) { if (SiteService.getSiteUserId(site.getId()).equals( SessionManager.getCurrentSessionUserId())) { isMyWorkspace = true; context.put("siteUserId", SiteService .getSiteUserId(site.getId())); } } context.put("isMyWorkspace", Boolean.valueOf(isMyWorkspace)); String siteId = site.getId(); if (state.getAttribute(STATE_ICONS) != null) { List skins = (List) state.getAttribute(STATE_ICONS); for (int i = 0; i < skins.size(); i++) { MyIcon s = (MyIcon) skins.get(i); if (!StringUtil .different(s.getUrl(), site.getIconUrl())) { context.put("siteUnit", s.getName()); break; } } } context.put("siteIcon", site.getIconUrl()); context.put("siteTitle", site.getTitle()); context.put("siteDescription", site.getDescription()); context.put("siteJoinable", new Boolean(site.isJoinable())); if (site.isPublished()) { context.put("published", Boolean.TRUE); } else { context.put("published", Boolean.FALSE); context.put("owner", site.getCreatedBy().getSortName()); } Time creationTime = site.getCreatedTime(); if (creationTime != null) { context.put("siteCreationDate", creationTime .toStringLocalFull()); } boolean allowUpdateSite = SiteService.allowUpdateSite(siteId); context.put("allowUpdate", Boolean.valueOf(allowUpdateSite)); boolean allowUpdateGroupMembership = SiteService .allowUpdateGroupMembership(siteId); context.put("allowUpdateGroupMembership", Boolean .valueOf(allowUpdateGroupMembership)); boolean allowUpdateSiteMembership = SiteService .allowUpdateSiteMembership(siteId); context.put("allowUpdateSiteMembership", Boolean .valueOf(allowUpdateSiteMembership)); Menu b = new MenuImpl(portlet, data, (String) state .getAttribute(STATE_ACTION)); if (allowUpdateSite) { // top menu bar if (!isMyWorkspace) { b.add(new MenuEntry(rb.getString("java.editsite"), "doMenu_edit_site_info")); } b.add(new MenuEntry(rb.getString("java.edittools"), "doMenu_edit_site_tools")); } if (allowUpdateSiteMembership) { // show add participant menu if (!isMyWorkspace) { // show the Add Participant menu b.add(new MenuEntry(rb.getString("java.addp"), "doMenu_siteInfo_addParticipant")); } } if (allowUpdateGroupMembership) { // show Manage Groups menu if (!isMyWorkspace && (ServerConfigurationService .getString("wsetup.group.support") == "" || ServerConfigurationService .getString("wsetup.group.support") .equalsIgnoreCase(Boolean.TRUE.toString()))) { // show the group toolbar unless configured // to not support group b.add(new MenuEntry(rb.getString("java.group"), "doMenu_group")); } } if (allowUpdateSite) { if (!isMyWorkspace) { List gradToolsSiteTypes = (List) state .getAttribute(GRADTOOLS_SITE_TYPES); boolean isGradToolSite = false; if (siteType != null && gradToolsSiteTypes.contains(siteType)) { isGradToolSite = true; } if (siteType == null || siteType != null && !isGradToolSite) { // hide site access for GRADTOOLS // type of sites b.add(new MenuEntry( rb.getString("java.siteaccess"), "doMenu_edit_site_access")); } if (siteType != null && siteType.equals((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { b.add(new MenuEntry(rb.getString("java.editc"), "doMenu_siteInfo_editClass")); } if (siteType == null || siteType != null && !isGradToolSite) { // hide site duplicate and import // for GRADTOOLS type of sites if (SiteService.allowAddSite(null)) { b.add(new MenuEntry(rb.getString("java.duplicate"), "doMenu_siteInfo_duplicate")); } List updatableSites = SiteService .getSites( org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, null, null, null, SortType.TITLE_ASC, null); // import link should be visible even if only one // site if (updatableSites.size() > 0) { b.add(new MenuEntry( rb.getString("java.import"), "doMenu_siteInfo_import")); // a configuration param for // showing/hiding import // from file choice String importFromFile = ServerConfigurationService .getString("site.setup.import.file", Boolean.TRUE.toString()); if (importFromFile.equalsIgnoreCase("true")) { // htripath: June // 4th added as per // Kris and changed // desc of above b.add(new MenuEntry(rb .getString("java.importFile"), "doAttachmentsMtrlFrmFile")); } } } } // if the page order helper is available, not // stealthed and not hidden, show the link if (notStealthOrHiddenTool("sakai-site-pageorder-helper")) { b.add(new MenuEntry(rb.getString("java.orderpages"), "doPageOrderHelper")); } } if (b.size() > 0) { // add the menus to vm context.put("menu", b); } if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITESETUP)) { // editing from worksite setup tool context.put("fromWSetup", Boolean.TRUE); if (state.getAttribute(STATE_PREV_SITE) != null) { context.put("prevSite", state .getAttribute(STATE_PREV_SITE)); } if (state.getAttribute(STATE_NEXT_SITE) != null) { context.put("nextSite", state .getAttribute(STATE_NEXT_SITE)); } } else { context.put("fromWSetup", Boolean.FALSE); } // allow view roster? boolean allowViewRoster = SiteService.allowViewRoster(siteId); if (allowViewRoster) { context.put("viewRoster", Boolean.TRUE); } else { context.put("viewRoster", Boolean.FALSE); } // set participant list if (allowUpdateSite || allowViewRoster || allowUpdateSiteMembership) { Collection participantsCollection = getParticipantList(state); sortedBy = (String) state.getAttribute(SORTED_BY); sortedAsc = (String) state.getAttribute(SORTED_ASC); if (sortedBy == null) { state.setAttribute(SORTED_BY, SORTED_BY_PARTICIPANT_NAME); sortedBy = SORTED_BY_PARTICIPANT_NAME; } if (sortedAsc == null) { sortedAsc = Boolean.TRUE.toString(); state.setAttribute(SORTED_ASC, sortedAsc); } if (sortedBy != null) context.put("currentSortedBy", sortedBy); if (sortedAsc != null) context.put("currentSortAsc", sortedAsc); context.put("participantListSize", new Integer(participantsCollection.size())); context.put("participantList", prepPage(state)); pagingInfoToContext(state, context); } context.put("include", Boolean.valueOf(site.isPubView())); // site contact information String contactName = siteProperties .getProperty(PROP_SITE_CONTACT_NAME); String contactEmail = siteProperties .getProperty(PROP_SITE_CONTACT_EMAIL); if (contactName == null && contactEmail == null) { User u = site.getCreatedBy(); String email = u.getEmail(); if (email != null) { contactEmail = u.getEmail(); } contactName = u.getDisplayName(); } if (contactName != null) { context.put("contactName", contactName); } if (contactEmail != null) { context.put("contactEmail", contactEmail); } if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); coursesIntoContext(state, context, site); context.put("term", siteProperties .getProperty(PROP_SITE_TERM)); } else { context.put("isCourseSite", Boolean.FALSE); } } catch (Exception e) { M_log.warn(this + " site info list: " + e.toString()); } roles = getRoles(state); context.put("roles", roles); // will have the choice to active/inactive user or not String activeInactiveUser = ServerConfigurationService.getString( "activeInactiveUser", Boolean.FALSE.toString()); if (activeInactiveUser.equalsIgnoreCase("true")) { context.put("activeInactiveUser", Boolean.TRUE); // put realm object into context realmId = SiteService.siteReference(site.getId()); try { context.put("realm", AuthzGroupService .getAuthzGroup(realmId)); } catch (GroupNotDefinedException e) { M_log.warn(this + " IdUnusedException " + realmId); } } else { context.put("activeInactiveUser", Boolean.FALSE); } context.put("groupsWithMember", site .getGroupsWithMember(UserDirectoryService.getCurrentUser() .getId())); return (String) getContext(data).get("template") + TEMPLATE[12]; case 13: /* * buildContextForTemplate chef_site-siteInfo-editInfo.vm * */ siteProperties = site.getProperties(); context.put("title", state.getAttribute(FORM_SITEINFO_TITLE)); context.put("type", site.getType()); siteType = (String) state.getAttribute(STATE_SITE_TYPE); if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); context.put("skins", state.getAttribute(STATE_ICONS)); if (state.getAttribute(FORM_SITEINFO_SKIN) != null) { context.put("selectedIcon", state .getAttribute(FORM_SITEINFO_SKIN)); } else if (site.getIconUrl() != null) { context.put("selectedIcon", site.getIconUrl()); } setTermListForContext(context, state, true); // true->only future terms if (state.getAttribute(FORM_SITEINFO_TERM) == null) { String currentTerm = site.getProperties().getProperty( PROP_SITE_TERM); if (currentTerm != null) { state.setAttribute(FORM_SITEINFO_TERM, currentTerm); } } setSelectedTermForContext(context, state, FORM_SITEINFO_TERM); } else { context.put("isCourseSite", Boolean.FALSE); if (state.getAttribute(FORM_SITEINFO_ICON_URL) == null && StringUtil.trimToNull(site.getIconUrl()) != null) { state.setAttribute(FORM_SITEINFO_ICON_URL, site .getIconUrl()); } if (state.getAttribute(FORM_SITEINFO_ICON_URL) != null) { context.put("iconUrl", state .getAttribute(FORM_SITEINFO_ICON_URL)); } } context.put("description", state .getAttribute(FORM_SITEINFO_DESCRIPTION)); context.put("short_description", state .getAttribute(FORM_SITEINFO_SHORT_DESCRIPTION)); context.put("form_site_contact_name", state .getAttribute(FORM_SITEINFO_CONTACT_NAME)); context.put("form_site_contact_email", state .getAttribute(FORM_SITEINFO_CONTACT_EMAIL)); // Display of appearance icon/url list with course site based on // "disable.course.site.skin.selection" value set with // sakai.properties file. if ((ServerConfigurationService .getString("disable.course.site.skin.selection")) .equals("true")) { context.put("disableCourseSelection", Boolean.TRUE); } return (String) getContext(data).get("template") + TEMPLATE[13]; case 14: /* * buildContextForTemplate chef_site-siteInfo-editInfoConfirm.vm * */ siteProperties = site.getProperties(); siteType = (String) state.getAttribute(STATE_SITE_TYPE); if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); context.put("siteTerm", state.getAttribute(FORM_SITEINFO_TERM)); } else { context.put("isCourseSite", Boolean.FALSE); } context.put("oTitle", site.getTitle()); context.put("title", state.getAttribute(FORM_SITEINFO_TITLE)); context.put("description", state .getAttribute(FORM_SITEINFO_DESCRIPTION)); context.put("oDescription", site.getDescription()); context.put("short_description", state .getAttribute(FORM_SITEINFO_SHORT_DESCRIPTION)); context.put("oShort_description", site.getShortDescription()); context.put("skin", state.getAttribute(FORM_SITEINFO_SKIN)); context.put("oSkin", site.getIconUrl()); context.put("skins", state.getAttribute(STATE_ICONS)); context.put("oIcon", site.getIconUrl()); context.put("icon", state.getAttribute(FORM_SITEINFO_ICON_URL)); context.put("include", state.getAttribute(FORM_SITEINFO_INCLUDE)); context.put("oInclude", Boolean.valueOf(site.isPubView())); context.put("name", state.getAttribute(FORM_SITEINFO_CONTACT_NAME)); context.put("oName", siteProperties .getProperty(PROP_SITE_CONTACT_NAME)); context.put("email", state .getAttribute(FORM_SITEINFO_CONTACT_EMAIL)); context.put("oEmail", siteProperties .getProperty(PROP_SITE_CONTACT_EMAIL)); return (String) getContext(data).get("template") + TEMPLATE[14]; case 15: /* * buildContextForTemplate chef_site-addRemoveFeatureConfirm.vm * */ context.put("title", site.getTitle()); site_type = (String) state.getAttribute(STATE_SITE_TYPE); myworkspace_site = false; if (SiteService.isUserSite(site.getId())) { if (SiteService.getSiteUserId(site.getId()).equals( SessionManager.getCurrentSessionUserId())) { myworkspace_site = true; site_type = "myworkspace"; } } context.put(STATE_TOOL_REGISTRATION_LIST, state .getAttribute(STATE_TOOL_REGISTRATION_LIST)); context.put("check_home", state .getAttribute(STATE_TOOL_HOME_SELECTED)); context.put("selectedTools", orderToolIds(state, (String) state .getAttribute(STATE_SITE_TYPE), (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST))); context.put("oldSelectedTools", state .getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST)); context.put("oldSelectedHome", state .getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME)); context.put("continueIndex", "12"); if (state.getAttribute(STATE_TOOL_EMAIL_ADDRESS) != null) { context.put("emailId", state .getAttribute(STATE_TOOL_EMAIL_ADDRESS)); } context.put("serverName", ServerConfigurationService .getServerName()); context.put("newsTitles", (Hashtable) state .getAttribute(STATE_NEWS_TITLES)); context.put("wcTitles", (Hashtable) state .getAttribute(STATE_WEB_CONTENT_TITLES)); if (fromENWModifyView(state)) { context.put("back", "26"); } else { context.put("back", "4"); } return (String) getContext(data).get("template") + TEMPLATE[15]; case 16: /* * buildContextForTemplate chef_site-publishUnpublish-sendEmail.vm * */ context.put("title", site.getTitle()); context.put("willNotify", state.getAttribute(FORM_WILL_NOTIFY)); return (String) getContext(data).get("template") + TEMPLATE[16]; case 17: /* * buildContextForTemplate chef_site-publishUnpublish-confirm.vm * */ context.put("title", site.getTitle()); context.put("continueIndex", "12"); SiteInfo sInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); if (sInfo.getPublished()) { context.put("publish", Boolean.TRUE); context.put("backIndex", "16"); } else { context.put("publish", Boolean.FALSE); context.put("backIndex", "9"); } context.put("willNotify", state.getAttribute(FORM_WILL_NOTIFY)); return (String) getContext(data).get("template") + TEMPLATE[17]; case 18: /* * buildContextForTemplate chef_siteInfo-editAccess.vm * */ List publicChangeableSiteTypes = (List) state .getAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES); List unJoinableSiteTypes = (List) state .getAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE); if (site != null) { // editing existing site context.put("site", site); siteType = state.getAttribute(STATE_SITE_TYPE) != null ? (String) state .getAttribute(STATE_SITE_TYPE) : null; if (siteType != null && publicChangeableSiteTypes.contains(siteType)) { context.put("publicChangeable", Boolean.TRUE); } else { context.put("publicChangeable", Boolean.FALSE); } context.put("include", Boolean.valueOf(site.isPubView())); if (siteType != null && !unJoinableSiteTypes.contains(siteType)) { // site can be set as joinable context.put("disableJoinable", Boolean.FALSE); if (state.getAttribute(STATE_JOINABLE) == null) { state.setAttribute(STATE_JOINABLE, Boolean.valueOf(site .isJoinable())); } if (state.getAttribute(STATE_JOINERROLE) == null || state.getAttribute(STATE_JOINABLE) != null && ((Boolean) state.getAttribute(STATE_JOINABLE)) .booleanValue()) { state.setAttribute(STATE_JOINERROLE, site .getJoinerRole()); } if (state.getAttribute(STATE_JOINABLE) != null) { context.put("joinable", state .getAttribute(STATE_JOINABLE)); } if (state.getAttribute(STATE_JOINERROLE) != null) { context.put("joinerRole", state .getAttribute(STATE_JOINERROLE)); } } else { // site cannot be set as joinable context.put("disableJoinable", Boolean.TRUE); } context.put("roles", getRoles(state)); context.put("back", "12"); } else { siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); if (siteInfo.site_type != null && publicChangeableSiteTypes .contains(siteInfo.site_type)) { context.put("publicChangeable", Boolean.TRUE); } else { context.put("publicChangeable", Boolean.FALSE); } context.put("include", Boolean.valueOf(siteInfo.getInclude())); context.put("published", Boolean.valueOf(siteInfo .getPublished())); if (siteInfo.site_type != null && !unJoinableSiteTypes.contains(siteInfo.site_type)) { // site can be set as joinable context.put("disableJoinable", Boolean.FALSE); context.put("joinable", Boolean.valueOf(siteInfo.joinable)); context.put("joinerRole", siteInfo.joinerRole); } else { // site cannot be set as joinable context.put("disableJoinable", Boolean.TRUE); } // use the type's template, if defined String realmTemplate = "!site.template"; if (siteInfo.site_type != null) { realmTemplate = realmTemplate + "." + siteInfo.site_type; } try { AuthzGroup r = AuthzGroupService .getAuthzGroup(realmTemplate); context.put("roles", r.getRoles()); } catch (GroupNotDefinedException e) { try { AuthzGroup rr = AuthzGroupService .getAuthzGroup("!site.template"); context.put("roles", rr.getRoles()); } catch (GroupNotDefinedException ee) { } } // new site, go to confirmation page context.put("continue", "10"); if (fromENWModifyView(state)) { context.put("back", "26"); } else if (state.getAttribute(STATE_IMPORT) != null) { context.put("back", "27"); } else { context.put("back", "3"); } siteType = (String) state.getAttribute(STATE_SITE_TYPE); if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); context.put("isProjectSite", Boolean.FALSE); } else { context.put("isCourseSite", Boolean.FALSE); if (siteType.equalsIgnoreCase("project")) { context.put("isProjectSite", Boolean.TRUE); } } } return (String) getContext(data).get("template") + TEMPLATE[18]; case 19: /* * buildContextForTemplate chef_site-addParticipant-sameRole.vm * */ context.put("title", site.getTitle()); context.put("roles", getRoles(state)); context.put("participantList", state .getAttribute(STATE_ADD_PARTICIPANTS)); context.put("form_selectedRole", state .getAttribute("form_selectedRole")); return (String) getContext(data).get("template") + TEMPLATE[19]; case 20: /* * buildContextForTemplate chef_site-addParticipant-differentRole.vm * */ context.put("title", site.getTitle()); context.put("roles", getRoles(state)); context.put("selectedRoles", state .getAttribute(STATE_SELECTED_PARTICIPANT_ROLES)); context.put("participantList", state .getAttribute(STATE_ADD_PARTICIPANTS)); return (String) getContext(data).get("template") + TEMPLATE[20]; case 21: /* * buildContextForTemplate chef_site-addParticipant-notification.vm * */ context.put("title", site.getTitle()); context.put("sitePublished", Boolean.valueOf(site.isPublished())); if (state.getAttribute("form_selectedNotify") == null) { state.setAttribute("form_selectedNotify", Boolean.FALSE); } context.put("notify", state.getAttribute("form_selectedNotify")); boolean same_role = state.getAttribute("form_same_role") == null ? true : ((Boolean) state.getAttribute("form_same_role")) .booleanValue(); if (same_role) { context.put("backIndex", "19"); } else { context.put("backIndex", "20"); } return (String) getContext(data).get("template") + TEMPLATE[21]; case 22: /* * buildContextForTemplate chef_site-addParticipant-confirm.vm * */ context.put("title", site.getTitle()); context.put("participants", state .getAttribute(STATE_ADD_PARTICIPANTS)); context.put("notify", state.getAttribute("form_selectedNotify")); context.put("roles", getRoles(state)); context.put("same_role", state.getAttribute("form_same_role")); context.put("selectedRoles", state .getAttribute(STATE_SELECTED_PARTICIPANT_ROLES)); context .put("selectedRole", state .getAttribute("form_selectedRole")); return (String) getContext(data).get("template") + TEMPLATE[22]; case 23: /* * buildContextForTemplate chef_siteInfo-editAccess-globalAccess.vm * */ context.put("title", site.getTitle()); context.put("roles", getRoles(state)); if (state.getAttribute("form_joinable") == null) { state.setAttribute("form_joinable", new Boolean(site .isJoinable())); } context.put("form_joinable", state.getAttribute("form_joinable")); if (state.getAttribute("form_joinerRole") == null) { state.setAttribute("form_joinerRole", site.getJoinerRole()); } context.put("form_joinerRole", state .getAttribute("form_joinerRole")); return (String) getContext(data).get("template") + TEMPLATE[23]; case 24: /* * buildContextForTemplate * chef_siteInfo-editAccess-globalAccess-confirm.vm * */ context.put("title", site.getTitle()); context.put("form_joinable", state.getAttribute("form_joinable")); context.put("form_joinerRole", state .getAttribute("form_joinerRole")); return (String) getContext(data).get("template") + TEMPLATE[24]; case 25: /* * buildContextForTemplate chef_changeRoles-confirm.vm * */ Boolean sameRole = (Boolean) state .getAttribute(STATE_CHANGEROLE_SAMEROLE); context.put("sameRole", sameRole); if (sameRole.booleanValue()) { // same role context.put("currentRole", state .getAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE)); } else { context.put("selectedRoles", state .getAttribute(STATE_SELECTED_PARTICIPANT_ROLES)); } roles = getRoles(state); context.put("roles", roles); context.put("participantSelectedList", state .getAttribute(STATE_SELECTED_PARTICIPANTS)); if (state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES) != null) { context.put("selectedRoles", state .getAttribute(STATE_SELECTED_PARTICIPANT_ROLES)); } context.put("siteTitle", site.getTitle()); return (String) getContext(data).get("template") + TEMPLATE[25]; case 26: /* * buildContextForTemplate chef_site-modifyENW.vm * */ site_type = (String) state.getAttribute(STATE_SITE_TYPE); boolean existingSite = site != null ? true : false; if (existingSite) { // revising a existing site's tool context.put("existingSite", Boolean.TRUE); context.put("back", "4"); context.put("continue", "15"); context.put("function", "eventSubmit_doAdd_remove_features"); } else { // new site context.put("existingSite", Boolean.FALSE); context.put("function", "eventSubmit_doAdd_features"); if (state.getAttribute(STATE_IMPORT) != null) { context.put("back", "27"); } else { // new site, go to edit access page context.put("back", "3"); } context.put("continue", "18"); } context.put(STATE_TOOL_REGISTRATION_LIST, state .getAttribute(STATE_TOOL_REGISTRATION_LIST)); toolRegistrationSelectedList = (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); // String toolId's String emailId = (String) state .getAttribute(STATE_TOOL_EMAIL_ADDRESS); if (emailId != null) { context.put("emailId", emailId); } // titles for news tools newsTitles = (Hashtable) state.getAttribute(STATE_NEWS_TITLES); if (newsTitles == null) { newsTitles = new Hashtable(); newsTitles.put("sakai.news", NEWS_DEFAULT_TITLE); state.setAttribute(STATE_NEWS_TITLES, newsTitles); } context.put("newsTitles", newsTitles); // urls for news tools newsUrls = (Hashtable) state.getAttribute(STATE_NEWS_URLS); if (newsUrls == null) { newsUrls = new Hashtable(); newsUrls.put("sakai.news", NEWS_DEFAULT_URL); state.setAttribute(STATE_NEWS_URLS, newsUrls); } context.put("newsUrls", newsUrls); // titles for web content tools wcTitles = (Hashtable) state.getAttribute(STATE_WEB_CONTENT_TITLES); if (wcTitles == null) { wcTitles = new Hashtable(); wcTitles.put("sakai.iframe", WEB_CONTENT_DEFAULT_TITLE); state.setAttribute(STATE_WEB_CONTENT_TITLES, wcTitles); } context.put("wcTitles", wcTitles); // URLs for web content tools wcUrls = (Hashtable) state.getAttribute(STATE_WEB_CONTENT_URLS); if (wcUrls == null) { wcUrls = new Hashtable(); wcUrls.put("sakai.iframe", WEB_CONTENT_DEFAULT_URL); state.setAttribute(STATE_WEB_CONTENT_URLS, wcUrls); } context.put("wcUrls", wcUrls); context.put("serverName", ServerConfigurationService .getServerName()); context.put("oldSelectedTools", state .getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST)); return (String) getContext(data).get("template") + TEMPLATE[26]; case 27: /* * buildContextForTemplate chef_site-importSites.vm * */ existingSite = site != null ? true : false; site_type = (String) state.getAttribute(STATE_SITE_TYPE); if (existingSite) { // revising a existing site's tool context.put("continue", "12"); context.put("back", "28"); context.put("totalSteps", "2"); context.put("step", "2"); context.put("currentSite", site); } else { // new site, go to edit access page context.put("back", "3"); if (fromENWModifyView(state)) { context.put("continue", "26"); } else { context.put("continue", "18"); } } context.put(STATE_TOOL_REGISTRATION_LIST, state .getAttribute(STATE_TOOL_REGISTRATION_LIST)); context.put("selectedTools", orderToolIds(state, site_type, (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST))); // String toolId's context.put("importSites", state.getAttribute(STATE_IMPORT_SITES)); context.put("importSitesTools", state .getAttribute(STATE_IMPORT_SITE_TOOL)); context.put("check_home", state .getAttribute(STATE_TOOL_HOME_SELECTED)); context.put("importSupportedTools", importTools()); return (String) getContext(data).get("template") + TEMPLATE[27]; case 28: /* * buildContextForTemplate chef_siteinfo-import.vm * */ context.put("currentSite", site); context.put("importSiteList", state .getAttribute(STATE_IMPORT_SITES)); context.put("sites", SiteService.getSites( org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, null, null, null, SortType.TITLE_ASC, null)); return (String) getContext(data).get("template") + TEMPLATE[28]; case 29: /* * buildContextForTemplate chef_siteinfo-duplicate.vm * */ context.put("siteTitle", site.getTitle()); String sType = site.getType(); if (sType != null && sType.equals((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); context.put("currentTermId", site.getProperties().getProperty( PROP_SITE_TERM)); setTermListForContext(context, state, true); // true upcoming only } else { context.put("isCourseSite", Boolean.FALSE); } if (state.getAttribute(SITE_DUPLICATED) == null) { context.put("siteDuplicated", Boolean.FALSE); } else { context.put("siteDuplicated", Boolean.TRUE); context.put("duplicatedName", state .getAttribute(SITE_DUPLICATED_NAME)); } return (String) getContext(data).get("template") + TEMPLATE[29]; case 36: /* * buildContextForTemplate chef_site-newSiteCourse.vm */ // SAK-9824 Boolean enableCourseCreationForUser = ServerConfigurationService.getBoolean("site.enableCreateAnyUser", Boolean.FALSE); context.put("enableCourseCreationForUser", enableCourseCreationForUser); if (site != null) { context.put("site", site); context.put("siteTitle", site.getTitle()); setTermListForContext(context, state, true); // true -> upcoming only List providerCourseList = (List) state .getAttribute(SITE_PROVIDER_COURSE_LIST); coursesIntoContext(state, context, site); AcademicSession t = (AcademicSession) state .getAttribute(STATE_TERM_SELECTED); context.put("term", t); if (t != null) { String userId = UserDirectoryService.getCurrentUser().getEid(); List courses = prepareCourseAndSectionListing(userId, t .getEid(), state); if (courses != null && courses.size() > 0) { Vector notIncludedCourse = new Vector(); // remove included sites for (Iterator i = courses.iterator(); i.hasNext();) { CourseObject c = (CourseObject) i.next(); if (providerCourseList == null || providerCourseList != null && !providerCourseList.contains(c.getEid())) { notIncludedCourse.add(c); } } state.setAttribute(STATE_TERM_COURSE_LIST, notIncludedCourse); } else { state.removeAttribute(STATE_TERM_COURSE_LIST); } } // step number used in UI state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer("1")); } else { // need to include both list 'cos STATE_CM_AUTHORIZER_SECTIONS // contains sections that doens't belongs to current user and // STATE_ADD_CLASS_PROVIDER_CHOSEN contains section that does - // v2.4 daisyf if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null || state.getAttribute(STATE_CM_AUTHORIZER_SECTIONS) != null) { List<String> providerSectionList = (List<String>) state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN); if (providerSectionList != null) { /* List list1 = prepareSectionObject(providerSectionList, (String) state .getAttribute(STATE_CM_CURRENT_USERID)); */ context.put("selectedProviderCourse", providerSectionList); } List<SectionObject> authorizerSectionList = (List<SectionObject>) state .getAttribute(STATE_CM_AUTHORIZER_SECTIONS); if (authorizerSectionList != null) { List authorizerList = (List) state .getAttribute(STATE_CM_AUTHORIZER_LIST); //authorizerList is a list of SectionObject /* String userId = null; if (authorizerList != null) { userId = (String) authorizerList.get(0); } List list2 = prepareSectionObject( authorizerSectionList, userId); */ ArrayList list2 = new ArrayList(); for (int i=0; i<authorizerSectionList.size();i++){ SectionObject so = (SectionObject)authorizerSectionList.get(i); list2.add(so.getEid()); } context.put("selectedAuthorizerCourse", list2); } } if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { context.put("selectedManualCourse", Boolean.TRUE); } context.put("term", (AcademicSession) state .getAttribute(STATE_TERM_SELECTED)); context.put("currentUserId", (String) state .getAttribute(STATE_CM_CURRENT_USERID)); context.put("form_additional", (String) state .getAttribute(FORM_ADDITIONAL)); context.put("authorizers", getAuthorizers(state)); } if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITESETUP)) { context.put("backIndex", "1"); } else if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITEINFO)) { context.put("backIndex", ""); } List ll = (List) state.getAttribute(STATE_TERM_COURSE_LIST); context.put("termCourseList", state .getAttribute(STATE_TERM_COURSE_LIST)); // added for 2.4 -daisyf context.put("campusDirectory", getCampusDirectory()); context.put("userId", (String) state .getAttribute(STATE_INSTRUCTOR_SELECTED)); /* * for measuring how long it takes to load sections java.util.Date * date = new java.util.Date(); M_log.debug("***2. finish at: * "+date); M_log.debug("***3. userId:"+(String) state * .getAttribute(STATE_INSTRUCTOR_SELECTED)); */ return (String) getContext(data).get("template") + TEMPLATE[36]; case 37: /* * buildContextForTemplate chef_site-newSiteCourseManual.vm */ if (site != null) { context.put("site", site); context.put("siteTitle", site.getTitle()); coursesIntoContext(state, context, site); } buildInstructorSectionsList(state, params, context); context.put("form_requiredFields", sectionFieldProvider .getRequiredFields()); context.put("form_additional", siteInfo.additional); context.put("form_title", siteInfo.title); context.put("form_description", siteInfo.description); context.put("officialAccountName", ServerConfigurationService .getString("officialAccountName", "")); context.put("value_uniqname", state .getAttribute(STATE_SITE_QUEST_UNIQNAME)); int number = 1; if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { number = ((Integer) state .getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)) .intValue(); context.put("currentNumber", new Integer(number)); } context.put("currentNumber", new Integer(number)); context.put("listSize", new Integer(number - 1)); context.put("fieldValues", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) { List l = (List) state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN); context.put("selectedProviderCourse", l); context.put("size", new Integer(l.size() - 1)); } if (state.getAttribute(STATE_CM_REQUESTED_SECTIONS) != null) { List l = (List) state .getAttribute(STATE_CM_REQUESTED_SECTIONS); context.put("cmRequestedSections", l); } if (state.getAttribute(STATE_SITE_MODE).equals(SITE_MODE_SITEINFO)) { context.put("editSite", Boolean.TRUE); context.put("cmSelectedSections", state.getAttribute(STATE_CM_SELECTED_SECTIONS)); } if (site == null) { // v2.4 - added & modified by daisyf if (courseManagementIsImplemented() && state.getAttribute(STATE_TERM_COURSE_LIST) != null) { // back to the list view of sections context.put("back", "36"); } else { context.put("back", "1"); } if (state.getAttribute(STATE_AUTO_ADD) != null) { context.put("autoAdd", Boolean.TRUE); // context.put("back", "36"); } } else { // editing site context.put("back", "36"); } isFutureTermSelected(state); context.put("isFutureTerm", state .getAttribute(STATE_FUTURE_TERM_SELECTED)); context.put("weeksAhead", ServerConfigurationService.getString( "roster.available.weeks.before.term.start", "0")); return (String) getContext(data).get("template") + TEMPLATE[37]; case 42: /* * buildContextForTemplate chef_site-gradtoolsConfirm.vm * */ siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); context.put("title", siteInfo.title); context.put("description", siteInfo.description); context.put("short_description", siteInfo.short_description); toolRegistrationList = (Vector) state .getAttribute(STATE_PROJECT_TOOL_LIST); toolRegistrationSelectedList = (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); // String toolId's context.put(STATE_TOOL_REGISTRATION_LIST, toolRegistrationList); // %%% // use // Tool context.put("check_home", state .getAttribute(STATE_TOOL_HOME_SELECTED)); context .put("emailId", state .getAttribute(STATE_TOOL_EMAIL_ADDRESS)); context.put("serverName", ServerConfigurationService .getServerName()); context.put("include", new Boolean(siteInfo.include)); return (String) getContext(data).get("template") + TEMPLATE[42]; case 43: /* * buildContextForTemplate chef_siteInfo-editClass.vm * */ bar = new MenuImpl(portlet, data, (String) state .getAttribute(STATE_ACTION)); if (SiteService.allowAddSite(null)) { bar.add(new MenuEntry(rb.getString("java.addclasses"), "doMenu_siteInfo_addClass")); } context.put("menu", bar); context.put("siteTitle", site.getTitle()); coursesIntoContext(state, context, site); return (String) getContext(data).get("template") + TEMPLATE[43]; case 44: /* * buildContextForTemplate chef_siteInfo-addCourseConfirm.vm * */ context.put("siteTitle", site.getTitle()); coursesIntoContext(state, context, site); context.put("providerAddCourses", state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN)); if (state.getAttribute(STATE_CM_SELECTED_SECTIONS) != null) { context.put("cmSelectedSections", state.getAttribute(STATE_CM_SELECTED_SECTIONS)); } if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { int addNumber = ((Integer) state .getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)) .intValue() - 1; context.put("manualAddNumber", new Integer(addNumber)); context.put("requestFields", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); context.put("backIndex", "37"); } else { context.put("backIndex", "36"); } // those manual inputs context.put("form_requiredFields", sectionFieldProvider .getRequiredFields()); context.put("fieldValues", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); return (String) getContext(data).get("template") + TEMPLATE[44]; // htripath - import materials from classic case 45: /* * buildContextForTemplate chef_siteInfo-importMtrlMaster.vm * */ return (String) getContext(data).get("template") + TEMPLATE[45]; case 46: /* * buildContextForTemplate chef_siteInfo-importMtrlCopy.vm * */ // this is for list display in listbox context .put("allZipSites", state .getAttribute(ALL_ZIP_IMPORT_SITES)); context.put("finalZipSites", state .getAttribute(FINAL_ZIP_IMPORT_SITES)); // zip file // context.put("zipreffile",state.getAttribute(CLASSIC_ZIP_FILE_NAME)); return (String) getContext(data).get("template") + TEMPLATE[46]; case 47: /* * buildContextForTemplate chef_siteInfo-importMtrlCopyConfirm.vm * */ context.put("finalZipSites", state .getAttribute(FINAL_ZIP_IMPORT_SITES)); return (String) getContext(data).get("template") + TEMPLATE[47]; case 48: /* * buildContextForTemplate chef_siteInfo-importMtrlCopyConfirm.vm * */ context.put("finalZipSites", state .getAttribute(FINAL_ZIP_IMPORT_SITES)); return (String) getContext(data).get("template") + TEMPLATE[48]; case 49: /* * buildContextForTemplate chef_siteInfo-group.vm * */ context.put("site", site); bar = new MenuImpl(portlet, data, (String) state .getAttribute(STATE_ACTION)); if (SiteService.allowUpdateSite(site.getId()) || SiteService.allowUpdateGroupMembership(site.getId())) { bar.add(new MenuEntry(rb.getString("java.newgroup"), "doGroup_new")); } context.put("menu", bar); // the group list sortedBy = (String) state.getAttribute(SORTED_BY); sortedAsc = (String) state.getAttribute(SORTED_ASC); if (sortedBy != null) context.put("currentSortedBy", sortedBy); if (sortedAsc != null) context.put("currentSortAsc", sortedAsc); // only show groups created by WSetup tool itself Collection groups = (Collection) site.getGroups(); List groupsByWSetup = new Vector(); for (Iterator gIterator = groups.iterator(); gIterator.hasNext();) { Group gNext = (Group) gIterator.next(); String gProp = gNext.getProperties().getProperty( GROUP_PROP_WSETUP_CREATED); if (gProp != null && gProp.equals(Boolean.TRUE.toString())) { groupsByWSetup.add(gNext); } } if (sortedBy != null && sortedAsc != null) { context.put("groups", new SortedIterator(groupsByWSetup .iterator(), new SiteComparator(sortedBy, sortedAsc))); } return (String) getContext(data).get("template") + TEMPLATE[49]; case 50: /* * buildContextForTemplate chef_siteInfo-groupedit.vm * */ Group g = getStateGroup(state); if (g != null) { context.put("group", g); context.put("newgroup", Boolean.FALSE); } else { context.put("newgroup", Boolean.TRUE); } if (state.getAttribute(STATE_GROUP_TITLE) != null) { context.put("title", state.getAttribute(STATE_GROUP_TITLE)); } if (state.getAttribute(STATE_GROUP_DESCRIPTION) != null) { context.put("description", state .getAttribute(STATE_GROUP_DESCRIPTION)); } Iterator siteMembers = new SortedIterator(getParticipantList(state) .iterator(), new SiteComparator(SORTED_BY_PARTICIPANT_NAME, Boolean.TRUE.toString())); if (siteMembers != null && siteMembers.hasNext()) { context.put("generalMembers", siteMembers); } Set groupMembersSet = (Set) state.getAttribute(STATE_GROUP_MEMBERS); if (state.getAttribute(STATE_GROUP_MEMBERS) != null) { context.put("groupMembers", new SortedIterator(groupMembersSet .iterator(), new SiteComparator(SORTED_BY_MEMBER_NAME, Boolean.TRUE.toString()))); } context.put("groupMembersClone", groupMembersSet); context.put("userDirectoryService", UserDirectoryService .getInstance()); return (String) getContext(data).get("template") + TEMPLATE[50]; case 51: /* * buildContextForTemplate chef_siteInfo-groupDeleteConfirm.vm * */ context.put("site", site); context .put("removeGroupIds", new ArrayList(Arrays .asList((String[]) state .getAttribute(STATE_GROUP_REMOVE)))); return (String) getContext(data).get("template") + TEMPLATE[51]; case 53: { /* * build context for chef_site-findCourse.vm */ AcademicSession t = (AcademicSession) state .getAttribute(STATE_TERM_SELECTED); List cmLevels = (List) state.getAttribute(STATE_CM_LEVELS), selections = (List) state .getAttribute(STATE_CM_LEVEL_SELECTIONS); if (cmLevels == null) { cmLevels = getCMLevelLabels(); } SectionObject selectedSect = (SectionObject) state .getAttribute(STATE_CM_SELECTED_SECTION); List<SectionObject> requestedSections = (List<SectionObject>) state .getAttribute(STATE_CM_REQUESTED_SECTIONS); if (courseManagementIsImplemented() && cms != null) { context.put("cmsAvailable", new Boolean(true)); } if (cms == null || !courseManagementIsImplemented() || cmLevels == null || cmLevels.size() < 1) { // TODO: redirect to manual entry: case #37 } else { Object levelOpts[] = new Object[cmLevels.size()]; int numSelections = 0; if (selections != null) numSelections = selections.size(); // populate options for dropdown lists switch (numSelections) { /* * execution will fall through these statements based on number * of selections already made */ case 3: // intentionally blank case 2: levelOpts[2] = getCMSections((String) selections.get(1)); case 1: levelOpts[1] = getCMCourseOfferings((String) selections .get(0), t.getEid()); default: levelOpts[0] = getCMSubjects(); } context.put("cmLevelOptions", Arrays.asList(levelOpts)); } if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) { context.put("selectedProviderCourse", state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN)); } if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { int courseInd = ((Integer) state .getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)) .intValue(); context.put("manualAddNumber", new Integer(courseInd - 1)); context.put("manualAddFields", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); } context.put("term", (AcademicSession) state .getAttribute(STATE_TERM_SELECTED)); context.put("cmLevels", cmLevels); context.put("cmLevelSelections", selections); context.put("selectedCourse", selectedSect); context.put("cmRequestedSections", requestedSections); if (state.getAttribute(STATE_SITE_MODE).equals(SITE_MODE_SITEINFO)) { context.put("editSite", Boolean.TRUE); context.put("cmSelectedSections", state.getAttribute(STATE_CM_SELECTED_SECTIONS)); } if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITESETUP)) { if (state.getAttribute(STATE_TERM_COURSE_LIST) != null) { context.put("backIndex", "36"); } else { context.put("backIndex", "1"); } } else if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITEINFO)) { context.put("backIndex", "36"); } return (String) getContext(data).get("template") + TEMPLATE[53]; } } // should never be reached return (String) getContext(data).get("template") + TEMPLATE[0]; } // buildContextForTemplate
private String buildContextForTemplate(int index, VelocityPortlet portlet, Context context, RunData data, SessionState state) { String realmId = ""; String site_type = ""; String sortedBy = ""; String sortedAsc = ""; ParameterParser params = data.getParameters(); context.put("tlang", rb); context.put("alertMessage", state.getAttribute(STATE_MESSAGE)); // If cleanState() has removed SiteInfo, get a new instance into state SiteInfo siteInfo = new SiteInfo(); if (state.getAttribute(STATE_SITE_INFO) != null) { siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); } else { state.setAttribute(STATE_SITE_INFO, siteInfo); } // Lists used in more than one template // Access List roles = new Vector(); // the hashtables for News and Web Content tools Hashtable newsTitles = new Hashtable(); Hashtable newsUrls = new Hashtable(); Hashtable wcTitles = new Hashtable(); Hashtable wcUrls = new Hashtable(); List toolRegistrationList = new Vector(); List toolRegistrationSelectedList = new Vector(); ResourceProperties siteProperties = null; // for showing site creation steps if (state.getAttribute(SITE_CREATE_TOTAL_STEPS) != null) { context.put("totalSteps", state .getAttribute(SITE_CREATE_TOTAL_STEPS)); } if (state.getAttribute(SITE_CREATE_CURRENT_STEP) != null) { context.put("step", state.getAttribute(SITE_CREATE_CURRENT_STEP)); } String hasGradSites = ServerConfigurationService.getString( "withDissertation", Boolean.FALSE.toString()); context.put("cms", cms); // course site type context.put("courseSiteType", state.getAttribute(STATE_COURSE_SITE_TYPE)); Site site = getStateSite(state); switch (index) { case 0: /* * buildContextForTemplate chef_site-list.vm * */ // site types List sTypes = (List) state.getAttribute(STATE_SITE_TYPES); // make sure auto-updates are enabled Hashtable views = new Hashtable(); if (SecurityService.isSuperUser()) { views.put(rb.getString("java.allmy"), rb .getString("java.allmy")); views.put(rb.getString("java.my") + " " + rb.getString("java.sites"), rb.getString("java.my")); for (int sTypeIndex = 0; sTypeIndex < sTypes.size(); sTypeIndex++) { String type = (String) sTypes.get(sTypeIndex); views.put(type + " " + rb.getString("java.sites"), type); } if (hasGradSites.equalsIgnoreCase("true")) { views.put(rb.getString("java.gradtools") + " " + rb.getString("java.sites"), rb .getString("java.gradtools")); } if (state.getAttribute(STATE_VIEW_SELECTED) == null) { state.setAttribute(STATE_VIEW_SELECTED, rb .getString("java.allmy")); } context.put("superUser", Boolean.TRUE); } else { context.put("superUser", Boolean.FALSE); views.put(rb.getString("java.allmy"), rb .getString("java.allmy")); // if there is a GradToolsStudent choice inside boolean remove = false; if (hasGradSites.equalsIgnoreCase("true")) { try { // the Grad Tools site option is only presented to // GradTools Candidates String userId = StringUtil.trimToZero(SessionManager .getCurrentSessionUserId()); // am I a grad student? if (!isGradToolsCandidate(userId)) { // not a gradstudent remove = true; } } catch (Exception e) { remove = true; } } else { // not support for dissertation sites remove = true; } // do not show this site type in views // sTypes.remove(new String(SITE_TYPE_GRADTOOLS_STUDENT)); for (int sTypeIndex = 0; sTypeIndex < sTypes.size(); sTypeIndex++) { String type = (String) sTypes.get(sTypeIndex); if (!type.equals(SITE_TYPE_GRADTOOLS_STUDENT)) { views .put(type + " " + rb.getString("java.sites"), type); } } if (!remove) { views.put(rb.getString("java.gradtools") + " " + rb.getString("java.sites"), rb .getString("java.gradtools")); } // default view if (state.getAttribute(STATE_VIEW_SELECTED) == null) { state.setAttribute(STATE_VIEW_SELECTED, rb .getString("java.allmy")); } } context.put("views", views); if (state.getAttribute(STATE_VIEW_SELECTED) != null) { context.put("viewSelected", (String) state .getAttribute(STATE_VIEW_SELECTED)); } String search = (String) state.getAttribute(STATE_SEARCH); context.put("search_term", search); sortedBy = (String) state.getAttribute(SORTED_BY); if (sortedBy == null) { state.setAttribute(SORTED_BY, SortType.TITLE_ASC.toString()); sortedBy = SortType.TITLE_ASC.toString(); } sortedAsc = (String) state.getAttribute(SORTED_ASC); if (sortedAsc == null) { sortedAsc = Boolean.TRUE.toString(); state.setAttribute(SORTED_ASC, sortedAsc); } if (sortedBy != null) context.put("currentSortedBy", sortedBy); if (sortedAsc != null) context.put("currentSortAsc", sortedAsc); String portalUrl = ServerConfigurationService.getPortalUrl(); context.put("portalUrl", portalUrl); List sites = prepPage(state); state.setAttribute(STATE_SITES, sites); context.put("sites", sites); context.put("totalPageNumber", new Integer(totalPageNumber(state))); context.put("searchString", state.getAttribute(STATE_SEARCH)); context.put("form_search", FORM_SEARCH); context.put("formPageNumber", FORM_PAGE_NUMBER); context.put("prev_page_exists", state .getAttribute(STATE_PREV_PAGE_EXISTS)); context.put("next_page_exists", state .getAttribute(STATE_NEXT_PAGE_EXISTS)); context.put("current_page", state.getAttribute(STATE_CURRENT_PAGE)); // put the service in the context (used for allow update calls on // each site) context.put("service", SiteService.getInstance()); context.put("sortby_title", SortType.TITLE_ASC.toString()); context.put("sortby_type", SortType.TYPE_ASC.toString()); context.put("sortby_createdby", SortType.CREATED_BY_ASC.toString()); context.put("sortby_publish", SortType.PUBLISHED_ASC.toString()); context.put("sortby_createdon", SortType.CREATED_ON_ASC.toString()); // top menu bar Menu bar = new MenuImpl(portlet, data, (String) state .getAttribute(STATE_ACTION)); if (SiteService.allowAddSite(null)) { bar.add(new MenuEntry(rb.getString("java.new"), "doNew_site")); } bar.add(new MenuEntry(rb.getString("java.revise"), null, true, MenuItem.CHECKED_NA, "doGet_site", "sitesForm")); bar.add(new MenuEntry(rb.getString("java.delete"), null, true, MenuItem.CHECKED_NA, "doMenu_site_delete", "sitesForm")); context.put("menu", bar); // default to be no pageing context.put("paged", Boolean.FALSE); Menu bar2 = new MenuImpl(portlet, data, (String) state .getAttribute(STATE_ACTION)); // add the search commands addSearchMenus(bar2, state); context.put("menu2", bar2); pagingInfoToContext(state, context); return (String) getContext(data).get("template") + TEMPLATE[0]; case 1: /* * buildContextForTemplate chef_site-type.vm * */ if (hasGradSites.equalsIgnoreCase("true")) { context.put("withDissertation", Boolean.TRUE); try { // the Grad Tools site option is only presented to UM grad // students String userId = StringUtil.trimToZero(SessionManager .getCurrentSessionUserId()); // am I a UM grad student? Boolean isGradStudent = new Boolean( isGradToolsCandidate(userId)); context.put("isGradStudent", isGradStudent); // if I am a UM grad student, do I already have a Grad Tools // site? boolean noGradToolsSite = true; if (hasGradToolsStudentSite(userId)) noGradToolsSite = false; context .put("noGradToolsSite", new Boolean(noGradToolsSite)); } catch (Exception e) { if (Log.isWarnEnabled()) { M_log.warn("buildContextForTemplate chef_site-type.vm " + e); } } } else { context.put("withDissertation", Boolean.FALSE); } List types = (List) state.getAttribute(STATE_SITE_TYPES); context.put("siteTypes", types); // put selected/default site type into context if (siteInfo.site_type != null && siteInfo.site_type.length() > 0) { context.put("typeSelected", siteInfo.site_type); } else if (types.size() > 0) { context.put("typeSelected", types.get(0)); } setTermListForContext(context, state, true); // true => only // upcoming terms setSelectedTermForContext(context, state, STATE_TERM_SELECTED); return (String) getContext(data).get("template") + TEMPLATE[1]; case 2: /* * buildContextForTemplate chef_site-newSiteInformation.vm * */ context.put("siteTypes", state.getAttribute(STATE_SITE_TYPES)); String siteType = (String) state.getAttribute(STATE_SITE_TYPE); context.put("type", siteType); if (siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); context.put("isProjectSite", Boolean.FALSE); if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) { context.put("selectedProviderCourse", state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN)); } List<SectionObject> cmRequestedList = (List<SectionObject>) state .getAttribute(STATE_CM_REQUESTED_SECTIONS); if (cmRequestedList != null) { context.put("cmRequestedSections", cmRequestedList); context.put("back", "53"); } List<SectionObject> cmAuthorizerSectionList = (List<SectionObject>) state .getAttribute(STATE_CM_AUTHORIZER_SECTIONS); if (cmAuthorizerSectionList != null) { context .put("cmAuthorizerSections", cmAuthorizerSectionList); context.put("back", "36"); } if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { int number = ((Integer) state .getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)) .intValue(); context.put("manualAddNumber", new Integer(number - 1)); context.put("manualAddFields", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); context.put("back", "37"); } else { if (courseManagementIsImplemented()) { context.put("back", "36"); } else { context.put("back", "0"); context.put("template-index", "37"); } } context.put("skins", state.getAttribute(STATE_ICONS)); if (StringUtil.trimToNull(siteInfo.getIconUrl()) != null) { context.put("selectedIcon", siteInfo.getIconUrl()); } } else { context.put("isCourseSite", Boolean.FALSE); if (siteType.equalsIgnoreCase("project")) { context.put("isProjectSite", Boolean.TRUE); } if (StringUtil.trimToNull(siteInfo.iconUrl) != null) { context.put(FORM_ICON_URL, siteInfo.iconUrl); } context.put("back", "1"); } context.put(FORM_TITLE, siteInfo.title); context.put(FORM_SHORT_DESCRIPTION, siteInfo.short_description); context.put(FORM_DESCRIPTION, siteInfo.description); // defalt the site contact person to the site creator if (siteInfo.site_contact_name.equals(NULL_STRING) && siteInfo.site_contact_email.equals(NULL_STRING)) { User user = UserDirectoryService.getCurrentUser(); siteInfo.site_contact_name = user.getDisplayName(); siteInfo.site_contact_email = user.getEmail(); } context.put("form_site_contact_name", siteInfo.site_contact_name); context.put("form_site_contact_email", siteInfo.site_contact_email); // those manual inputs context.put("form_requiredFields", sectionFieldProvider .getRequiredFields()); context.put("fieldValues", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); return (String) getContext(data).get("template") + TEMPLATE[2]; case 3: /* * buildContextForTemplate chef_site-newSiteFeatures.vm * */ siteType = (String) state.getAttribute(STATE_SITE_TYPE); if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); context.put("isProjectSite", Boolean.FALSE); } else { context.put("isCourseSite", Boolean.FALSE); if (siteType.equalsIgnoreCase("project")) { context.put("isProjectSite", Boolean.TRUE); } } context.put("defaultTools", ServerConfigurationService .getToolsRequired(siteType)); toolRegistrationSelectedList = (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); // If this is the first time through, check for tools // which should be selected by default. List defaultSelectedTools = ServerConfigurationService .getDefaultTools(siteType); if (toolRegistrationSelectedList == null) { toolRegistrationSelectedList = new Vector(defaultSelectedTools); } context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); // String toolId's context.put(STATE_TOOL_REGISTRATION_LIST, state .getAttribute(STATE_TOOL_REGISTRATION_LIST)); // %%% use // ToolRegistrations // for // template // list context .put("emailId", state .getAttribute(STATE_TOOL_EMAIL_ADDRESS)); context.put("serverName", ServerConfigurationService .getServerName()); // The "Home" tool checkbox needs special treatment to be selected // by // default. Boolean checkHome = (Boolean) state .getAttribute(STATE_TOOL_HOME_SELECTED); if (checkHome == null) { if ((defaultSelectedTools != null) && defaultSelectedTools.contains(HOME_TOOL_ID)) { checkHome = Boolean.TRUE; } } context.put("check_home", checkHome); // titles for news tools context.put("newsTitles", state.getAttribute(STATE_NEWS_TITLES)); // titles for web content tools context.put("wcTitles", state .getAttribute(STATE_WEB_CONTENT_TITLES)); // urls for news tools context.put("newsUrls", state.getAttribute(STATE_NEWS_URLS)); // urls for web content tools context.put("wcUrls", state.getAttribute(STATE_WEB_CONTENT_URLS)); context.put("sites", SiteService.getSites( org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, null, null, null, SortType.TITLE_ASC, null)); context.put("import", state.getAttribute(STATE_IMPORT)); context.put("importSites", state.getAttribute(STATE_IMPORT_SITES)); return (String) getContext(data).get("template") + TEMPLATE[3]; case 4: /* * buildContextForTemplate chef_site-addRemoveFeatures.vm * */ context.put("SiteTitle", site.getTitle()); String type = (String) state.getAttribute(STATE_SITE_TYPE); context.put("defaultTools", ServerConfigurationService .getToolsRequired(type)); boolean myworkspace_site = false; // Put up tool lists filtered by category List siteTypes = (List) state.getAttribute(STATE_SITE_TYPES); if (siteTypes.contains(type)) { myworkspace_site = false; } if (SiteService.isUserSite(site.getId()) || (type != null && type.equalsIgnoreCase("myworkspace"))) { myworkspace_site = true; type = "myworkspace"; } context.put("myworkspace_site", new Boolean(myworkspace_site)); context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST)); // titles for news tools context.put("newsTitles", state.getAttribute(STATE_NEWS_TITLES)); // titles for web content tools context.put("wcTitles", state .getAttribute(STATE_WEB_CONTENT_TITLES)); // urls for news tools context.put("newsUrls", state.getAttribute(STATE_NEWS_URLS)); // urls for web content tools context.put("wcUrls", state.getAttribute(STATE_WEB_CONTENT_URLS)); context.put(STATE_TOOL_REGISTRATION_LIST, state .getAttribute(STATE_TOOL_REGISTRATION_LIST)); context.put("check_home", state .getAttribute(STATE_TOOL_HOME_SELECTED)); // get the email alias when an Email Archive tool has been selected String channelReference = mailArchiveChannelReference(site.getId()); List aliases = AliasService.getAliases(channelReference, 1, 1); if (aliases.size() > 0) { state.setAttribute(STATE_TOOL_EMAIL_ADDRESS, ((Alias) aliases .get(0)).getId()); } else { state.removeAttribute(STATE_TOOL_EMAIL_ADDRESS); } if (state.getAttribute(STATE_TOOL_EMAIL_ADDRESS) != null) { context.put("emailId", state .getAttribute(STATE_TOOL_EMAIL_ADDRESS)); } context.put("serverName", ServerConfigurationService .getServerName()); context.put("backIndex", "12"); return (String) getContext(data).get("template") + TEMPLATE[4]; case 5: /* * buildContextForTemplate chef_site-addParticipant.vm * */ context.put("title", site.getTitle()); roles = getRoles(state); context.put("roles", roles); // Note that (for now) these strings are in both sakai.properties // and sitesetupgeneric.properties context.put("officialAccountSectionTitle", ServerConfigurationService .getString("officialAccountSectionTitle")); context.put("officialAccountName", ServerConfigurationService .getString("officialAccountName")); context.put("officialAccountLabel", ServerConfigurationService .getString("officialAccountLabel")); context.put("nonOfficialAccountSectionTitle", ServerConfigurationService .getString("nonOfficialAccountSectionTitle")); context.put("nonOfficialAccountName", ServerConfigurationService .getString("nonOfficialAccountName")); context.put("nonOfficialAccountLabel", ServerConfigurationService .getString("nonOfficialAccountLabel")); if (state.getAttribute("officialAccountValue") != null) { context.put("officialAccountValue", (String) state .getAttribute("officialAccountValue")); } if (state.getAttribute("nonOfficialAccountValue") != null) { context.put("nonOfficialAccountValue", (String) state .getAttribute("nonOfficialAccountValue")); } if (state.getAttribute("form_same_role") != null) { context.put("form_same_role", ((Boolean) state .getAttribute("form_same_role")).toString()); } else { context.put("form_same_role", Boolean.TRUE.toString()); } context.put("backIndex", "12"); return (String) getContext(data).get("template") + TEMPLATE[5]; case 6: /* * buildContextForTemplate chef_site-removeParticipants.vm * */ context.put("title", site.getTitle()); realmId = SiteService.siteReference(site.getId()); try { AuthzGroup realm = AuthzGroupService.getAuthzGroup(realmId); try { List removeableList = (List) state .getAttribute(STATE_REMOVEABLE_USER_LIST); List removeableParticipants = new Vector(); for (int k = 0; k < removeableList.size(); k++) { User user = UserDirectoryService .getUser((String) removeableList.get(k)); Participant participant = new Participant(); participant.name = user.getSortName(); participant.uniqname = user.getId(); Role r = realm.getUserRole(user.getId()); if (r != null) { participant.role = r.getId(); } removeableParticipants.add(participant); } context.put("removeableList", removeableParticipants); } catch (UserNotDefinedException ee) { } } catch (GroupNotDefinedException e) { } context.put("backIndex", "18"); return (String) getContext(data).get("template") + TEMPLATE[6]; case 7: /* * buildContextForTemplate chef_site-changeRoles.vm * */ context.put("same_role", state .getAttribute(STATE_CHANGEROLE_SAMEROLE)); roles = getRoles(state); context.put("roles", roles); context.put("currentRole", state .getAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE)); context.put("participantSelectedList", state .getAttribute(STATE_SELECTED_PARTICIPANTS)); context.put("selectedRoles", state .getAttribute(STATE_SELECTED_PARTICIPANT_ROLES)); context.put("siteTitle", site.getTitle()); return (String) getContext(data).get("template") + TEMPLATE[7]; case 8: /* * buildContextForTemplate chef_site-siteDeleteConfirm.vm * */ String site_title = NULL_STRING; String[] removals = (String[]) state .getAttribute(STATE_SITE_REMOVALS); List remove = new Vector(); String user = SessionManager.getCurrentSessionUserId(); String workspace = SiteService.getUserSiteId(user); if (removals != null && removals.length != 0) { for (int i = 0; i < removals.length; i++) { String id = (String) removals[i]; if (!(id.equals(workspace))) { try { site_title = SiteService.getSite(id).getTitle(); } catch (IdUnusedException e) { M_log .warn("SiteAction.doSite_delete_confirmed - IdUnusedException " + id); addAlert(state, rb.getString("java.sitewith") + " " + id + " " + rb.getString("java.couldnt") + " "); } if (SiteService.allowRemoveSite(id)) { try { Site removeSite = SiteService.getSite(id); remove.add(removeSite); } catch (IdUnusedException e) { M_log .warn("SiteAction.buildContextForTemplate chef_site-siteDeleteConfirm.vm: IdUnusedException"); } } else { addAlert(state, site_title + " " + rb.getString("java.couldntdel") + " "); } } else { addAlert(state, rb.getString("java.yourwork")); } } if (remove.size() == 0) { addAlert(state, rb.getString("java.click")); } } context.put("removals", remove); return (String) getContext(data).get("template") + TEMPLATE[8]; case 9: /* * buildContextForTemplate chef_site-publishUnpublish.vm * */ context.put("publish", Boolean.valueOf(((SiteInfo) state .getAttribute(STATE_SITE_INFO)).getPublished())); context.put("backIndex", "12"); return (String) getContext(data).get("template") + TEMPLATE[9]; case 10: /* * buildContextForTemplate chef_site-newSiteConfirm.vm * */ siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); siteType = (String) state.getAttribute(STATE_SITE_TYPE); if (siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); context.put("isProjectSite", Boolean.FALSE); if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) { context.put("selectedProviderCourse", state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN)); } if (state.getAttribute(STATE_CM_AUTHORIZER_SECTIONS) != null) { context.put("selectedAuthorizerCourse", state .getAttribute(STATE_CM_AUTHORIZER_SECTIONS)); } if (state.getAttribute(STATE_CM_REQUESTED_SECTIONS) != null) { context.put("selectedRequestedCourse", state .getAttribute(STATE_CM_REQUESTED_SECTIONS)); } if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { int number = ((Integer) state .getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)) .intValue(); context.put("manualAddNumber", new Integer(number - 1)); context.put("manualAddFields", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); } context.put("skins", state.getAttribute(STATE_ICONS)); if (StringUtil.trimToNull(siteInfo.getIconUrl()) != null) { context.put("selectedIcon", siteInfo.getIconUrl()); } } else { context.put("isCourseSite", Boolean.FALSE); if (siteType != null && siteType.equalsIgnoreCase("project")) { context.put("isProjectSite", Boolean.TRUE); } if (StringUtil.trimToNull(siteInfo.iconUrl) != null) { context.put("iconUrl", siteInfo.iconUrl); } } context.put("title", siteInfo.title); context.put("description", siteInfo.description); context.put("short_description", siteInfo.short_description); context.put("siteContactName", siteInfo.site_contact_name); context.put("siteContactEmail", siteInfo.site_contact_email); siteType = (String) state.getAttribute(STATE_SITE_TYPE); toolRegistrationSelectedList = (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); // String toolId's context.put(STATE_TOOL_REGISTRATION_LIST, state .getAttribute(STATE_TOOL_REGISTRATION_LIST)); // %%% use // Tool context.put("check_home", state .getAttribute(STATE_TOOL_HOME_SELECTED)); context .put("emailId", state .getAttribute(STATE_TOOL_EMAIL_ADDRESS)); context.put("serverName", ServerConfigurationService .getServerName()); context.put("include", new Boolean(siteInfo.include)); context.put("published", new Boolean(siteInfo.published)); context.put("joinable", new Boolean(siteInfo.joinable)); context.put("joinerRole", siteInfo.joinerRole); context.put("newsTitles", (Hashtable) state .getAttribute(STATE_NEWS_TITLES)); context.put("wcTitles", (Hashtable) state .getAttribute(STATE_WEB_CONTENT_TITLES)); // back to edit access page context.put("back", "18"); context.put("importSiteTools", state .getAttribute(STATE_IMPORT_SITE_TOOL)); context.put("siteService", SiteService.getInstance()); // those manual inputs context.put("form_requiredFields", sectionFieldProvider .getRequiredFields()); context.put("fieldValues", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); return (String) getContext(data).get("template") + TEMPLATE[10]; case 11: /* * buildContextForTemplate chef_site-newSitePublishUnpublish.vm * */ return (String) getContext(data).get("template") + TEMPLATE[11]; case 12: /* * buildContextForTemplate chef_site-siteInfo-list.vm * */ context.put("userDirectoryService", UserDirectoryService .getInstance()); try { siteProperties = site.getProperties(); siteType = site.getType(); if (siteType != null) { state.setAttribute(STATE_SITE_TYPE, siteType); } boolean isMyWorkspace = false; if (SiteService.isUserSite(site.getId())) { if (SiteService.getSiteUserId(site.getId()).equals( SessionManager.getCurrentSessionUserId())) { isMyWorkspace = true; context.put("siteUserId", SiteService .getSiteUserId(site.getId())); } } context.put("isMyWorkspace", Boolean.valueOf(isMyWorkspace)); String siteId = site.getId(); if (state.getAttribute(STATE_ICONS) != null) { List skins = (List) state.getAttribute(STATE_ICONS); for (int i = 0; i < skins.size(); i++) { MyIcon s = (MyIcon) skins.get(i); if (!StringUtil .different(s.getUrl(), site.getIconUrl())) { context.put("siteUnit", s.getName()); break; } } } context.put("siteIcon", site.getIconUrl()); context.put("siteTitle", site.getTitle()); context.put("siteDescription", site.getDescription()); context.put("siteJoinable", new Boolean(site.isJoinable())); if (site.isPublished()) { context.put("published", Boolean.TRUE); } else { context.put("published", Boolean.FALSE); context.put("owner", site.getCreatedBy().getSortName()); } Time creationTime = site.getCreatedTime(); if (creationTime != null) { context.put("siteCreationDate", creationTime .toStringLocalFull()); } boolean allowUpdateSite = SiteService.allowUpdateSite(siteId); context.put("allowUpdate", Boolean.valueOf(allowUpdateSite)); boolean allowUpdateGroupMembership = SiteService .allowUpdateGroupMembership(siteId); context.put("allowUpdateGroupMembership", Boolean .valueOf(allowUpdateGroupMembership)); boolean allowUpdateSiteMembership = SiteService .allowUpdateSiteMembership(siteId); context.put("allowUpdateSiteMembership", Boolean .valueOf(allowUpdateSiteMembership)); Menu b = new MenuImpl(portlet, data, (String) state .getAttribute(STATE_ACTION)); if (allowUpdateSite) { // top menu bar if (!isMyWorkspace) { b.add(new MenuEntry(rb.getString("java.editsite"), "doMenu_edit_site_info")); } b.add(new MenuEntry(rb.getString("java.edittools"), "doMenu_edit_site_tools")); } if (allowUpdateSiteMembership) { // show add participant menu if (!isMyWorkspace) { // show the Add Participant menu b.add(new MenuEntry(rb.getString("java.addp"), "doMenu_siteInfo_addParticipant")); } } if (allowUpdateGroupMembership) { // show Manage Groups menu if (!isMyWorkspace && (ServerConfigurationService .getString("wsetup.group.support") == "" || ServerConfigurationService .getString("wsetup.group.support") .equalsIgnoreCase(Boolean.TRUE.toString()))) { // show the group toolbar unless configured // to not support group b.add(new MenuEntry(rb.getString("java.group"), "doMenu_group")); } } if (allowUpdateSite) { if (!isMyWorkspace) { List gradToolsSiteTypes = (List) state .getAttribute(GRADTOOLS_SITE_TYPES); boolean isGradToolSite = false; if (siteType != null && gradToolsSiteTypes.contains(siteType)) { isGradToolSite = true; } if (siteType == null || siteType != null && !isGradToolSite) { // hide site access for GRADTOOLS // type of sites b.add(new MenuEntry( rb.getString("java.siteaccess"), "doMenu_edit_site_access")); } if (siteType != null && siteType.equals((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { b.add(new MenuEntry(rb.getString("java.editc"), "doMenu_siteInfo_editClass")); } if (siteType == null || siteType != null && !isGradToolSite) { // hide site duplicate and import // for GRADTOOLS type of sites if (SiteService.allowAddSite(null)) { b.add(new MenuEntry(rb.getString("java.duplicate"), "doMenu_siteInfo_duplicate")); } List updatableSites = SiteService .getSites( org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, null, null, null, SortType.TITLE_ASC, null); // import link should be visible even if only one // site if (updatableSites.size() > 0) { b.add(new MenuEntry( rb.getString("java.import"), "doMenu_siteInfo_import")); // a configuration param for // showing/hiding import // from file choice String importFromFile = ServerConfigurationService .getString("site.setup.import.file", Boolean.TRUE.toString()); if (importFromFile.equalsIgnoreCase("true")) { // htripath: June // 4th added as per // Kris and changed // desc of above b.add(new MenuEntry(rb .getString("java.importFile"), "doAttachmentsMtrlFrmFile")); } } } } // if the page order helper is available, not // stealthed and not hidden, show the link if (notStealthOrHiddenTool("sakai-site-pageorder-helper")) { b.add(new MenuEntry(rb.getString("java.orderpages"), "doPageOrderHelper")); } } if (b.size() > 0) { // add the menus to vm context.put("menu", b); } if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITESETUP)) { // editing from worksite setup tool context.put("fromWSetup", Boolean.TRUE); if (state.getAttribute(STATE_PREV_SITE) != null) { context.put("prevSite", state .getAttribute(STATE_PREV_SITE)); } if (state.getAttribute(STATE_NEXT_SITE) != null) { context.put("nextSite", state .getAttribute(STATE_NEXT_SITE)); } } else { context.put("fromWSetup", Boolean.FALSE); } // allow view roster? boolean allowViewRoster = SiteService.allowViewRoster(siteId); if (allowViewRoster) { context.put("viewRoster", Boolean.TRUE); } else { context.put("viewRoster", Boolean.FALSE); } // set participant list if (allowUpdateSite || allowViewRoster || allowUpdateSiteMembership) { Collection participantsCollection = getParticipantList(state); sortedBy = (String) state.getAttribute(SORTED_BY); sortedAsc = (String) state.getAttribute(SORTED_ASC); if (sortedBy == null) { state.setAttribute(SORTED_BY, SORTED_BY_PARTICIPANT_NAME); sortedBy = SORTED_BY_PARTICIPANT_NAME; } if (sortedAsc == null) { sortedAsc = Boolean.TRUE.toString(); state.setAttribute(SORTED_ASC, sortedAsc); } if (sortedBy != null) context.put("currentSortedBy", sortedBy); if (sortedAsc != null) context.put("currentSortAsc", sortedAsc); context.put("participantListSize", new Integer(participantsCollection.size())); context.put("participantList", prepPage(state)); pagingInfoToContext(state, context); } context.put("include", Boolean.valueOf(site.isPubView())); // site contact information String contactName = siteProperties .getProperty(PROP_SITE_CONTACT_NAME); String contactEmail = siteProperties .getProperty(PROP_SITE_CONTACT_EMAIL); if (contactName == null && contactEmail == null) { User u = site.getCreatedBy(); String email = u.getEmail(); if (email != null) { contactEmail = u.getEmail(); } contactName = u.getDisplayName(); } if (contactName != null) { context.put("contactName", contactName); } if (contactEmail != null) { context.put("contactEmail", contactEmail); } if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); coursesIntoContext(state, context, site); context.put("term", siteProperties .getProperty(PROP_SITE_TERM)); } else { context.put("isCourseSite", Boolean.FALSE); } } catch (Exception e) { M_log.warn(this + " site info list: " + e.toString()); } roles = getRoles(state); context.put("roles", roles); // will have the choice to active/inactive user or not String activeInactiveUser = ServerConfigurationService.getString( "activeInactiveUser", Boolean.FALSE.toString()); if (activeInactiveUser.equalsIgnoreCase("true")) { context.put("activeInactiveUser", Boolean.TRUE); // put realm object into context realmId = SiteService.siteReference(site.getId()); try { context.put("realm", AuthzGroupService .getAuthzGroup(realmId)); } catch (GroupNotDefinedException e) { M_log.warn(this + " IdUnusedException " + realmId); } } else { context.put("activeInactiveUser", Boolean.FALSE); } context.put("groupsWithMember", site .getGroupsWithMember(UserDirectoryService.getCurrentUser() .getId())); return (String) getContext(data).get("template") + TEMPLATE[12]; case 13: /* * buildContextForTemplate chef_site-siteInfo-editInfo.vm * */ siteProperties = site.getProperties(); context.put("title", state.getAttribute(FORM_SITEINFO_TITLE)); context.put("type", site.getType()); siteType = (String) state.getAttribute(STATE_SITE_TYPE); if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); context.put("skins", state.getAttribute(STATE_ICONS)); if (state.getAttribute(FORM_SITEINFO_SKIN) != null) { context.put("selectedIcon", state .getAttribute(FORM_SITEINFO_SKIN)); } else if (site.getIconUrl() != null) { context.put("selectedIcon", site.getIconUrl()); } setTermListForContext(context, state, true); // true->only future terms if (state.getAttribute(FORM_SITEINFO_TERM) == null) { String currentTerm = site.getProperties().getProperty( PROP_SITE_TERM); if (currentTerm != null) { state.setAttribute(FORM_SITEINFO_TERM, currentTerm); } } setSelectedTermForContext(context, state, FORM_SITEINFO_TERM); } else { context.put("isCourseSite", Boolean.FALSE); if (state.getAttribute(FORM_SITEINFO_ICON_URL) == null && StringUtil.trimToNull(site.getIconUrl()) != null) { state.setAttribute(FORM_SITEINFO_ICON_URL, site .getIconUrl()); } if (state.getAttribute(FORM_SITEINFO_ICON_URL) != null) { context.put("iconUrl", state .getAttribute(FORM_SITEINFO_ICON_URL)); } } context.put("description", state .getAttribute(FORM_SITEINFO_DESCRIPTION)); context.put("short_description", state .getAttribute(FORM_SITEINFO_SHORT_DESCRIPTION)); context.put("form_site_contact_name", state .getAttribute(FORM_SITEINFO_CONTACT_NAME)); context.put("form_site_contact_email", state .getAttribute(FORM_SITEINFO_CONTACT_EMAIL)); // Display of appearance icon/url list with course site based on // "disable.course.site.skin.selection" value set with // sakai.properties file. if ((ServerConfigurationService .getString("disable.course.site.skin.selection")) .equals("true")) { context.put("disableCourseSelection", Boolean.TRUE); } return (String) getContext(data).get("template") + TEMPLATE[13]; case 14: /* * buildContextForTemplate chef_site-siteInfo-editInfoConfirm.vm * */ siteProperties = site.getProperties(); siteType = (String) state.getAttribute(STATE_SITE_TYPE); if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); context.put("siteTerm", state.getAttribute(FORM_SITEINFO_TERM)); } else { context.put("isCourseSite", Boolean.FALSE); } context.put("oTitle", site.getTitle()); context.put("title", state.getAttribute(FORM_SITEINFO_TITLE)); context.put("description", state .getAttribute(FORM_SITEINFO_DESCRIPTION)); context.put("oDescription", site.getDescription()); context.put("short_description", state .getAttribute(FORM_SITEINFO_SHORT_DESCRIPTION)); context.put("oShort_description", site.getShortDescription()); context.put("skin", state.getAttribute(FORM_SITEINFO_SKIN)); context.put("oSkin", site.getIconUrl()); context.put("skins", state.getAttribute(STATE_ICONS)); context.put("oIcon", site.getIconUrl()); context.put("icon", state.getAttribute(FORM_SITEINFO_ICON_URL)); context.put("include", state.getAttribute(FORM_SITEINFO_INCLUDE)); context.put("oInclude", Boolean.valueOf(site.isPubView())); context.put("name", state.getAttribute(FORM_SITEINFO_CONTACT_NAME)); context.put("oName", siteProperties .getProperty(PROP_SITE_CONTACT_NAME)); context.put("email", state .getAttribute(FORM_SITEINFO_CONTACT_EMAIL)); context.put("oEmail", siteProperties .getProperty(PROP_SITE_CONTACT_EMAIL)); return (String) getContext(data).get("template") + TEMPLATE[14]; case 15: /* * buildContextForTemplate chef_site-addRemoveFeatureConfirm.vm * */ context.put("title", site.getTitle()); site_type = (String) state.getAttribute(STATE_SITE_TYPE); myworkspace_site = false; if (SiteService.isUserSite(site.getId())) { if (SiteService.getSiteUserId(site.getId()).equals( SessionManager.getCurrentSessionUserId())) { myworkspace_site = true; site_type = "myworkspace"; } } context.put(STATE_TOOL_REGISTRATION_LIST, state .getAttribute(STATE_TOOL_REGISTRATION_LIST)); context.put("check_home", state .getAttribute(STATE_TOOL_HOME_SELECTED)); context.put("selectedTools", orderToolIds(state, (String) state .getAttribute(STATE_SITE_TYPE), (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST))); context.put("oldSelectedTools", state .getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST)); context.put("oldSelectedHome", state .getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME)); context.put("continueIndex", "12"); if (state.getAttribute(STATE_TOOL_EMAIL_ADDRESS) != null) { context.put("emailId", state .getAttribute(STATE_TOOL_EMAIL_ADDRESS)); } context.put("serverName", ServerConfigurationService .getServerName()); context.put("newsTitles", (Hashtable) state .getAttribute(STATE_NEWS_TITLES)); context.put("wcTitles", (Hashtable) state .getAttribute(STATE_WEB_CONTENT_TITLES)); if (fromENWModifyView(state)) { context.put("back", "26"); } else { context.put("back", "4"); } return (String) getContext(data).get("template") + TEMPLATE[15]; case 16: /* * buildContextForTemplate chef_site-publishUnpublish-sendEmail.vm * */ context.put("title", site.getTitle()); context.put("willNotify", state.getAttribute(FORM_WILL_NOTIFY)); return (String) getContext(data).get("template") + TEMPLATE[16]; case 17: /* * buildContextForTemplate chef_site-publishUnpublish-confirm.vm * */ context.put("title", site.getTitle()); context.put("continueIndex", "12"); SiteInfo sInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); if (sInfo.getPublished()) { context.put("publish", Boolean.TRUE); context.put("backIndex", "16"); } else { context.put("publish", Boolean.FALSE); context.put("backIndex", "9"); } context.put("willNotify", state.getAttribute(FORM_WILL_NOTIFY)); return (String) getContext(data).get("template") + TEMPLATE[17]; case 18: /* * buildContextForTemplate chef_siteInfo-editAccess.vm * */ List publicChangeableSiteTypes = (List) state .getAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES); List unJoinableSiteTypes = (List) state .getAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE); if (site != null) { // editing existing site context.put("site", site); siteType = state.getAttribute(STATE_SITE_TYPE) != null ? (String) state .getAttribute(STATE_SITE_TYPE) : null; if (siteType != null && publicChangeableSiteTypes.contains(siteType)) { context.put("publicChangeable", Boolean.TRUE); } else { context.put("publicChangeable", Boolean.FALSE); } context.put("include", Boolean.valueOf(site.isPubView())); if (siteType != null && !unJoinableSiteTypes.contains(siteType)) { // site can be set as joinable context.put("disableJoinable", Boolean.FALSE); if (state.getAttribute(STATE_JOINABLE) == null) { state.setAttribute(STATE_JOINABLE, Boolean.valueOf(site .isJoinable())); } if (state.getAttribute(STATE_JOINERROLE) == null || state.getAttribute(STATE_JOINABLE) != null && ((Boolean) state.getAttribute(STATE_JOINABLE)) .booleanValue()) { state.setAttribute(STATE_JOINERROLE, site .getJoinerRole()); } if (state.getAttribute(STATE_JOINABLE) != null) { context.put("joinable", state .getAttribute(STATE_JOINABLE)); } if (state.getAttribute(STATE_JOINERROLE) != null) { context.put("joinerRole", state .getAttribute(STATE_JOINERROLE)); } } else { // site cannot be set as joinable context.put("disableJoinable", Boolean.TRUE); } context.put("roles", getRoles(state)); context.put("back", "12"); } else { siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); if (siteInfo.site_type != null && publicChangeableSiteTypes .contains(siteInfo.site_type)) { context.put("publicChangeable", Boolean.TRUE); } else { context.put("publicChangeable", Boolean.FALSE); } context.put("include", Boolean.valueOf(siteInfo.getInclude())); context.put("published", Boolean.valueOf(siteInfo .getPublished())); if (siteInfo.site_type != null && !unJoinableSiteTypes.contains(siteInfo.site_type)) { // site can be set as joinable context.put("disableJoinable", Boolean.FALSE); context.put("joinable", Boolean.valueOf(siteInfo.joinable)); context.put("joinerRole", siteInfo.joinerRole); } else { // site cannot be set as joinable context.put("disableJoinable", Boolean.TRUE); } // use the type's template, if defined String realmTemplate = "!site.template"; if (siteInfo.site_type != null) { realmTemplate = realmTemplate + "." + siteInfo.site_type; } try { AuthzGroup r = AuthzGroupService .getAuthzGroup(realmTemplate); context.put("roles", r.getRoles()); } catch (GroupNotDefinedException e) { try { AuthzGroup rr = AuthzGroupService .getAuthzGroup("!site.template"); context.put("roles", rr.getRoles()); } catch (GroupNotDefinedException ee) { } } // new site, go to confirmation page context.put("continue", "10"); if (fromENWModifyView(state)) { context.put("back", "26"); } else if (state.getAttribute(STATE_IMPORT) != null) { context.put("back", "27"); } else { context.put("back", "3"); } siteType = (String) state.getAttribute(STATE_SITE_TYPE); if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); context.put("isProjectSite", Boolean.FALSE); } else { context.put("isCourseSite", Boolean.FALSE); if (siteType.equalsIgnoreCase("project")) { context.put("isProjectSite", Boolean.TRUE); } } } return (String) getContext(data).get("template") + TEMPLATE[18]; case 19: /* * buildContextForTemplate chef_site-addParticipant-sameRole.vm * */ context.put("title", site.getTitle()); context.put("roles", getRoles(state)); context.put("participantList", state .getAttribute(STATE_ADD_PARTICIPANTS)); context.put("form_selectedRole", state .getAttribute("form_selectedRole")); return (String) getContext(data).get("template") + TEMPLATE[19]; case 20: /* * buildContextForTemplate chef_site-addParticipant-differentRole.vm * */ context.put("title", site.getTitle()); context.put("roles", getRoles(state)); context.put("selectedRoles", state .getAttribute(STATE_SELECTED_PARTICIPANT_ROLES)); context.put("participantList", state .getAttribute(STATE_ADD_PARTICIPANTS)); return (String) getContext(data).get("template") + TEMPLATE[20]; case 21: /* * buildContextForTemplate chef_site-addParticipant-notification.vm * */ context.put("title", site.getTitle()); context.put("sitePublished", Boolean.valueOf(site.isPublished())); if (state.getAttribute("form_selectedNotify") == null) { state.setAttribute("form_selectedNotify", Boolean.FALSE); } context.put("notify", state.getAttribute("form_selectedNotify")); boolean same_role = state.getAttribute("form_same_role") == null ? true : ((Boolean) state.getAttribute("form_same_role")) .booleanValue(); if (same_role) { context.put("backIndex", "19"); } else { context.put("backIndex", "20"); } return (String) getContext(data).get("template") + TEMPLATE[21]; case 22: /* * buildContextForTemplate chef_site-addParticipant-confirm.vm * */ context.put("title", site.getTitle()); context.put("participants", state .getAttribute(STATE_ADD_PARTICIPANTS)); context.put("notify", state.getAttribute("form_selectedNotify")); context.put("roles", getRoles(state)); context.put("same_role", state.getAttribute("form_same_role")); context.put("selectedRoles", state .getAttribute(STATE_SELECTED_PARTICIPANT_ROLES)); context .put("selectedRole", state .getAttribute("form_selectedRole")); return (String) getContext(data).get("template") + TEMPLATE[22]; case 23: /* * buildContextForTemplate chef_siteInfo-editAccess-globalAccess.vm * */ context.put("title", site.getTitle()); context.put("roles", getRoles(state)); if (state.getAttribute("form_joinable") == null) { state.setAttribute("form_joinable", new Boolean(site .isJoinable())); } context.put("form_joinable", state.getAttribute("form_joinable")); if (state.getAttribute("form_joinerRole") == null) { state.setAttribute("form_joinerRole", site.getJoinerRole()); } context.put("form_joinerRole", state .getAttribute("form_joinerRole")); return (String) getContext(data).get("template") + TEMPLATE[23]; case 24: /* * buildContextForTemplate * chef_siteInfo-editAccess-globalAccess-confirm.vm * */ context.put("title", site.getTitle()); context.put("form_joinable", state.getAttribute("form_joinable")); context.put("form_joinerRole", state .getAttribute("form_joinerRole")); return (String) getContext(data).get("template") + TEMPLATE[24]; case 25: /* * buildContextForTemplate chef_changeRoles-confirm.vm * */ Boolean sameRole = (Boolean) state .getAttribute(STATE_CHANGEROLE_SAMEROLE); context.put("sameRole", sameRole); if (sameRole.booleanValue()) { // same role context.put("currentRole", state .getAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE)); } else { context.put("selectedRoles", state .getAttribute(STATE_SELECTED_PARTICIPANT_ROLES)); } roles = getRoles(state); context.put("roles", roles); context.put("participantSelectedList", state .getAttribute(STATE_SELECTED_PARTICIPANTS)); if (state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES) != null) { context.put("selectedRoles", state .getAttribute(STATE_SELECTED_PARTICIPANT_ROLES)); } context.put("siteTitle", site.getTitle()); return (String) getContext(data).get("template") + TEMPLATE[25]; case 26: /* * buildContextForTemplate chef_site-modifyENW.vm * */ site_type = (String) state.getAttribute(STATE_SITE_TYPE); boolean existingSite = site != null ? true : false; if (existingSite) { // revising a existing site's tool context.put("existingSite", Boolean.TRUE); context.put("back", "4"); context.put("continue", "15"); context.put("function", "eventSubmit_doAdd_remove_features"); } else { // new site context.put("existingSite", Boolean.FALSE); context.put("function", "eventSubmit_doAdd_features"); if (state.getAttribute(STATE_IMPORT) != null) { context.put("back", "27"); } else { // new site, go to edit access page context.put("back", "3"); } context.put("continue", "18"); } context.put(STATE_TOOL_REGISTRATION_LIST, state .getAttribute(STATE_TOOL_REGISTRATION_LIST)); toolRegistrationSelectedList = (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); // String toolId's String emailId = (String) state .getAttribute(STATE_TOOL_EMAIL_ADDRESS); if (emailId != null) { context.put("emailId", emailId); } // titles for news tools newsTitles = (Hashtable) state.getAttribute(STATE_NEWS_TITLES); if (newsTitles == null) { newsTitles = new Hashtable(); newsTitles.put("sakai.news", NEWS_DEFAULT_TITLE); state.setAttribute(STATE_NEWS_TITLES, newsTitles); } context.put("newsTitles", newsTitles); // urls for news tools newsUrls = (Hashtable) state.getAttribute(STATE_NEWS_URLS); if (newsUrls == null) { newsUrls = new Hashtable(); newsUrls.put("sakai.news", NEWS_DEFAULT_URL); state.setAttribute(STATE_NEWS_URLS, newsUrls); } context.put("newsUrls", newsUrls); // titles for web content tools wcTitles = (Hashtable) state.getAttribute(STATE_WEB_CONTENT_TITLES); if (wcTitles == null) { wcTitles = new Hashtable(); wcTitles.put("sakai.iframe", WEB_CONTENT_DEFAULT_TITLE); state.setAttribute(STATE_WEB_CONTENT_TITLES, wcTitles); } context.put("wcTitles", wcTitles); // URLs for web content tools wcUrls = (Hashtable) state.getAttribute(STATE_WEB_CONTENT_URLS); if (wcUrls == null) { wcUrls = new Hashtable(); wcUrls.put("sakai.iframe", WEB_CONTENT_DEFAULT_URL); state.setAttribute(STATE_WEB_CONTENT_URLS, wcUrls); } context.put("wcUrls", wcUrls); context.put("serverName", ServerConfigurationService .getServerName()); context.put("oldSelectedTools", state .getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST)); return (String) getContext(data).get("template") + TEMPLATE[26]; case 27: /* * buildContextForTemplate chef_site-importSites.vm * */ existingSite = site != null ? true : false; site_type = (String) state.getAttribute(STATE_SITE_TYPE); if (existingSite) { // revising a existing site's tool context.put("continue", "12"); context.put("back", "28"); context.put("totalSteps", "2"); context.put("step", "2"); context.put("currentSite", site); } else { // new site, go to edit access page context.put("back", "3"); if (fromENWModifyView(state)) { context.put("continue", "26"); } else { context.put("continue", "18"); } } context.put(STATE_TOOL_REGISTRATION_LIST, state .getAttribute(STATE_TOOL_REGISTRATION_LIST)); context.put("selectedTools", orderToolIds(state, site_type, (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST))); // String toolId's context.put("importSites", state.getAttribute(STATE_IMPORT_SITES)); context.put("importSitesTools", state .getAttribute(STATE_IMPORT_SITE_TOOL)); context.put("check_home", state .getAttribute(STATE_TOOL_HOME_SELECTED)); context.put("importSupportedTools", importTools()); return (String) getContext(data).get("template") + TEMPLATE[27]; case 28: /* * buildContextForTemplate chef_siteinfo-import.vm * */ context.put("currentSite", site); context.put("importSiteList", state .getAttribute(STATE_IMPORT_SITES)); context.put("sites", SiteService.getSites( org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, null, null, null, SortType.TITLE_ASC, null)); return (String) getContext(data).get("template") + TEMPLATE[28]; case 29: /* * buildContextForTemplate chef_siteinfo-duplicate.vm * */ context.put("siteTitle", site.getTitle()); String sType = site.getType(); if (sType != null && sType.equals((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); context.put("currentTermId", site.getProperties().getProperty( PROP_SITE_TERM)); setTermListForContext(context, state, true); // true upcoming only } else { context.put("isCourseSite", Boolean.FALSE); } if (state.getAttribute(SITE_DUPLICATED) == null) { context.put("siteDuplicated", Boolean.FALSE); } else { context.put("siteDuplicated", Boolean.TRUE); context.put("duplicatedName", state .getAttribute(SITE_DUPLICATED_NAME)); } return (String) getContext(data).get("template") + TEMPLATE[29]; case 36: /* * buildContextForTemplate chef_site-newSiteCourse.vm */ // SAK-9824 Boolean enableCourseCreationForUser = ServerConfigurationService.getBoolean("site.enableCreateAnyUser", Boolean.FALSE); context.put("enableCourseCreationForUser", enableCourseCreationForUser); if (site != null) { context.put("site", site); context.put("siteTitle", site.getTitle()); setTermListForContext(context, state, true); // true -> upcoming only List providerCourseList = (List) state .getAttribute(SITE_PROVIDER_COURSE_LIST); coursesIntoContext(state, context, site); AcademicSession t = (AcademicSession) state .getAttribute(STATE_TERM_SELECTED); context.put("term", t); if (t != null) { String userId = UserDirectoryService.getCurrentUser().getEid(); List courses = prepareCourseAndSectionListing(userId, t .getEid(), state); if (courses != null && courses.size() > 0) { Vector notIncludedCourse = new Vector(); // remove included sites for (Iterator i = courses.iterator(); i.hasNext();) { CourseObject c = (CourseObject) i.next(); if (providerCourseList == null || providerCourseList != null && !providerCourseList.contains(c.getEid())) { notIncludedCourse.add(c); } } state.setAttribute(STATE_TERM_COURSE_LIST, notIncludedCourse); } else { state.removeAttribute(STATE_TERM_COURSE_LIST); } } // step number used in UI state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer("1")); } else { // need to include both list 'cos STATE_CM_AUTHORIZER_SECTIONS // contains sections that doens't belongs to current user and // STATE_ADD_CLASS_PROVIDER_CHOSEN contains section that does - // v2.4 daisyf if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null || state.getAttribute(STATE_CM_AUTHORIZER_SECTIONS) != null) { List<String> providerSectionList = (List<String>) state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN); if (providerSectionList != null) { /* List list1 = prepareSectionObject(providerSectionList, (String) state .getAttribute(STATE_CM_CURRENT_USERID)); */ context.put("selectedProviderCourse", providerSectionList); } List<SectionObject> authorizerSectionList = (List<SectionObject>) state .getAttribute(STATE_CM_AUTHORIZER_SECTIONS); if (authorizerSectionList != null) { List authorizerList = (List) state .getAttribute(STATE_CM_AUTHORIZER_LIST); //authorizerList is a list of SectionObject /* String userId = null; if (authorizerList != null) { userId = (String) authorizerList.get(0); } List list2 = prepareSectionObject( authorizerSectionList, userId); */ ArrayList list2 = new ArrayList(); for (int i=0; i<authorizerSectionList.size();i++){ SectionObject so = (SectionObject)authorizerSectionList.get(i); list2.add(so.getEid()); } context.put("selectedAuthorizerCourse", list2); } } if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { context.put("selectedManualCourse", Boolean.TRUE); } context.put("term", (AcademicSession) state .getAttribute(STATE_TERM_SELECTED)); context.put("currentUserId", (String) state .getAttribute(STATE_CM_CURRENT_USERID)); context.put("form_additional", (String) state .getAttribute(FORM_ADDITIONAL)); context.put("authorizers", getAuthorizers(state)); } if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITESETUP)) { context.put("backIndex", "1"); } else if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITEINFO)) { context.put("backIndex", ""); } List ll = (List) state.getAttribute(STATE_TERM_COURSE_LIST); context.put("termCourseList", state .getAttribute(STATE_TERM_COURSE_LIST)); // added for 2.4 -daisyf context.put("campusDirectory", getCampusDirectory()); context.put("userId", (String) state .getAttribute(STATE_INSTRUCTOR_SELECTED)); /* * for measuring how long it takes to load sections java.util.Date * date = new java.util.Date(); M_log.debug("***2. finish at: * "+date); M_log.debug("***3. userId:"+(String) state * .getAttribute(STATE_INSTRUCTOR_SELECTED)); */ return (String) getContext(data).get("template") + TEMPLATE[36]; case 37: /* * buildContextForTemplate chef_site-newSiteCourseManual.vm */ if (site != null) { context.put("site", site); context.put("siteTitle", site.getTitle()); coursesIntoContext(state, context, site); } buildInstructorSectionsList(state, params, context); context.put("form_requiredFields", sectionFieldProvider .getRequiredFields()); context.put("form_additional", siteInfo.additional); context.put("form_title", siteInfo.title); context.put("form_description", siteInfo.description); context.put("officialAccountName", ServerConfigurationService .getString("officialAccountName", "")); context.put("value_uniqname", state .getAttribute(STATE_SITE_QUEST_UNIQNAME)); int number = 1; if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { number = ((Integer) state .getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)) .intValue(); context.put("currentNumber", new Integer(number)); } context.put("currentNumber", new Integer(number)); context.put("listSize", new Integer(number - 1)); context.put("fieldValues", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) { List l = (List) state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN); context.put("selectedProviderCourse", l); context.put("size", new Integer(l.size() - 1)); } if (state.getAttribute(STATE_CM_REQUESTED_SECTIONS) != null) { List l = (List) state .getAttribute(STATE_CM_REQUESTED_SECTIONS); context.put("cmRequestedSections", l); } if (state.getAttribute(STATE_SITE_MODE).equals(SITE_MODE_SITEINFO)) { context.put("editSite", Boolean.TRUE); context.put("cmSelectedSections", state.getAttribute(STATE_CM_SELECTED_SECTIONS)); } if (site == null) { // v2.4 - added & modified by daisyf if (courseManagementIsImplemented() && state.getAttribute(STATE_TERM_COURSE_LIST) != null) { // back to the list view of sections context.put("back", "36"); } else { context.put("back", "1"); } if (state.getAttribute(STATE_AUTO_ADD) != null) { context.put("autoAdd", Boolean.TRUE); // context.put("back", "36"); } } else { // editing site context.put("back", "36"); } isFutureTermSelected(state); context.put("isFutureTerm", state .getAttribute(STATE_FUTURE_TERM_SELECTED)); context.put("weeksAhead", ServerConfigurationService.getString( "roster.available.weeks.before.term.start", "0")); return (String) getContext(data).get("template") + TEMPLATE[37]; case 42: /* * buildContextForTemplate chef_site-gradtoolsConfirm.vm * */ siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); context.put("title", siteInfo.title); context.put("description", siteInfo.description); context.put("short_description", siteInfo.short_description); toolRegistrationList = (Vector) state .getAttribute(STATE_PROJECT_TOOL_LIST); toolRegistrationSelectedList = (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); // String toolId's context.put(STATE_TOOL_REGISTRATION_LIST, toolRegistrationList); // %%% // use // Tool context.put("check_home", state .getAttribute(STATE_TOOL_HOME_SELECTED)); context .put("emailId", state .getAttribute(STATE_TOOL_EMAIL_ADDRESS)); context.put("serverName", ServerConfigurationService .getServerName()); context.put("include", new Boolean(siteInfo.include)); return (String) getContext(data).get("template") + TEMPLATE[42]; case 43: /* * buildContextForTemplate chef_siteInfo-editClass.vm * */ bar = new MenuImpl(portlet, data, (String) state .getAttribute(STATE_ACTION)); if (SiteService.allowAddSite(null)) { bar.add(new MenuEntry(rb.getString("java.addclasses"), "doMenu_siteInfo_addClass")); } context.put("menu", bar); context.put("siteTitle", site.getTitle()); coursesIntoContext(state, context, site); return (String) getContext(data).get("template") + TEMPLATE[43]; case 44: /* * buildContextForTemplate chef_siteInfo-addCourseConfirm.vm * */ context.put("siteTitle", site.getTitle()); coursesIntoContext(state, context, site); context.put("providerAddCourses", state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN)); if (state.getAttribute(STATE_CM_SELECTED_SECTIONS) != null) { context.put("cmSelectedSections", state.getAttribute(STATE_CM_SELECTED_SECTIONS)); } if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { int addNumber = ((Integer) state .getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)) .intValue() - 1; context.put("manualAddNumber", new Integer(addNumber)); context.put("requestFields", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); context.put("backIndex", "37"); } else { context.put("backIndex", "36"); } // those manual inputs context.put("form_requiredFields", sectionFieldProvider .getRequiredFields()); context.put("fieldValues", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); return (String) getContext(data).get("template") + TEMPLATE[44]; // htripath - import materials from classic case 45: /* * buildContextForTemplate chef_siteInfo-importMtrlMaster.vm * */ return (String) getContext(data).get("template") + TEMPLATE[45]; case 46: /* * buildContextForTemplate chef_siteInfo-importMtrlCopy.vm * */ // this is for list display in listbox context .put("allZipSites", state .getAttribute(ALL_ZIP_IMPORT_SITES)); context.put("finalZipSites", state .getAttribute(FINAL_ZIP_IMPORT_SITES)); // zip file // context.put("zipreffile",state.getAttribute(CLASSIC_ZIP_FILE_NAME)); return (String) getContext(data).get("template") + TEMPLATE[46]; case 47: /* * buildContextForTemplate chef_siteInfo-importMtrlCopyConfirm.vm * */ context.put("finalZipSites", state .getAttribute(FINAL_ZIP_IMPORT_SITES)); return (String) getContext(data).get("template") + TEMPLATE[47]; case 48: /* * buildContextForTemplate chef_siteInfo-importMtrlCopyConfirm.vm * */ context.put("finalZipSites", state .getAttribute(FINAL_ZIP_IMPORT_SITES)); return (String) getContext(data).get("template") + TEMPLATE[48]; case 49: /* * buildContextForTemplate chef_siteInfo-group.vm * */ context.put("site", site); bar = new MenuImpl(portlet, data, (String) state .getAttribute(STATE_ACTION)); if (SiteService.allowUpdateSite(site.getId()) || SiteService.allowUpdateGroupMembership(site.getId())) { bar.add(new MenuEntry(rb.getString("java.newgroup"), "doGroup_new")); } context.put("menu", bar); // the group list sortedBy = (String) state.getAttribute(SORTED_BY); sortedAsc = (String) state.getAttribute(SORTED_ASC); if (sortedBy != null) context.put("currentSortedBy", sortedBy); if (sortedAsc != null) context.put("currentSortAsc", sortedAsc); // only show groups created by WSetup tool itself Collection groups = (Collection) site.getGroups(); List groupsByWSetup = new Vector(); for (Iterator gIterator = groups.iterator(); gIterator.hasNext();) { Group gNext = (Group) gIterator.next(); String gProp = gNext.getProperties().getProperty( GROUP_PROP_WSETUP_CREATED); if (gProp != null && gProp.equals(Boolean.TRUE.toString())) { groupsByWSetup.add(gNext); } } if (sortedBy != null && sortedAsc != null) { context.put("groups", new SortedIterator(groupsByWSetup .iterator(), new SiteComparator(sortedBy, sortedAsc))); } return (String) getContext(data).get("template") + TEMPLATE[49]; case 50: /* * buildContextForTemplate chef_siteInfo-groupedit.vm * */ Group g = getStateGroup(state); if (g != null) { context.put("group", g); context.put("newgroup", Boolean.FALSE); } else { context.put("newgroup", Boolean.TRUE); } if (state.getAttribute(STATE_GROUP_TITLE) != null) { context.put("title", state.getAttribute(STATE_GROUP_TITLE)); } if (state.getAttribute(STATE_GROUP_DESCRIPTION) != null) { context.put("description", state .getAttribute(STATE_GROUP_DESCRIPTION)); } Iterator siteMembers = new SortedIterator(getParticipantList(state) .iterator(), new SiteComparator(SORTED_BY_PARTICIPANT_NAME, Boolean.TRUE.toString())); if (siteMembers != null && siteMembers.hasNext()) { context.put("generalMembers", siteMembers); } Set groupMembersSet = (Set) state.getAttribute(STATE_GROUP_MEMBERS); if (state.getAttribute(STATE_GROUP_MEMBERS) != null) { context.put("groupMembers", new SortedIterator(groupMembersSet .iterator(), new SiteComparator(SORTED_BY_MEMBER_NAME, Boolean.TRUE.toString()))); } context.put("groupMembersClone", groupMembersSet); context.put("userDirectoryService", UserDirectoryService .getInstance()); return (String) getContext(data).get("template") + TEMPLATE[50]; case 51: /* * buildContextForTemplate chef_siteInfo-groupDeleteConfirm.vm * */ context.put("site", site); context .put("removeGroupIds", new ArrayList(Arrays .asList((String[]) state .getAttribute(STATE_GROUP_REMOVE)))); return (String) getContext(data).get("template") + TEMPLATE[51]; case 53: { /* * build context for chef_site-findCourse.vm */ AcademicSession t = (AcademicSession) state .getAttribute(STATE_TERM_SELECTED); List cmLevels = (List) state.getAttribute(STATE_CM_LEVELS), selections = (List) state .getAttribute(STATE_CM_LEVEL_SELECTIONS); if (cmLevels == null) { cmLevels = getCMLevelLabels(); } SectionObject selectedSect = (SectionObject) state .getAttribute(STATE_CM_SELECTED_SECTION); List<SectionObject> requestedSections = (List<SectionObject>) state .getAttribute(STATE_CM_REQUESTED_SECTIONS); if (courseManagementIsImplemented() && cms != null) { context.put("cmsAvailable", new Boolean(true)); } if (cms == null || !courseManagementIsImplemented() || cmLevels == null || cmLevels.size() < 1) { // TODO: redirect to manual entry: case #37 } else { Object levelOpts[] = new Object[cmLevels.size()]; int numSelections = 0; if (selections != null) numSelections = selections.size(); // populate options for dropdown lists switch (numSelections) { /* * execution will fall through these statements based on number * of selections already made */ case 3: // intentionally blank case 2: levelOpts[2] = getCMSections((String) selections.get(1)); case 1: levelOpts[1] = getCMCourseOfferings((String) selections .get(0), t.getEid()); default: levelOpts[0] = getCMSubjects(); } context.put("cmLevelOptions", Arrays.asList(levelOpts)); } if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) { context.put("selectedProviderCourse", state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN)); } if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { int courseInd = ((Integer) state .getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)) .intValue(); context.put("manualAddNumber", new Integer(courseInd - 1)); context.put("manualAddFields", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); } context.put("term", (AcademicSession) state .getAttribute(STATE_TERM_SELECTED)); context.put("cmLevels", cmLevels); context.put("cmLevelSelections", selections); context.put("selectedCourse", selectedSect); context.put("cmRequestedSections", requestedSections); if (state.getAttribute(STATE_SITE_MODE).equals(SITE_MODE_SITEINFO)) { context.put("editSite", Boolean.TRUE); context.put("cmSelectedSections", state.getAttribute(STATE_CM_SELECTED_SECTIONS)); } if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITESETUP)) { if (state.getAttribute(STATE_TERM_COURSE_LIST) != null) { context.put("backIndex", "36"); } else { context.put("backIndex", "1"); } } else if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITEINFO)) { context.put("backIndex", "36"); } context.put("authzGroupService", AuthzGroupService.getInstance()); return (String) getContext(data).get("template") + TEMPLATE[53]; } } // should never be reached return (String) getContext(data).get("template") + TEMPLATE[0]; } // buildContextForTemplate
diff --git a/backend/manager/modules/restapi/jaxrs/src/main/java/org/ovirt/engine/api/restapi/resource/BackendDisksResource.java b/backend/manager/modules/restapi/jaxrs/src/main/java/org/ovirt/engine/api/restapi/resource/BackendDisksResource.java index a9dcbbc2c..c80f1ad13 100644 --- a/backend/manager/modules/restapi/jaxrs/src/main/java/org/ovirt/engine/api/restapi/resource/BackendDisksResource.java +++ b/backend/manager/modules/restapi/jaxrs/src/main/java/org/ovirt/engine/api/restapi/resource/BackendDisksResource.java @@ -1,58 +1,61 @@ package org.ovirt.engine.api.restapi.resource; import java.util.List; import javax.ws.rs.core.Response; import org.ovirt.engine.api.model.Disk; import org.ovirt.engine.api.model.Disks; import org.ovirt.engine.api.resource.DiskResource; import org.ovirt.engine.api.resource.DisksResource; import org.ovirt.engine.core.common.action.AddDiskParameters; import org.ovirt.engine.core.common.action.RemoveDiskParameters; import org.ovirt.engine.core.common.action.VdcActionType; import org.ovirt.engine.core.common.interfaces.SearchType; import org.ovirt.engine.core.common.queries.GetDiskByDiskIdParameters; import org.ovirt.engine.core.common.queries.VdcQueryType; import org.ovirt.engine.core.compat.Guid; public class BackendDisksResource extends AbstractBackendCollectionResource<Disk, org.ovirt.engine.core.common.businessentities.Disk> implements DisksResource{ private static final String SUB_COLLECTIONS = "statistics"; public BackendDisksResource() { super(Disk.class, org.ovirt.engine.core.common.businessentities.Disk.class, SUB_COLLECTIONS); } @Override public Response add(Disk disk) { validateParameters(disk, "size", "format", "interface"); AddDiskParameters params = new AddDiskParameters(); params.setDiskInfo(getMapper(Disk.class, org.ovirt.engine.core.common.businessentities.Disk.class).map(disk, null)); + if (disk.isSetStorageDomains() && disk.getStorageDomains().isSetStorageDomains() && disk.getStorageDomains().getStorageDomains().get(0).isSetId()) { + params.setStorageDomainId(Guid.createGuidFromString(disk.getStorageDomains().getStorageDomains().get(0).getId())); + } return performCreation(VdcActionType.AddDisk, params, new QueryIdResolver(VdcQueryType.GetDiskByDiskId, GetDiskByDiskIdParameters.class)); } @Override public Disks list() { return mapCollection(getBackendCollection(SearchType.Disk)); } @Override public DiskResource getDeviceSubResource(String id) { return inject(new BackendDiskResource(id)); } @Override protected Response performRemove(String id) { return performAction(VdcActionType.RemoveDisk, new RemoveDiskParameters(Guid.createGuidFromString(id))); } protected Disks mapCollection(List<org.ovirt.engine.core.common.businessentities.Disk> entities) { Disks collection = new Disks(); for (org.ovirt.engine.core.common.businessentities.Disk disk : entities) { collection.getDisks().add(addLinks(map(disk))); } return collection; } }
true
true
public Response add(Disk disk) { validateParameters(disk, "size", "format", "interface"); AddDiskParameters params = new AddDiskParameters(); params.setDiskInfo(getMapper(Disk.class, org.ovirt.engine.core.common.businessentities.Disk.class).map(disk, null)); return performCreation(VdcActionType.AddDisk, params, new QueryIdResolver(VdcQueryType.GetDiskByDiskId, GetDiskByDiskIdParameters.class)); }
public Response add(Disk disk) { validateParameters(disk, "size", "format", "interface"); AddDiskParameters params = new AddDiskParameters(); params.setDiskInfo(getMapper(Disk.class, org.ovirt.engine.core.common.businessentities.Disk.class).map(disk, null)); if (disk.isSetStorageDomains() && disk.getStorageDomains().isSetStorageDomains() && disk.getStorageDomains().getStorageDomains().get(0).isSetId()) { params.setStorageDomainId(Guid.createGuidFromString(disk.getStorageDomains().getStorageDomains().get(0).getId())); } return performCreation(VdcActionType.AddDisk, params, new QueryIdResolver(VdcQueryType.GetDiskByDiskId, GetDiskByDiskIdParameters.class)); }
diff --git a/src/rtmp/cz/vity/freerapid/plugins/services/rtmp/DefaultPacketHandler.java b/src/rtmp/cz/vity/freerapid/plugins/services/rtmp/DefaultPacketHandler.java index 4acd3ca2..388bb62d 100644 --- a/src/rtmp/cz/vity/freerapid/plugins/services/rtmp/DefaultPacketHandler.java +++ b/src/rtmp/cz/vity/freerapid/plugins/services/rtmp/DefaultPacketHandler.java @@ -1,199 +1,202 @@ package cz.vity.freerapid.plugins.services.rtmp; import org.apache.mina.core.buffer.IoBuffer; import java.util.List; import java.util.logging.Logger; /** * @author Peter Thomas * @author ntoskrnl */ class DefaultPacketHandler implements PacketHandler { private final static Logger logger = Logger.getLogger(DefaultPacketHandler.class.getName()); private final static int BUFFER_TIME = 10 * 60 * 60 * 1000;//10 hours @Override public boolean handle(Packet packet, RtmpSession session) { IoBuffer data = packet.getData(); switch (packet.getHeader().getPacketType()) { case CHUNK_SIZE: int newChunkSize = data.getInt(); session.setChunkSize(newChunkSize); logger.fine("new chunk size is: " + newChunkSize); break; case CONTROL_MESSAGE: short type = data.getShort(); if (type == 6) { int time = data.getInt(); data.rewind(); logger.fine("server ping: " + packet); Packet pong = Packet.ping(7, time, -1); // 7 == pong type logger.fine("client pong: " + pong); session.send(pong); } else if (type == 0x001A) { logger.fine("server swf verification request: " + packet); + byte swfvType = data.get(2); + if (swfvType > 1) { + logger.warning("swf verification type " + swfvType + " not supported, attempting to use type 1"); + } byte[] swfv = session.getSwfVerification(); if (swfv == null) { - logger.warning("not sending swf verification response! connect parameters not set, server likely to stop responding"); + logger.warning("swf verification parameters not set, not sending response"); } else { Packet pong = Packet.swfVerification(swfv); logger.fine("sending client swf verification response: " + pong); session.send(pong); } } else if (type == 31) { logger.fine("Server sent BufferEmpty, sending pause"); if (session.getPauseMode() == 0) { final int time = session.getOutputWriter().getStatus().getVideoChannelTime(); session.setPauseTimestamp(time); session.send(new Invoke("pause", 8, null, true, time)); session.setPauseMode(1); } else if (session.getPauseMode() == 2) { logger.fine("Sending unpause"); session.send(new Invoke("pause", 8, null, false, session.getPauseTimestamp())); session.setPauseMode(3); } } else if (type == 32) { logger.fine("Server sent BufferReady"); } else if (type == 1) { logger.fine("Server sent Stream EOF"); if (session.getPauseMode() == 1) { session.setPauseMode(2); } } else { logger.fine("not handling unknown control message type: " + type + " " + packet); } break; case AUDIO_DATA: case VIDEO_DATA: session.getOutputWriter().write(packet); break; case FLV_DATA: session.getOutputWriter().writeFlvData(data); break; case NOTIFY: AmfObject notify = new AmfObject(); notify.decode(data, false); String notifyMethod = notify.getFirstPropertyAsString(); logger.fine("server notify: " + notify); if (notifyMethod.equals("onMetaData")) { logger.fine("notify is 'onMetadata', writing metadata"); data.rewind(); session.getOutputWriter().write(packet); List<AmfProperty> properties = notify.getProperties(); if (properties != null && properties.size() >= 2) { AmfProperty property = properties.get(1); if (property != null) { Object value = property.getValue(); if (value != null && value instanceof AmfObject) { AmfProperty pDuration = ((AmfObject) value).getProperty("duration"); if (pDuration != null) { Object oDuration = pDuration.getValue(); if (oDuration != null && oDuration instanceof Double) { double duration = (Double) oDuration; logger.fine("Stream duration: " + duration + " seconds"); session.setStreamDuration((int) (duration * 1000)); } } } } } } break; case INVOKE: Invoke invoke = new Invoke(); invoke.decode(packet); String methodName = invoke.getMethodName(); if (methodName.equals("_result")) { String resultFor = session.getInvokedMethods().get(invoke.getSequenceId()); logger.fine("result for method call: " + resultFor); if (resultFor.equals("connect")) { if (session.getSecureToken() != null) { AmfObject amf = invoke.getSecondArgAsAmfObject(); if (amf != null) { AmfProperty amfprop = amf.getProperty("secureToken"); String secureToken = null; if (amfprop != null) { secureToken = (String) amfprop.getValue(); } if (secureToken != null) { logger.info("Sending secureToken challenge response"); session.send(new Invoke("secureTokenResponse", 3, null, XXTEA.decrypt(secureToken, session.getSecureToken()))); } } } session.send(Packet.serverBw(2500000)); // hard coded for now session.send(new Invoke("createStream", 3)); } else if (resultFor.equals("createStream")) { int streamId = invoke.getLastArgAsInt(); logger.fine("value of streamId to play: " + streamId); - Invoke play = new Invoke(streamId, "play", 8, null, - session.getPlayName(), session.getPlayStart(), session.getPlayDuration()); + Invoke play = new Invoke(streamId, "play", 8, null, session.getPlayName()); session.send(play); session.send(Packet.ping(3, streamId, BUFFER_TIME)); } else if (resultFor.equals("secureTokenResponse")) { logger.fine("server sent response for secureTokenResponse"); } else { logger.warning("unhandled server result for: " + resultFor); } } else if (methodName.equals("onStatus")) { AmfObject temp = invoke.getSecondArgAsAmfObject(); String code = (String) temp.getProperty("code").getValue(); logger.fine("onStatus code: " + code); if (code.equals("NetStream.Failed") || code.equals("NetStream.Play.Failed") || code.equals("NetStream.Play.Stop") || code.equals("NetStream.Play.StreamNotFound") || code.equals("NetConnection.Connect.InvalidApp")) { logger.fine("disconnecting"); session.getDecoderOutput().disconnect(); } else if (code.equals("NetStream.Pause.Notify")) { if (session.getPauseMode() == 1 || session.getPauseMode() == 2) { logger.fine("Sending unpause"); session.send(new Invoke("pause", 8, null, false, session.getPauseTimestamp())); session.setPauseMode(3); } } } else if (methodName.equals("onBWDone")) { if (session.getBwCheckCounter() == 0) { logger.fine("Server invoked onBWDone, invoking _checkbw"); Invoke checkbw = new Invoke("_checkbw", 3); session.send(checkbw); session.getInvokedMethods().remove(checkbw.getSequenceId()); } else { logger.fine("Server invoked onBWDone, ignoring"); } } else if (methodName.equals("_onbwcheck")) { logger.fine("Server invoked _onbwcheck, invoking _result"); int bwCheckCounter = session.getBwCheckCounter(); Header header = new Header(Header.Type.MEDIUM, 3, Packet.Type.INVOKE); header.setTime(0x16 * bwCheckCounter); IoBuffer body = AmfProperty.encode("_result", invoke.getSequenceId(), null, bwCheckCounter); Packet result = new Packet(header, body); logger.fine("Sending _onbwcheck result: " + result); session.send(result); session.setBwCheckCounter(bwCheckCounter + 1); } else if (methodName.equals("_onbwdone")) { logger.fine("Server invoked _onbwdone"); } else if (methodName.equals("_error")) { logger.warning("Server sent error: " + invoke); } else if (methodName.equals("close")) { logger.fine("Server requested close, disconnecting"); session.getDecoderOutput().disconnect(); } else { logger.fine("unhandled server invoke: " + invoke); } break; case BYTES_READ: case SERVER_BANDWIDTH: case CLIENT_BANDWIDTH: logger.fine("ignoring received packet: " + packet.getHeader()); break; default: throw new RuntimeException("unknown packet type: " + packet.getHeader()); } return true; } }
false
true
public boolean handle(Packet packet, RtmpSession session) { IoBuffer data = packet.getData(); switch (packet.getHeader().getPacketType()) { case CHUNK_SIZE: int newChunkSize = data.getInt(); session.setChunkSize(newChunkSize); logger.fine("new chunk size is: " + newChunkSize); break; case CONTROL_MESSAGE: short type = data.getShort(); if (type == 6) { int time = data.getInt(); data.rewind(); logger.fine("server ping: " + packet); Packet pong = Packet.ping(7, time, -1); // 7 == pong type logger.fine("client pong: " + pong); session.send(pong); } else if (type == 0x001A) { logger.fine("server swf verification request: " + packet); byte[] swfv = session.getSwfVerification(); if (swfv == null) { logger.warning("not sending swf verification response! connect parameters not set, server likely to stop responding"); } else { Packet pong = Packet.swfVerification(swfv); logger.fine("sending client swf verification response: " + pong); session.send(pong); } } else if (type == 31) { logger.fine("Server sent BufferEmpty, sending pause"); if (session.getPauseMode() == 0) { final int time = session.getOutputWriter().getStatus().getVideoChannelTime(); session.setPauseTimestamp(time); session.send(new Invoke("pause", 8, null, true, time)); session.setPauseMode(1); } else if (session.getPauseMode() == 2) { logger.fine("Sending unpause"); session.send(new Invoke("pause", 8, null, false, session.getPauseTimestamp())); session.setPauseMode(3); } } else if (type == 32) { logger.fine("Server sent BufferReady"); } else if (type == 1) { logger.fine("Server sent Stream EOF"); if (session.getPauseMode() == 1) { session.setPauseMode(2); } } else { logger.fine("not handling unknown control message type: " + type + " " + packet); } break; case AUDIO_DATA: case VIDEO_DATA: session.getOutputWriter().write(packet); break; case FLV_DATA: session.getOutputWriter().writeFlvData(data); break; case NOTIFY: AmfObject notify = new AmfObject(); notify.decode(data, false); String notifyMethod = notify.getFirstPropertyAsString(); logger.fine("server notify: " + notify); if (notifyMethod.equals("onMetaData")) { logger.fine("notify is 'onMetadata', writing metadata"); data.rewind(); session.getOutputWriter().write(packet); List<AmfProperty> properties = notify.getProperties(); if (properties != null && properties.size() >= 2) { AmfProperty property = properties.get(1); if (property != null) { Object value = property.getValue(); if (value != null && value instanceof AmfObject) { AmfProperty pDuration = ((AmfObject) value).getProperty("duration"); if (pDuration != null) { Object oDuration = pDuration.getValue(); if (oDuration != null && oDuration instanceof Double) { double duration = (Double) oDuration; logger.fine("Stream duration: " + duration + " seconds"); session.setStreamDuration((int) (duration * 1000)); } } } } } } break; case INVOKE: Invoke invoke = new Invoke(); invoke.decode(packet); String methodName = invoke.getMethodName(); if (methodName.equals("_result")) { String resultFor = session.getInvokedMethods().get(invoke.getSequenceId()); logger.fine("result for method call: " + resultFor); if (resultFor.equals("connect")) { if (session.getSecureToken() != null) { AmfObject amf = invoke.getSecondArgAsAmfObject(); if (amf != null) { AmfProperty amfprop = amf.getProperty("secureToken"); String secureToken = null; if (amfprop != null) { secureToken = (String) amfprop.getValue(); } if (secureToken != null) { logger.info("Sending secureToken challenge response"); session.send(new Invoke("secureTokenResponse", 3, null, XXTEA.decrypt(secureToken, session.getSecureToken()))); } } } session.send(Packet.serverBw(2500000)); // hard coded for now session.send(new Invoke("createStream", 3)); } else if (resultFor.equals("createStream")) { int streamId = invoke.getLastArgAsInt(); logger.fine("value of streamId to play: " + streamId); Invoke play = new Invoke(streamId, "play", 8, null, session.getPlayName(), session.getPlayStart(), session.getPlayDuration()); session.send(play); session.send(Packet.ping(3, streamId, BUFFER_TIME)); } else if (resultFor.equals("secureTokenResponse")) { logger.fine("server sent response for secureTokenResponse"); } else { logger.warning("unhandled server result for: " + resultFor); } } else if (methodName.equals("onStatus")) { AmfObject temp = invoke.getSecondArgAsAmfObject(); String code = (String) temp.getProperty("code").getValue(); logger.fine("onStatus code: " + code); if (code.equals("NetStream.Failed") || code.equals("NetStream.Play.Failed") || code.equals("NetStream.Play.Stop") || code.equals("NetStream.Play.StreamNotFound") || code.equals("NetConnection.Connect.InvalidApp")) { logger.fine("disconnecting"); session.getDecoderOutput().disconnect(); } else if (code.equals("NetStream.Pause.Notify")) { if (session.getPauseMode() == 1 || session.getPauseMode() == 2) { logger.fine("Sending unpause"); session.send(new Invoke("pause", 8, null, false, session.getPauseTimestamp())); session.setPauseMode(3); } } } else if (methodName.equals("onBWDone")) { if (session.getBwCheckCounter() == 0) { logger.fine("Server invoked onBWDone, invoking _checkbw"); Invoke checkbw = new Invoke("_checkbw", 3); session.send(checkbw); session.getInvokedMethods().remove(checkbw.getSequenceId()); } else { logger.fine("Server invoked onBWDone, ignoring"); } } else if (methodName.equals("_onbwcheck")) { logger.fine("Server invoked _onbwcheck, invoking _result"); int bwCheckCounter = session.getBwCheckCounter(); Header header = new Header(Header.Type.MEDIUM, 3, Packet.Type.INVOKE); header.setTime(0x16 * bwCheckCounter); IoBuffer body = AmfProperty.encode("_result", invoke.getSequenceId(), null, bwCheckCounter); Packet result = new Packet(header, body); logger.fine("Sending _onbwcheck result: " + result); session.send(result); session.setBwCheckCounter(bwCheckCounter + 1); } else if (methodName.equals("_onbwdone")) { logger.fine("Server invoked _onbwdone"); } else if (methodName.equals("_error")) { logger.warning("Server sent error: " + invoke); } else if (methodName.equals("close")) { logger.fine("Server requested close, disconnecting"); session.getDecoderOutput().disconnect(); } else { logger.fine("unhandled server invoke: " + invoke); } break; case BYTES_READ: case SERVER_BANDWIDTH: case CLIENT_BANDWIDTH: logger.fine("ignoring received packet: " + packet.getHeader()); break; default: throw new RuntimeException("unknown packet type: " + packet.getHeader()); } return true; }
public boolean handle(Packet packet, RtmpSession session) { IoBuffer data = packet.getData(); switch (packet.getHeader().getPacketType()) { case CHUNK_SIZE: int newChunkSize = data.getInt(); session.setChunkSize(newChunkSize); logger.fine("new chunk size is: " + newChunkSize); break; case CONTROL_MESSAGE: short type = data.getShort(); if (type == 6) { int time = data.getInt(); data.rewind(); logger.fine("server ping: " + packet); Packet pong = Packet.ping(7, time, -1); // 7 == pong type logger.fine("client pong: " + pong); session.send(pong); } else if (type == 0x001A) { logger.fine("server swf verification request: " + packet); byte swfvType = data.get(2); if (swfvType > 1) { logger.warning("swf verification type " + swfvType + " not supported, attempting to use type 1"); } byte[] swfv = session.getSwfVerification(); if (swfv == null) { logger.warning("swf verification parameters not set, not sending response"); } else { Packet pong = Packet.swfVerification(swfv); logger.fine("sending client swf verification response: " + pong); session.send(pong); } } else if (type == 31) { logger.fine("Server sent BufferEmpty, sending pause"); if (session.getPauseMode() == 0) { final int time = session.getOutputWriter().getStatus().getVideoChannelTime(); session.setPauseTimestamp(time); session.send(new Invoke("pause", 8, null, true, time)); session.setPauseMode(1); } else if (session.getPauseMode() == 2) { logger.fine("Sending unpause"); session.send(new Invoke("pause", 8, null, false, session.getPauseTimestamp())); session.setPauseMode(3); } } else if (type == 32) { logger.fine("Server sent BufferReady"); } else if (type == 1) { logger.fine("Server sent Stream EOF"); if (session.getPauseMode() == 1) { session.setPauseMode(2); } } else { logger.fine("not handling unknown control message type: " + type + " " + packet); } break; case AUDIO_DATA: case VIDEO_DATA: session.getOutputWriter().write(packet); break; case FLV_DATA: session.getOutputWriter().writeFlvData(data); break; case NOTIFY: AmfObject notify = new AmfObject(); notify.decode(data, false); String notifyMethod = notify.getFirstPropertyAsString(); logger.fine("server notify: " + notify); if (notifyMethod.equals("onMetaData")) { logger.fine("notify is 'onMetadata', writing metadata"); data.rewind(); session.getOutputWriter().write(packet); List<AmfProperty> properties = notify.getProperties(); if (properties != null && properties.size() >= 2) { AmfProperty property = properties.get(1); if (property != null) { Object value = property.getValue(); if (value != null && value instanceof AmfObject) { AmfProperty pDuration = ((AmfObject) value).getProperty("duration"); if (pDuration != null) { Object oDuration = pDuration.getValue(); if (oDuration != null && oDuration instanceof Double) { double duration = (Double) oDuration; logger.fine("Stream duration: " + duration + " seconds"); session.setStreamDuration((int) (duration * 1000)); } } } } } } break; case INVOKE: Invoke invoke = new Invoke(); invoke.decode(packet); String methodName = invoke.getMethodName(); if (methodName.equals("_result")) { String resultFor = session.getInvokedMethods().get(invoke.getSequenceId()); logger.fine("result for method call: " + resultFor); if (resultFor.equals("connect")) { if (session.getSecureToken() != null) { AmfObject amf = invoke.getSecondArgAsAmfObject(); if (amf != null) { AmfProperty amfprop = amf.getProperty("secureToken"); String secureToken = null; if (amfprop != null) { secureToken = (String) amfprop.getValue(); } if (secureToken != null) { logger.info("Sending secureToken challenge response"); session.send(new Invoke("secureTokenResponse", 3, null, XXTEA.decrypt(secureToken, session.getSecureToken()))); } } } session.send(Packet.serverBw(2500000)); // hard coded for now session.send(new Invoke("createStream", 3)); } else if (resultFor.equals("createStream")) { int streamId = invoke.getLastArgAsInt(); logger.fine("value of streamId to play: " + streamId); Invoke play = new Invoke(streamId, "play", 8, null, session.getPlayName()); session.send(play); session.send(Packet.ping(3, streamId, BUFFER_TIME)); } else if (resultFor.equals("secureTokenResponse")) { logger.fine("server sent response for secureTokenResponse"); } else { logger.warning("unhandled server result for: " + resultFor); } } else if (methodName.equals("onStatus")) { AmfObject temp = invoke.getSecondArgAsAmfObject(); String code = (String) temp.getProperty("code").getValue(); logger.fine("onStatus code: " + code); if (code.equals("NetStream.Failed") || code.equals("NetStream.Play.Failed") || code.equals("NetStream.Play.Stop") || code.equals("NetStream.Play.StreamNotFound") || code.equals("NetConnection.Connect.InvalidApp")) { logger.fine("disconnecting"); session.getDecoderOutput().disconnect(); } else if (code.equals("NetStream.Pause.Notify")) { if (session.getPauseMode() == 1 || session.getPauseMode() == 2) { logger.fine("Sending unpause"); session.send(new Invoke("pause", 8, null, false, session.getPauseTimestamp())); session.setPauseMode(3); } } } else if (methodName.equals("onBWDone")) { if (session.getBwCheckCounter() == 0) { logger.fine("Server invoked onBWDone, invoking _checkbw"); Invoke checkbw = new Invoke("_checkbw", 3); session.send(checkbw); session.getInvokedMethods().remove(checkbw.getSequenceId()); } else { logger.fine("Server invoked onBWDone, ignoring"); } } else if (methodName.equals("_onbwcheck")) { logger.fine("Server invoked _onbwcheck, invoking _result"); int bwCheckCounter = session.getBwCheckCounter(); Header header = new Header(Header.Type.MEDIUM, 3, Packet.Type.INVOKE); header.setTime(0x16 * bwCheckCounter); IoBuffer body = AmfProperty.encode("_result", invoke.getSequenceId(), null, bwCheckCounter); Packet result = new Packet(header, body); logger.fine("Sending _onbwcheck result: " + result); session.send(result); session.setBwCheckCounter(bwCheckCounter + 1); } else if (methodName.equals("_onbwdone")) { logger.fine("Server invoked _onbwdone"); } else if (methodName.equals("_error")) { logger.warning("Server sent error: " + invoke); } else if (methodName.equals("close")) { logger.fine("Server requested close, disconnecting"); session.getDecoderOutput().disconnect(); } else { logger.fine("unhandled server invoke: " + invoke); } break; case BYTES_READ: case SERVER_BANDWIDTH: case CLIENT_BANDWIDTH: logger.fine("ignoring received packet: " + packet.getHeader()); break; default: throw new RuntimeException("unknown packet type: " + packet.getHeader()); } return true; }
diff --git a/EasyMobArmory/src/main/java/com/runetooncraft/plugins/EasyMobArmory/egghandler/ZombieCache.java b/EasyMobArmory/src/main/java/com/runetooncraft/plugins/EasyMobArmory/egghandler/ZombieCache.java index 046bbcc..1c9a6cb 100644 --- a/EasyMobArmory/src/main/java/com/runetooncraft/plugins/EasyMobArmory/egghandler/ZombieCache.java +++ b/EasyMobArmory/src/main/java/com/runetooncraft/plugins/EasyMobArmory/egghandler/ZombieCache.java @@ -1,18 +1,18 @@ package com.runetooncraft.plugins.EasyMobArmory.egghandler; import org.bukkit.entity.Entity; import org.bukkit.inventory.ItemStack; import com.runetooncraft.plugins.EasyMobArmory.core.Messenger; public class ZombieCache { ItemStack[] Equip = null; ItemStack handitem = null; Boolean isbaby = null; ZombieCache(ItemStack[] equip, ItemStack handitem, Boolean isbaby) { Messenger.info("DEBUG! " + isbaby); - this.isbaby.equals(isbaby); - this.Equip.equals(equip); - this.handitem.equals(handitem); + this.isbaby = isbaby; + this.Equip = equip; + this.handitem = handitem; } }
true
true
ZombieCache(ItemStack[] equip, ItemStack handitem, Boolean isbaby) { Messenger.info("DEBUG! " + isbaby); this.isbaby.equals(isbaby); this.Equip.equals(equip); this.handitem.equals(handitem); }
ZombieCache(ItemStack[] equip, ItemStack handitem, Boolean isbaby) { Messenger.info("DEBUG! " + isbaby); this.isbaby = isbaby; this.Equip = equip; this.handitem = handitem; }
diff --git a/src/main/java/org/jinglenodes/component/SIPGatewayApplication.java b/src/main/java/org/jinglenodes/component/SIPGatewayApplication.java index 1001428..2d6a41c 100644 --- a/src/main/java/org/jinglenodes/component/SIPGatewayApplication.java +++ b/src/main/java/org/jinglenodes/component/SIPGatewayApplication.java @@ -1,129 +1,128 @@ /* * Copyright (C) 2011 - Jingle Nodes - Yuilop - Neppo * * This file is part of Switji (http://jinglenodes.org) * * Switji is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Switji is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MjSip; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author(s): * Benhur Langoni ([email protected]) * Thiago Camargo ([email protected]) */ package org.jinglenodes.component; import org.apache.log4j.Logger; import org.jinglenodes.jingle.processor.JingleProcessor; import org.jinglenodes.sip.processor.SipProcessor; import org.jivesoftware.whack.ExternalComponentManager; import org.xmpp.component.ComponentException; public class SIPGatewayApplication { private static final Logger log = Logger.getLogger(SIPGatewayApplication.class); private static final String DESCRIPTION = "SIP Gateway"; private String subdomain = "sip"; private SIPGatewayComponent sipGatewayComponent; private ExternalComponentManager manager; private JingleProcessor jingleProcessor; private SipProcessor sipProcessor; private String password; public SIPGatewayComponent getSipGatewayComponent() { return sipGatewayComponent; } public ExternalComponentManager getManager() { return manager; } public void setManager(ExternalComponentManager manager) { this.manager = manager; } public void setSipGatewayComponent(SIPGatewayComponent sipGatewayComponent) { this.sipGatewayComponent = sipGatewayComponent; } public String getSubdomain() { return subdomain; } public void setSubdomain(String subdomain) { this.subdomain = subdomain; } public JingleProcessor getJingleProcessor() { return jingleProcessor; } public void setJingleProcessor(JingleProcessor jingleProcessor) { this.jingleProcessor = jingleProcessor; } public SipProcessor getSipProcessor() { return sipProcessor; } public void setSipProcessor(SipProcessor sipProcessor) { this.sipProcessor = sipProcessor; } public void destroy() { try { manager.removeComponent(subdomain); } catch (ComponentException e) { log.error("Could Not Remove Component.", e); } if (sipGatewayComponent.getGatewaySipRouter() != null) { sipGatewayComponent.getGatewaySipRouter().shutdown(); sipGatewayComponent.shutdown(); } } public void init() { log.info("SIP Provider Info: " + sipGatewayComponent); int t = 2; while (true) { try { manager.setSecretKey(subdomain, password); manager.setMultipleAllowed(subdomain, false); manager.addComponent(subdomain, sipGatewayComponent); - sipGatewayComponent.init(); break; } catch (ComponentException e) { log.error("Connection Error... ", e); } log.info("Retrying Connection in " + (t * 1000) + "s"); try { Thread.sleep(t * 1000); } catch (InterruptedException e) { // Do Nothing } t = t * 2; if (t > 120) { t = 2; } } } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
true
true
public void init() { log.info("SIP Provider Info: " + sipGatewayComponent); int t = 2; while (true) { try { manager.setSecretKey(subdomain, password); manager.setMultipleAllowed(subdomain, false); manager.addComponent(subdomain, sipGatewayComponent); sipGatewayComponent.init(); break; } catch (ComponentException e) { log.error("Connection Error... ", e); } log.info("Retrying Connection in " + (t * 1000) + "s"); try { Thread.sleep(t * 1000); } catch (InterruptedException e) { // Do Nothing } t = t * 2; if (t > 120) { t = 2; } } }
public void init() { log.info("SIP Provider Info: " + sipGatewayComponent); int t = 2; while (true) { try { manager.setSecretKey(subdomain, password); manager.setMultipleAllowed(subdomain, false); manager.addComponent(subdomain, sipGatewayComponent); break; } catch (ComponentException e) { log.error("Connection Error... ", e); } log.info("Retrying Connection in " + (t * 1000) + "s"); try { Thread.sleep(t * 1000); } catch (InterruptedException e) { // Do Nothing } t = t * 2; if (t > 120) { t = 2; } } }
diff --git a/Schema/src/com/schema/bro/widget/CardWidget.java b/Schema/src/com/schema/bro/widget/CardWidget.java index 9a5c7c6..9bad0ad 100644 --- a/Schema/src/com/schema/bro/widget/CardWidget.java +++ b/Schema/src/com/schema/bro/widget/CardWidget.java @@ -1,114 +1,114 @@ package com.schema.bro.widget; import java.util.Calendar; import android.app.AlarmManager; import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.res.TypedArray; import android.util.Log; import android.widget.RemoteViews; import com.schema.bro.MainActivity; import com.schema.bro.R; import com.schema.bro.ks.Lesson; import com.schema.bro.ks.Schedule; public class CardWidget extends AppWidgetProvider { public static final String ACTION_UPDATE = "schema_update"; private static final int updateInterval = 60000; @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); Log.d("CardWidget:onReceive", "action: " + action); if (action.equals(CardWidget.ACTION_UPDATE)) { updateAppWidget(context, AppWidgetManager.getInstance(context), 0); }else { super.onReceive(context, intent); } } @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { Log.d("CardWidget:onUpdate", "called, number of instances " + appWidgetIds.length); for (int widgetId : appWidgetIds) { updateAppWidget(context, appWidgetManager, widgetId); } } @Override public void onEnabled(Context context) { super.onEnabled(context); Log.d("CardWidget:onEnabled", "Widget enabled!"); Intent intentUpdate = new Intent(context, CardWidget.class); intentUpdate.setAction(CardWidget.ACTION_UPDATE); PendingIntent pendingIntentAlarm = PendingIntent.getBroadcast(context, 0, intentUpdate, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); alarmManager.setRepeating(AlarmManager.RTC, System.currentTimeMillis(), updateInterval, pendingIntentAlarm); } @Override public void onDisabled(Context context) { super.onDisabled(context); Log.d("CardWidget:onDisabled", "Widget disabled!"); Intent intentUpdate = new Intent(context, CardWidget.class); intentUpdate.setAction(CardWidget.ACTION_UPDATE); PendingIntent pendingIntentAlarm = PendingIntent.getBroadcast(context, 0, intentUpdate, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); alarm.cancel(pendingIntentAlarm); } private void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId) { Schedule database = new Schedule(context); if(database.isEmpty()){ RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_no_lessons); Intent intent = new Intent(context, MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); remoteViews.setOnClickPendingIntent(R.id.cardWidget, pendingIntent); return; } RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_card); Intent intent = new Intent(context, MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); remoteViews.setOnClickPendingIntent(R.id.cardWidget, pendingIntent); Lesson lesson = database.getCurrentLesson(); TypedArray images = context.getResources().obtainTypedArray(R.array.imageIDs); remoteViews.setImageViewResource(R.id.cardLessonImage, images.getResourceId(lesson.getImage(), -1)); remoteViews.setTextViewText(R.id.cardLessonText, lesson.getName()); remoteViews.setTextViewText(R.id.cardTeacher, lesson.getMaster()); remoteViews.setTextViewText(R.id.cardStartTime, lesson.getStartTime()); remoteViews.setTextViewText(R.id.cardEndTime, lesson.getEndTime()); remoteViews.setTextViewText(R.id.cardRoom, lesson.getRoom()); Calendar c = Calendar.getInstance(); final int currentTime = c.get(Calendar.HOUR_OF_DAY) * 60 + c.get(Calendar.MINUTE); - final int lessonStartTime = (lesson.getEndHour() * 60 + lesson.getEndMinute() - currentTime); - if (currentTime < lessonStartTime) + final int lessonStartTime = (lesson.getStartHour() * 60 + lesson.getStartMinute()); + if (currentTime <= lessonStartTime) remoteViews.setTextViewText(R.id.cardTimeLeft,"Tid kvar: " + lesson.getTimeLeft(false) + "m"); else remoteViews.setTextViewText(R.id.cardTimeLeft,"Tid kvar: " + lesson.getTimeLeft(true) + "m"); images.recycle(); ComponentName schemaWidget = new ComponentName(context, CardWidget.class); AppWidgetManager.getInstance(context).updateAppWidget(schemaWidget, remoteViews); Log.i("CardWidget:updateAppWidget", "Widget updated!"); } }
true
true
private void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId) { Schedule database = new Schedule(context); if(database.isEmpty()){ RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_no_lessons); Intent intent = new Intent(context, MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); remoteViews.setOnClickPendingIntent(R.id.cardWidget, pendingIntent); return; } RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_card); Intent intent = new Intent(context, MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); remoteViews.setOnClickPendingIntent(R.id.cardWidget, pendingIntent); Lesson lesson = database.getCurrentLesson(); TypedArray images = context.getResources().obtainTypedArray(R.array.imageIDs); remoteViews.setImageViewResource(R.id.cardLessonImage, images.getResourceId(lesson.getImage(), -1)); remoteViews.setTextViewText(R.id.cardLessonText, lesson.getName()); remoteViews.setTextViewText(R.id.cardTeacher, lesson.getMaster()); remoteViews.setTextViewText(R.id.cardStartTime, lesson.getStartTime()); remoteViews.setTextViewText(R.id.cardEndTime, lesson.getEndTime()); remoteViews.setTextViewText(R.id.cardRoom, lesson.getRoom()); Calendar c = Calendar.getInstance(); final int currentTime = c.get(Calendar.HOUR_OF_DAY) * 60 + c.get(Calendar.MINUTE); final int lessonStartTime = (lesson.getEndHour() * 60 + lesson.getEndMinute() - currentTime); if (currentTime < lessonStartTime) remoteViews.setTextViewText(R.id.cardTimeLeft,"Tid kvar: " + lesson.getTimeLeft(false) + "m"); else remoteViews.setTextViewText(R.id.cardTimeLeft,"Tid kvar: " + lesson.getTimeLeft(true) + "m"); images.recycle(); ComponentName schemaWidget = new ComponentName(context, CardWidget.class); AppWidgetManager.getInstance(context).updateAppWidget(schemaWidget, remoteViews); Log.i("CardWidget:updateAppWidget", "Widget updated!"); }
private void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId) { Schedule database = new Schedule(context); if(database.isEmpty()){ RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_no_lessons); Intent intent = new Intent(context, MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); remoteViews.setOnClickPendingIntent(R.id.cardWidget, pendingIntent); return; } RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_card); Intent intent = new Intent(context, MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); remoteViews.setOnClickPendingIntent(R.id.cardWidget, pendingIntent); Lesson lesson = database.getCurrentLesson(); TypedArray images = context.getResources().obtainTypedArray(R.array.imageIDs); remoteViews.setImageViewResource(R.id.cardLessonImage, images.getResourceId(lesson.getImage(), -1)); remoteViews.setTextViewText(R.id.cardLessonText, lesson.getName()); remoteViews.setTextViewText(R.id.cardTeacher, lesson.getMaster()); remoteViews.setTextViewText(R.id.cardStartTime, lesson.getStartTime()); remoteViews.setTextViewText(R.id.cardEndTime, lesson.getEndTime()); remoteViews.setTextViewText(R.id.cardRoom, lesson.getRoom()); Calendar c = Calendar.getInstance(); final int currentTime = c.get(Calendar.HOUR_OF_DAY) * 60 + c.get(Calendar.MINUTE); final int lessonStartTime = (lesson.getStartHour() * 60 + lesson.getStartMinute()); if (currentTime <= lessonStartTime) remoteViews.setTextViewText(R.id.cardTimeLeft,"Tid kvar: " + lesson.getTimeLeft(false) + "m"); else remoteViews.setTextViewText(R.id.cardTimeLeft,"Tid kvar: " + lesson.getTimeLeft(true) + "m"); images.recycle(); ComponentName schemaWidget = new ComponentName(context, CardWidget.class); AppWidgetManager.getInstance(context).updateAppWidget(schemaWidget, remoteViews); Log.i("CardWidget:updateAppWidget", "Widget updated!"); }
diff --git a/src/test/java/com/eviware/soapui/impl/rest/support/RestUtilsTestCase.java b/src/test/java/com/eviware/soapui/impl/rest/support/RestUtilsTestCase.java index 7762cbe6d..a01617990 100644 --- a/src/test/java/com/eviware/soapui/impl/rest/support/RestUtilsTestCase.java +++ b/src/test/java/com/eviware/soapui/impl/rest/support/RestUtilsTestCase.java @@ -1,73 +1,74 @@ /* * soapUI, copyright (C) 2004-2012 smartbear.com * * soapUI is free software; you can redistribute it and/or modify it under the * terms of version 2.1 of the GNU Lesser General Public License as published by * the Free Software Foundation. * * soapUI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details at gnu.org. */ package com.eviware.soapui.impl.rest.support; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.io.File; import junit.framework.JUnit4TestAdapter; import org.junit.Test; import com.eviware.soapui.impl.rest.RestRequest; import com.eviware.soapui.impl.rest.RestRequestInterface; import com.eviware.soapui.impl.rest.RestResource; import com.eviware.soapui.impl.rest.RestService; import com.eviware.soapui.impl.rest.RestServiceFactory; import com.eviware.soapui.impl.wsdl.WsdlProject; public class RestUtilsTestCase { public static junit.framework.Test suite() { return new JUnit4TestAdapter( RestUtilsTestCase.class ); } @Test public void shouldExtractTemplateParams() throws Exception { String path = "/{id}/test/{test}/test"; String[] params = RestUtils.extractTemplateParams( path ); assertEquals( params.length, 2 ); assertEquals( "id", params[0] ); assertEquals( "test", params[1] ); } @Test public void shouldImportWadl() throws Exception { WsdlProject project = new WsdlProject(); RestService service = ( RestService )project.addNewInterface( "Test", RestServiceFactory.REST_TYPE ); - new WadlImporter( service ).initFromWadl( new File( "src" + File.separatorChar + "test-resources" + // TODO Hardcoded madness! + new WadlImporter( service ).initFromWadl( new File( "src" + File.separatorChar + "test" + File.separatorChar + "resources" + File.separatorChar + "wadl" + File.separatorChar + "YahooSearch.wadl" ).toURI().toURL().toString() ); assertEquals( 1, service.getOperationCount() ); assertEquals( "/NewsSearchService/V1/", service.getBasePath() ); RestResource resource = service.getOperationAt( 0 ); assertEquals( 1, resource.getPropertyCount() ); assertEquals( "appid", resource.getPropertyAt( 0 ).getName() ); assertNotNull( resource.getProperty( "appid" ) ); assertEquals( 1, resource.getRequestCount() ); RestRequest request = resource.getRequestAt( 0 ); assertEquals( RestRequestInterface.RequestMethod.GET, request.getMethod() ); assertEquals( 9, request.getPropertyCount() ); } }
true
true
public void shouldImportWadl() throws Exception { WsdlProject project = new WsdlProject(); RestService service = ( RestService )project.addNewInterface( "Test", RestServiceFactory.REST_TYPE ); new WadlImporter( service ).initFromWadl( new File( "src" + File.separatorChar + "test-resources" + File.separatorChar + "wadl" + File.separatorChar + "YahooSearch.wadl" ).toURI().toURL().toString() ); assertEquals( 1, service.getOperationCount() ); assertEquals( "/NewsSearchService/V1/", service.getBasePath() ); RestResource resource = service.getOperationAt( 0 ); assertEquals( 1, resource.getPropertyCount() ); assertEquals( "appid", resource.getPropertyAt( 0 ).getName() ); assertNotNull( resource.getProperty( "appid" ) ); assertEquals( 1, resource.getRequestCount() ); RestRequest request = resource.getRequestAt( 0 ); assertEquals( RestRequestInterface.RequestMethod.GET, request.getMethod() ); assertEquals( 9, request.getPropertyCount() ); }
public void shouldImportWadl() throws Exception { WsdlProject project = new WsdlProject(); RestService service = ( RestService )project.addNewInterface( "Test", RestServiceFactory.REST_TYPE ); // TODO Hardcoded madness! new WadlImporter( service ).initFromWadl( new File( "src" + File.separatorChar + "test" + File.separatorChar + "resources" + File.separatorChar + "wadl" + File.separatorChar + "YahooSearch.wadl" ).toURI().toURL().toString() ); assertEquals( 1, service.getOperationCount() ); assertEquals( "/NewsSearchService/V1/", service.getBasePath() ); RestResource resource = service.getOperationAt( 0 ); assertEquals( 1, resource.getPropertyCount() ); assertEquals( "appid", resource.getPropertyAt( 0 ).getName() ); assertNotNull( resource.getProperty( "appid" ) ); assertEquals( 1, resource.getRequestCount() ); RestRequest request = resource.getRequestAt( 0 ); assertEquals( RestRequestInterface.RequestMethod.GET, request.getMethod() ); assertEquals( 9, request.getPropertyCount() ); }
diff --git a/src/net/grinder/plugin/socket/SocketPlugin.java b/src/net/grinder/plugin/socket/SocketPlugin.java index a0109e55..81cf2926 100755 --- a/src/net/grinder/plugin/socket/SocketPlugin.java +++ b/src/net/grinder/plugin/socket/SocketPlugin.java @@ -1,239 +1,239 @@ // The Grinder // Copyright (C) 2001 Paco Gomez // Copyright (C) 2001 Philip Aston // Copyright (C) 2001 David Freels // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. package net.grinder.plugin.socket; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.Socket; import java.util.Date; import java.util.Set; import net.grinder.common.GrinderException; import net.grinder.common.GrinderProperties; import net.grinder.common.Test; import net.grinder.plugininterface.GrinderPlugin; import net.grinder.plugininterface.PluginException; import net.grinder.plugininterface.PluginProcessContext; import net.grinder.plugininterface.PluginThreadContext; import net.grinder.plugininterface.ThreadCallbacks; /** * Grinder Plugin that allows testing of socket based programs * * @author David Freels * @version $Revision$ */ public class SocketPlugin implements GrinderPlugin { private Set m_testsFromPropertiesFile; private String m_host = "localhost"; private int m_port = 7080; public void initialize(PluginProcessContext processContext, Set testsFromPropertiesFile) throws PluginException { m_testsFromPropertiesFile = testsFromPropertiesFile; final GrinderProperties parameters = processContext.getPluginParameters(); try { m_host = parameters.getMandatoryProperty("host"); m_port = parameters.getMandatoryInt("port"); } catch(GrinderException ge) { throw new PluginException("Missing property", ge); } } public Set getTests() { return m_testsFromPropertiesFile; } public ThreadCallbacks createThreadCallbackHandler() throws PluginException { return new SocketPluginThreadCallbacks(); } private class SocketPluginThreadCallbacks implements ThreadCallbacks { private PluginThreadContext m_pluginThreadContext = null; private Socket m_socket = null; private BufferedReader m_reader = null; private BufferedWriter m_writer = null; public void initialize(PluginThreadContext threadContext) { m_pluginThreadContext = threadContext; } /** * This is called for each method name in grinder.plugin.methods. */ public boolean doTest(Test testDefinition) throws PluginException { //Get the test parameters final GrinderProperties parameters = testDefinition.getParameters(); //Get the test number final int testName = testDefinition.getNumber(); /** * Multiple request/response operations could happen * during a single test, so we need to cycle through * each operation. */ //Message count int i = 0; //Look for the first request String requestFile = parameters.getProperty("request" + i, null); //If no request is found, abort if (requestFile == null) { throw new PluginException( "No request parameters have been set!"); } while (requestFile != null) { //Call method to load the next request and save the response sendRequest(requestFile, parameters.getProperty("response"+ i, "test" + testName + "response" + i + ".txt")); i++; //Get the next request file - requestFile = parameters.getProperty("request"+i, "nofile"); + requestFile = parameters.getProperty("request"+i, null); } return true; } /** * This method sends a request and records it the response the the file responseFile */ private void sendRequest(String requestFile, String responseFile) throws PluginException { try { //Read the contents of the file and send them to the server BufferedReader fis = new BufferedReader( new InputStreamReader( new FileInputStream(requestFile))); StringBuffer message = new StringBuffer(""); String line = ""; while( (line = fis.readLine()) != null) { message.append(line+"\n"); } m_writer.write(message.toString()); m_writer.flush(); fis.close(); //Read the response from the server and write it to a file message.delete(0, message.length()); line = ""; while((line = m_reader.readLine()) != null) { message.append(line+System.getProperty("line.separator")); } java.io.RandomAccessFile fos = new java.io.RandomAccessFile(responseFile, "rw"); fos.seek(fos.length()); fos.writeBytes(message.toString() + System.getProperty("line.separator")); fos.close(); } catch(java.io.IOException ioe) { throw new PluginException( "Error communicating with server", ioe); } } /** * This method is executed at the beginning of evey cycle. */ public void beginCycle() throws PluginException { //open the socket connection try { Date d = new Date(); m_socket = new Socket(m_host, m_port); m_pluginThreadContext.logMessage( "Time to connect to " + m_host + " took " + (new Date().getTime() - d.getTime())+" ms"); m_reader = new BufferedReader( new InputStreamReader(m_socket.getInputStream())); m_writer = new BufferedWriter( new OutputStreamWriter(m_socket.getOutputStream())); } catch(java.net.UnknownHostException uhe) { throw new PluginException("Cannot locate host "+ m_host, uhe); } catch(java.io.IOException ioe) { throw new PluginException("Unable to connect to host "+ m_host, ioe); } } /** * This method is executed at the end of every cycle. */ public void endCycle() throws PluginException { //close the socket connection if(m_socket != null) { try { m_socket.close(); m_reader.close(); m_writer.close(); } catch(java.io.IOException ioe) { throw new PluginException( "Error closing socket connection", ioe); } } } } }
true
true
public boolean doTest(Test testDefinition) throws PluginException { //Get the test parameters final GrinderProperties parameters = testDefinition.getParameters(); //Get the test number final int testName = testDefinition.getNumber(); /** * Multiple request/response operations could happen * during a single test, so we need to cycle through * each operation. */ //Message count int i = 0; //Look for the first request String requestFile = parameters.getProperty("request" + i, null); //If no request is found, abort if (requestFile == null) { throw new PluginException( "No request parameters have been set!"); } while (requestFile != null) { //Call method to load the next request and save the response sendRequest(requestFile, parameters.getProperty("response"+ i, "test" + testName + "response" + i + ".txt")); i++; //Get the next request file requestFile = parameters.getProperty("request"+i, "nofile"); } return true; }
public boolean doTest(Test testDefinition) throws PluginException { //Get the test parameters final GrinderProperties parameters = testDefinition.getParameters(); //Get the test number final int testName = testDefinition.getNumber(); /** * Multiple request/response operations could happen * during a single test, so we need to cycle through * each operation. */ //Message count int i = 0; //Look for the first request String requestFile = parameters.getProperty("request" + i, null); //If no request is found, abort if (requestFile == null) { throw new PluginException( "No request parameters have been set!"); } while (requestFile != null) { //Call method to load the next request and save the response sendRequest(requestFile, parameters.getProperty("response"+ i, "test" + testName + "response" + i + ".txt")); i++; //Get the next request file requestFile = parameters.getProperty("request"+i, null); } return true; }
diff --git a/src/edu/wheaton/simulator/entity/Agent.java b/src/edu/wheaton/simulator/entity/Agent.java index 6dd251b7..49e62ae3 100644 --- a/src/edu/wheaton/simulator/entity/Agent.java +++ b/src/edu/wheaton/simulator/entity/Agent.java @@ -1,230 +1,232 @@ /** * Agent.java * * Agents model actors in the simulation's Grid. * * @author Daniel Davenport, Grant Hensel, Elliot Penson, and Simon Swenson * Wheaton College, CSCI 335, Spring 2013 */ package edu.wheaton.simulator.entity; import java.awt.Color; import java.util.ArrayList; import java.util.Collections; import java.util.List; import net.sourceforge.jeval.EvaluationException; import edu.wheaton.simulator.datastructure.Grid; import edu.wheaton.simulator.simulation.SimulationPauseException; public class Agent extends GridEntity { /** * The list of all triggers/events associated with this agent. */ private List<Trigger> triggers; /** * Prototype of the agent */ private Prototype prototype; private final AgentID id = new AgentID(); private int currentTriggerIndex = 0; /** * Constructor. * * Makes an agent with the default gridEntity color * * @param g * The grid (passed to super constructor) */ public Agent(Grid g, Prototype prototype) { super(g); init(prototype); } /** * Constructor. Makes an agent with a solid color * * @param g * The grid (passed to super constructor) * @param c * The color of this agent (passed to super constructor) */ public Agent(Grid g, Prototype prototype, Color c) { super(g, c); init(prototype); } /** * Constructor. Makes an agent with custom color and color map * * @param g * The grid (passed to super constructor) * @param c * The color of this agent (passed to super constructor) * @param d * The design for this agent (passed to super constructor) */ public Agent(Grid g, Prototype prototype, Color c, byte[] d) { super(g, c, d); init(prototype); } private void init(Prototype p) { triggers = new ArrayList<Trigger>(); prototype = p; } /** * Causes this Agent to perform 1 action. All triggers with valid * conditions will fire. * * @throws Exception */ public void act() throws SimulationPauseException { for (Trigger t : triggers) try { t.evaluate(this); } catch (EvaluationException e) { System.err.println(e.getMessage()); String errorMessage = "Error in Agent: " + this.getName() + "\n ID: " + this.getID() + "\n Trigger: " + t.getName() + "\n MSG: " + e.getMessage() + "\n condition: " + t.getConditions().toString(); throw new SimulationPauseException(errorMessage); } } /** * Causes this Agent to perform only the triggers of the input priority * * @param priority: the priority of the triggers evaluated * @throws SimulationPauseException */ public void priorityAct(int priority) throws SimulationPauseException { - if (triggers.get(currentTriggerIndex).getPriority() > priority) { + if (triggers.size() < currentTriggerIndex || triggers.get(currentTriggerIndex).getPriority() > priority) { currentTriggerIndex = 0; } for (int i = currentTriggerIndex; i < triggers.size(); i++) { Trigger t = triggers.get(i); if (t.getPriority() == priority) { try { t.evaluate(this); } catch (EvaluationException e) { System.err.println(e.getMessage()); String errorMessage = "Error in Agent: " + this.getName() + "\n ID: " + this.getID() + "\n Trigger: " + t.getName() + "\n MSG: " + e.getMessage() + "\n condition: " + t.getConditions().toString(); throw new SimulationPauseException(errorMessage); } } else if (t.getPriority() > priority) { currentTriggerIndex = i - 1; + if (currentTriggerIndex < 0) + currentTriggerIndex = 0; return; } } } /** * Removes this Agent from the environment's list. */ public void die() { getGrid().removeAgent(getPosX(), getPosY()); } /** * Adds to the Agent's list of triggers * * @param trigger * The trigger to add */ public void addTrigger(Trigger trigger) { triggers.add(trigger); Collections.sort(triggers); } /** * Removes a trigger with the given priority (index in array list) * * @param priority * The priority of the given trigger to remove. */ public void removeTrigger(int priority) { triggers.remove(triggers.get(priority)); Collections.sort(triggers); } /** * Removes a trigger with the given name. * * @param name */ public void removeTrigger(String name) { for (int i = 0; i < triggers.size(); i++) if (getTriggerName(i).equals(name)) triggers.remove(i); } /** * Updates the trigger(s) with the given name * * @param name */ public void updateTrigger(String name, Trigger newT) { for (int i = 0; i < triggers.size(); i++) if (getTriggerName(i).equals(name)) triggers.set(i, newT); } private String getTriggerName(int index) { return triggers.get(index).getName(); } /** * Gets the current x position of this agent * * @return x */ public int getPosX() { return getField("x").getIntValue(); } /** * Gets the current y position of this agent * * @return y */ public int getPosY() { return getField("y").getIntValue(); } /** * Sets the Agent's new position * * @param x * @param y */ public void setPos(int x, int y) { updateField("x", x + ""); updateField("y", y + ""); } public Prototype getPrototype() { return prototype; } public String getName() { return getPrototype().getName(); } public AgentID getID() { return id; } }
false
true
public void priorityAct(int priority) throws SimulationPauseException { if (triggers.get(currentTriggerIndex).getPriority() > priority) { currentTriggerIndex = 0; } for (int i = currentTriggerIndex; i < triggers.size(); i++) { Trigger t = triggers.get(i); if (t.getPriority() == priority) { try { t.evaluate(this); } catch (EvaluationException e) { System.err.println(e.getMessage()); String errorMessage = "Error in Agent: " + this.getName() + "\n ID: " + this.getID() + "\n Trigger: " + t.getName() + "\n MSG: " + e.getMessage() + "\n condition: " + t.getConditions().toString(); throw new SimulationPauseException(errorMessage); } } else if (t.getPriority() > priority) { currentTriggerIndex = i - 1; return; } } }
public void priorityAct(int priority) throws SimulationPauseException { if (triggers.size() < currentTriggerIndex || triggers.get(currentTriggerIndex).getPriority() > priority) { currentTriggerIndex = 0; } for (int i = currentTriggerIndex; i < triggers.size(); i++) { Trigger t = triggers.get(i); if (t.getPriority() == priority) { try { t.evaluate(this); } catch (EvaluationException e) { System.err.println(e.getMessage()); String errorMessage = "Error in Agent: " + this.getName() + "\n ID: " + this.getID() + "\n Trigger: " + t.getName() + "\n MSG: " + e.getMessage() + "\n condition: " + t.getConditions().toString(); throw new SimulationPauseException(errorMessage); } } else if (t.getPriority() > priority) { currentTriggerIndex = i - 1; if (currentTriggerIndex < 0) currentTriggerIndex = 0; return; } } }
diff --git a/Essentials/src/com/earth2me/essentials/Settings.java b/Essentials/src/com/earth2me/essentials/Settings.java index 43b7dea3..067a58bf 100644 --- a/Essentials/src/com/earth2me/essentials/Settings.java +++ b/Essentials/src/com/earth2me/essentials/Settings.java @@ -1,995 +1,995 @@ package com.earth2me.essentials; import static com.earth2me.essentials.I18n._; import com.earth2me.essentials.commands.IEssentialsCommand; import com.earth2me.essentials.signs.EssentialsSign; import com.earth2me.essentials.signs.Signs; import com.earth2me.essentials.textreader.IText; import com.earth2me.essentials.textreader.SimpleTextInput; import java.io.File; import java.text.MessageFormat; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import org.bukkit.ChatColor; import org.bukkit.command.PluginCommand; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.MemoryConfiguration; import org.bukkit.event.EventPriority; import org.bukkit.inventory.ItemStack; public class Settings implements ISettings { private final transient EssentialsConf config; private final static Logger logger = Logger.getLogger("Minecraft"); private final transient IEssentials ess; private boolean metricsEnabled = true; public Settings(IEssentials ess) { this.ess = ess; config = new EssentialsConf(new File(ess.getDataFolder(), "config.yml")); config.setTemplateName("/config.yml"); reloadConfig(); } @Override public boolean getRespawnAtHome() { return config.getBoolean("respawn-at-home", false); } @Override public boolean getUpdateBedAtDaytime() { return config.getBoolean("update-bed-at-daytime", true); } @Override public Set<String> getMultipleHomes() { return config.getConfigurationSection("sethome-multiple").getKeys(false); } @Override public int getHomeLimit(final User user) { int limit = 1; if (user.isAuthorized("essentials.sethome.multiple")) { limit = getHomeLimit("default"); } final Set<String> homeList = getMultipleHomes(); if (homeList != null) { for (String set : homeList) { if (user.isAuthorized("essentials.sethome.multiple." + set) && (limit < getHomeLimit(set))) { limit = getHomeLimit(set); } } } return limit; } @Override public int getHomeLimit(final String set) { return config.getInt("sethome-multiple." + set, config.getInt("sethome-multiple.default", 3)); } private int chatRadius = 0; private int _getChatRadius() { return config.getInt("chat.radius", config.getInt("chat-radius", 0)); } @Override public int getChatRadius() { return chatRadius; } @Override public double getTeleportDelay() { return config.getDouble("teleport-delay", 0); } @Override public int getOversizedStackSize() { return config.getInt("oversized-stacksize", 64); } @Override public int getDefaultStackSize() { return config.getInt("default-stack-size", -1); } @Override public int getStartingBalance() { return config.getInt("starting-balance", 0); } @Override public boolean isCommandDisabled(final IEssentialsCommand cmd) { return isCommandDisabled(cmd.getName()); } private Set<String> disabledCommands = new HashSet<String>(); @Override public boolean isCommandDisabled(String label) { return disabledCommands.contains(label); } private Set<String> getDisabledCommands() { Set<String> disCommands = new HashSet<String>(); for (String c : config.getStringList("disabled-commands")) { disCommands.add(c.toLowerCase(Locale.ENGLISH)); } for (String c : config.getKeys(false)) { if (c.startsWith("disable-")) { disCommands.add(c.substring(8).toLowerCase(Locale.ENGLISH)); } } return disCommands; } @Override public boolean isPlayerCommand(String label) { for (String c : config.getStringList("player-commands")) { if (!c.equalsIgnoreCase(label)) { continue; } return true; } return false; } @Override public boolean isCommandOverridden(String name) { for (String c : config.getStringList("overridden-commands")) { if (!c.equalsIgnoreCase(name)) { continue; } return true; } return config.getBoolean("override-" + name.toLowerCase(Locale.ENGLISH), false); } private ConfigurationSection commandCosts; @Override public double getCommandCost(IEssentialsCommand cmd) { return getCommandCost(cmd.getName()); } public ConfigurationSection _getCommandCosts() { if (config.isConfigurationSection("command-costs")) { final ConfigurationSection section = config.getConfigurationSection("command-costs"); final ConfigurationSection newSection = new MemoryConfiguration(); for (String command : section.getKeys(false)) { PluginCommand cmd = ess.getServer().getPluginCommand(command); - if (cmd != null && !cmd.getPlugin().equals(ess)) + if (cmd != null && !cmd.getPlugin().equals(ess) && !isCommandOverridden(command)) { ess.getLogger().warning("Invalid command cost. '" + command + "' is not a command handled by Essentials."); } else if (command.charAt(0) == '/') { ess.getLogger().warning("Invalid command cost. '" + command + "' should not start with '/'."); } if (section.isDouble(command)) { newSection.set(command.toLowerCase(Locale.ENGLISH), section.getDouble(command)); } else if (section.isInt(command)) { newSection.set(command.toLowerCase(Locale.ENGLISH), (double)section.getInt(command)); } else if (section.isString(command)) { String costString = section.getString(command); try { double cost = Double.parseDouble(costString.trim().replace(getCurrencySymbol(), "").replaceAll("\\W", "")); newSection.set(command.toLowerCase(Locale.ENGLISH), cost); } catch (NumberFormatException ex) { ess.getLogger().warning("Invalid command cost for: " + command + " (" + costString + ")"); } } else { ess.getLogger().warning("Invalid command cost for: " + command); } } return newSection; } return null; } @Override public double getCommandCost(String name) { name = name.replace('.', '_').replace('/', '_'); if (commandCosts != null) { return commandCosts.getDouble(name, 0.0); } return 0.0; } private String nicknamePrefix = "~"; private String _getNicknamePrefix() { return config.getString("nickname-prefix", "~"); } @Override public String getNicknamePrefix() { return nicknamePrefix; } @Override public double getTeleportCooldown() { return config.getDouble("teleport-cooldown", 0); } @Override public double getHealCooldown() { return config.getDouble("heal-cooldown", 0); } private ConfigurationSection kits; public ConfigurationSection _getKits() { if (config.isConfigurationSection("kits")) { final ConfigurationSection section = config.getConfigurationSection("kits"); final ConfigurationSection newSection = new MemoryConfiguration(); for (String kitItem : section.getKeys(false)) { if (section.isConfigurationSection(kitItem)) { newSection.set(kitItem.toLowerCase(Locale.ENGLISH), section.getConfigurationSection(kitItem)); } } return newSection; } return null; } @Override public ConfigurationSection getKits() { return kits; } @Override public Map<String, Object> getKit(String name) { name = name.replace('.', '_').replace('/', '_'); if (getKits() != null) { final ConfigurationSection kits = getKits(); if (kits.isConfigurationSection(name)) { return kits.getConfigurationSection(name).getValues(true); } } return null; } private ChatColor operatorColor = null; @Override public ChatColor getOperatorColor() { return operatorColor; } private ChatColor _getOperatorColor() { String colorName = config.getString("ops-name-color", null); if (colorName == null) { return ChatColor.DARK_RED; } if ("none".equalsIgnoreCase(colorName) || colorName.isEmpty()) { return null; } try { return ChatColor.valueOf(colorName.toUpperCase(Locale.ENGLISH)); } catch (IllegalArgumentException ex) { } return ChatColor.getByChar(colorName); } @Override public int getSpawnMobLimit() { return config.getInt("spawnmob-limit", 10); } @Override public boolean showNonEssCommandsInHelp() { return config.getBoolean("non-ess-in-help", true); } @Override public boolean hidePermissionlessHelp() { return config.getBoolean("hide-permissionless-help", true); } @Override public int getProtectCreeperMaxHeight() { return config.getInt("protect.creeper.max-height", -1); } @Override public boolean areSignsDisabled() { return !signsEnabled; } @Override public long getBackupInterval() { return config.getInt("backup.interval", 1440); // 1440 = 24 * 60 } @Override public String getBackupCommand() { return config.getString("backup.command", null); } private Map<String, MessageFormat> chatFormats = Collections.synchronizedMap(new HashMap<String, MessageFormat>()); @Override public MessageFormat getChatFormat(String group) { MessageFormat mFormat = chatFormats.get(group); if (mFormat == null) { String format = config.getString("chat.group-formats." + (group == null ? "Default" : group), config.getString("chat.format", "&7[{GROUP}]&f {DISPLAYNAME}&7:&f {MESSAGE}")); format = Util.replaceFormat(format); format = format.replace("{DISPLAYNAME}", "%1$s"); format = format.replace("{GROUP}", "{0}"); format = format.replace("{MESSAGE}", "%2$s"); format = format.replace("{WORLDNAME}", "{1}"); format = format.replace("{SHORTWORLDNAME}", "{2}"); format = format.replaceAll("\\{(\\D*?)\\}", "\\[$1\\]"); format = "§r".concat(format); mFormat = new MessageFormat(format); chatFormats.put(group, mFormat); } return mFormat; } @Override public boolean getAnnounceNewPlayers() { return !config.getString("newbies.announce-format", "-").isEmpty(); } @Override public IText getAnnounceNewPlayerFormat() { return new SimpleTextInput(Util.replaceFormat(config.getString("newbies.announce-format", "&dWelcome {DISPLAYNAME} to the server!"))); } @Override public String getNewPlayerKit() { return config.getString("newbies.kit", ""); } @Override public String getNewbieSpawn() { return config.getString("newbies.spawnpoint", "default"); } @Override public boolean getPerWarpPermission() { return config.getBoolean("per-warp-permission", false); } @Override public boolean getSortListByGroups() { return config.getBoolean("sort-list-by-groups", true); } @Override public void reloadConfig() { config.load(); noGodWorlds = new HashSet<String>(config.getStringList("no-god-in-worlds")); enabledSigns = _getEnabledSigns(); teleportInvulnerability = _isTeleportInvulnerability(); disableItemPickupWhileAfk = _getDisableItemPickupWhileAfk(); registerBackInListener = _registerBackInListener(); cancelAfkOnMove = _cancelAfkOnMove(); getFreezeAfkPlayers = _getFreezeAfkPlayers(); itemSpawnBl = _getItemSpawnBlacklist(); loginAttackDelay = _getLoginAttackDelay(); signUsePerSecond = _getSignUsePerSecond(); kits = _getKits(); chatFormats.clear(); changeDisplayName = _changeDisplayName(); disabledCommands = getDisabledCommands(); nicknamePrefix = _getNicknamePrefix(); operatorColor = _getOperatorColor(); changePlayerListName = _changePlayerListName(); configDebug = _isDebug(); prefixsuffixconfigured = _isPrefixSuffixConfigured(); addprefixsuffix = _addPrefixSuffix(); disablePrefix = _disablePrefix(); disableSuffix = _disableSuffix(); chatRadius = _getChatRadius(); commandCosts = _getCommandCosts(); warnOnBuildDisallow = _warnOnBuildDisallow(); mailsPerMinute = _getMailsPerMinute(); } private List<Integer> itemSpawnBl = new ArrayList<Integer>(); @Override public List<Integer> itemSpawnBlacklist() { return itemSpawnBl; } private List<Integer> _getItemSpawnBlacklist() { final List<Integer> epItemSpwn = new ArrayList<Integer>(); if (ess.getItemDb() == null) { logger.log(Level.FINE, "Aborting ItemSpawnBL read, itemDB not yet loaded."); return epItemSpwn; } for (String itemName : config.getString("item-spawn-blacklist", "").split(",")) { itemName = itemName.trim(); if (itemName.isEmpty()) { continue; } try { final ItemStack iStack = ess.getItemDb().get(itemName); epItemSpwn.add(iStack.getTypeId()); } catch (Exception ex) { logger.log(Level.SEVERE, _("unknownItemInList", itemName, "item-spawn-blacklist")); } } return epItemSpwn; } private List<EssentialsSign> enabledSigns = new ArrayList<EssentialsSign>(); private boolean signsEnabled = false; @Override public List<EssentialsSign> enabledSigns() { return enabledSigns; } private List<EssentialsSign> _getEnabledSigns() { List<EssentialsSign> newSigns = new ArrayList<EssentialsSign>(); for (String signName : config.getStringList("enabledSigns")) { signName = signName.trim().toUpperCase(Locale.ENGLISH); if (signName.isEmpty()) { continue; } if (signName.equals("COLOR") || signName.equals("COLOUR")) { signsEnabled = true; continue; } try { newSigns.add(Signs.valueOf(signName).getSign()); } catch (Exception ex) { logger.log(Level.SEVERE, _("unknownItemInList", signName, "enabledSigns")); continue; } signsEnabled = true; } return newSigns; } private boolean warnOnBuildDisallow; private boolean _warnOnBuildDisallow() { return config.getBoolean("protect.disable.warn-on-build-disallow", false); } @Override public boolean warnOnBuildDisallow() { return warnOnBuildDisallow; } private boolean debug = false; private boolean configDebug = false; private boolean _isDebug() { return config.getBoolean("debug", false); } @Override public boolean isDebug() { return debug || configDebug; } @Override public boolean warnOnSmite() { return config.getBoolean("warn-on-smite", true); } @Override public boolean permissionBasedItemSpawn() { return config.getBoolean("permission-based-item-spawn", false); } @Override public String getLocale() { return config.getString("locale", ""); } //This method should always only return one character due to the implementation of the calling methods //If you need to use a string currency, for example "coins", use the translation key 'currency'. @Override public String getCurrencySymbol() { return config.getString("currency-symbol", "$").concat("$").substring(0, 1).replaceAll("[0-9]", "$"); } @Override public boolean isTradeInStacks(int id) { return config.getBoolean("trade-in-stacks-" + id, false); } @Override public boolean isEcoDisabled() { return config.getBoolean("disable-eco", false); } @Override public boolean getProtectPreventSpawn(final String creatureName) { return config.getBoolean("protect.prevent.spawn." + creatureName, false); } @Override public List<Integer> getProtectList(final String configName) { final List<Integer> list = new ArrayList<Integer>(); for (String itemName : config.getString(configName, "").split(",")) { itemName = itemName.trim(); if (itemName.isEmpty()) { continue; } ItemStack itemStack; try { itemStack = ess.getItemDb().get(itemName); list.add(itemStack.getTypeId()); } catch (Exception ex) { logger.log(Level.SEVERE, _("unknownItemInList", itemName, configName)); } } return list; } @Override public String getProtectString(final String configName) { return config.getString(configName, null); } @Override public boolean getProtectBoolean(final String configName, boolean def) { return config.getBoolean(configName, def); } private final static double MAXMONEY = 10000000000000.0; @Override public double getMaxMoney() { double max = config.getDouble("max-money", MAXMONEY); if (Math.abs(max) > MAXMONEY) { max = max < 0 ? -MAXMONEY : MAXMONEY; } return max; } private final static double MINMONEY = -10000000000000.0; @Override public double getMinMoney() { double min = config.getDouble("min-money", MINMONEY); if (min > 0) { min = -min; } if (min < MINMONEY) { min = MINMONEY; } return min; } @Override public boolean isEcoLogEnabled() { return config.getBoolean("economy-log-enabled", false); } @Override public boolean isEcoLogUpdateEnabled() { return config.getBoolean("economy-log-update-enabled", false); } @Override public boolean removeGodOnDisconnect() { return config.getBoolean("remove-god-on-disconnect", false); } private boolean changeDisplayName = true; private boolean _changeDisplayName() { return config.getBoolean("change-displayname", true); } @Override public boolean changeDisplayName() { return changeDisplayName; } private boolean changePlayerListName = false; private boolean _changePlayerListName() { return config.getBoolean("change-playerlist", false); } @Override public boolean changePlayerListName() { return changePlayerListName; } @Override public boolean useBukkitPermissions() { return config.getBoolean("use-bukkit-permissions", false); } private boolean prefixsuffixconfigured = false; private boolean addprefixsuffix = false; private boolean essentialsChatActive = false; private boolean _addPrefixSuffix() { return config.getBoolean("add-prefix-suffix", false); } private boolean _isPrefixSuffixConfigured() { return config.hasProperty("add-prefix-suffix"); } @Override public void setEssentialsChatActive(boolean essentialsChatActive) { this.essentialsChatActive = essentialsChatActive; } @Override public boolean addPrefixSuffix() { return prefixsuffixconfigured ? addprefixsuffix : essentialsChatActive; } private boolean disablePrefix = false; private boolean _disablePrefix() { return config.getBoolean("disablePrefix", false); } @Override public boolean disablePrefix() { return disablePrefix; } private boolean disableSuffix = false; private boolean _disableSuffix() { return config.getBoolean("disableSuffix", false); } @Override public boolean disableSuffix() { return disableSuffix; } @Override public long getAutoAfk() { return config.getLong("auto-afk", 300); } @Override public long getAutoAfkKick() { return config.getLong("auto-afk-kick", -1); } private boolean getFreezeAfkPlayers; @Override public boolean getFreezeAfkPlayers() { return getFreezeAfkPlayers; } private boolean _getFreezeAfkPlayers() { return config.getBoolean("freeze-afk-players", false); } private boolean cancelAfkOnMove; @Override public boolean cancelAfkOnMove() { return cancelAfkOnMove; } private boolean _cancelAfkOnMove() { return config.getBoolean("cancel-afk-on-move", true); } @Override public boolean areDeathMessagesEnabled() { return config.getBoolean("death-messages", true); } private Set<String> noGodWorlds = new HashSet<String>(); @Override public Set<String> getNoGodWorlds() { return noGodWorlds; } @Override public void setDebug(final boolean debug) { this.debug = debug; } @Override public boolean getRepairEnchanted() { return config.getBoolean("repair-enchanted", true); } @Override public boolean isWorldTeleportPermissions() { return config.getBoolean("world-teleport-permissions", false); } @Override public boolean isWorldHomePermissions() { return config.getBoolean("world-home-permissions", false); } private boolean registerBackInListener; @Override public boolean registerBackInListener() { return registerBackInListener; } private boolean _registerBackInListener() { return config.getBoolean("register-back-in-listener", false); } private boolean disableItemPickupWhileAfk; @Override public boolean getDisableItemPickupWhileAfk() { return disableItemPickupWhileAfk; } private boolean _getDisableItemPickupWhileAfk() { return config.getBoolean("disable-item-pickup-while-afk", false); } @Override public EventPriority getRespawnPriority() { String priority = config.getString("respawn-listener-priority", "normal").toLowerCase(Locale.ENGLISH); if ("lowest".equals(priority)) { return EventPriority.LOWEST; } if ("low".equals(priority)) { return EventPriority.LOW; } if ("normal".equals(priority)) { return EventPriority.NORMAL; } if ("high".equals(priority)) { return EventPriority.HIGH; } if ("highest".equals(priority)) { return EventPriority.HIGHEST; } return EventPriority.NORMAL; } @Override public long getTpaAcceptCancellation() { return config.getLong("tpa-accept-cancellation", 0); } @Override public boolean isMetricsEnabled() { return metricsEnabled; } @Override public void setMetricsEnabled(boolean metricsEnabled) { this.metricsEnabled = metricsEnabled; } private boolean teleportInvulnerability; @Override public long getTeleportInvulnerability() { return config.getLong("teleport-invulnerability", 0) * 1000; } private boolean _isTeleportInvulnerability() { return (config.getLong("teleport-invulnerability", 0) > 0); } @Override public boolean isTeleportInvulnerability() { return teleportInvulnerability; } private long loginAttackDelay; private long _getLoginAttackDelay() { return config.getLong("login-attack-delay", 0) * 1000; } @Override public long getLoginAttackDelay() { return loginAttackDelay; } private int signUsePerSecond; private int _getSignUsePerSecond() { final int perSec = config.getInt("sign-use-per-second", 4); return perSec > 0 ? perSec : 1; } @Override public int getSignUsePerSecond() { return signUsePerSecond; } @Override public double getMaxFlySpeed() { double maxSpeed = config.getDouble("max-fly-speed", 1.0); return maxSpeed > 1.0 ? 1.0 : Math.abs(maxSpeed); } //This option does not exist in the config.yml because it wasn't yet implemented in bukkit //The code was commented out in the /speed command @Override public double getMaxWalkSpeed() { double maxSpeed = config.getDouble("max-walk-speed", 0.8); return maxSpeed > 1.0 ? 1.0 : Math.abs(maxSpeed); } private int mailsPerMinute; private int _getMailsPerMinute() { return config.getInt("mails-per-minute", 1000); } @Override public int getMailsPerMinute() { return mailsPerMinute; } @Override public long getMaxTempban() { return config.getLong("max-tempban-time", -1); } }
true
true
public ConfigurationSection _getCommandCosts() { if (config.isConfigurationSection("command-costs")) { final ConfigurationSection section = config.getConfigurationSection("command-costs"); final ConfigurationSection newSection = new MemoryConfiguration(); for (String command : section.getKeys(false)) { PluginCommand cmd = ess.getServer().getPluginCommand(command); if (cmd != null && !cmd.getPlugin().equals(ess)) { ess.getLogger().warning("Invalid command cost. '" + command + "' is not a command handled by Essentials."); } else if (command.charAt(0) == '/') { ess.getLogger().warning("Invalid command cost. '" + command + "' should not start with '/'."); } if (section.isDouble(command)) { newSection.set(command.toLowerCase(Locale.ENGLISH), section.getDouble(command)); } else if (section.isInt(command)) { newSection.set(command.toLowerCase(Locale.ENGLISH), (double)section.getInt(command)); } else if (section.isString(command)) { String costString = section.getString(command); try { double cost = Double.parseDouble(costString.trim().replace(getCurrencySymbol(), "").replaceAll("\\W", "")); newSection.set(command.toLowerCase(Locale.ENGLISH), cost); } catch (NumberFormatException ex) { ess.getLogger().warning("Invalid command cost for: " + command + " (" + costString + ")"); } } else { ess.getLogger().warning("Invalid command cost for: " + command); } } return newSection; } return null; }
public ConfigurationSection _getCommandCosts() { if (config.isConfigurationSection("command-costs")) { final ConfigurationSection section = config.getConfigurationSection("command-costs"); final ConfigurationSection newSection = new MemoryConfiguration(); for (String command : section.getKeys(false)) { PluginCommand cmd = ess.getServer().getPluginCommand(command); if (cmd != null && !cmd.getPlugin().equals(ess) && !isCommandOverridden(command)) { ess.getLogger().warning("Invalid command cost. '" + command + "' is not a command handled by Essentials."); } else if (command.charAt(0) == '/') { ess.getLogger().warning("Invalid command cost. '" + command + "' should not start with '/'."); } if (section.isDouble(command)) { newSection.set(command.toLowerCase(Locale.ENGLISH), section.getDouble(command)); } else if (section.isInt(command)) { newSection.set(command.toLowerCase(Locale.ENGLISH), (double)section.getInt(command)); } else if (section.isString(command)) { String costString = section.getString(command); try { double cost = Double.parseDouble(costString.trim().replace(getCurrencySymbol(), "").replaceAll("\\W", "")); newSection.set(command.toLowerCase(Locale.ENGLISH), cost); } catch (NumberFormatException ex) { ess.getLogger().warning("Invalid command cost for: " + command + " (" + costString + ")"); } } else { ess.getLogger().warning("Invalid command cost for: " + command); } } return newSection; } return null; }
diff --git a/cyklotron-ui/src/main/java/net/cyklotron/cms/modules/actions/appearance/SelectScreenVariant.java b/cyklotron-ui/src/main/java/net/cyklotron/cms/modules/actions/appearance/SelectScreenVariant.java index 0b73b2691..dfbff446c 100644 --- a/cyklotron-ui/src/main/java/net/cyklotron/cms/modules/actions/appearance/SelectScreenVariant.java +++ b/cyklotron-ui/src/main/java/net/cyklotron/cms/modules/actions/appearance/SelectScreenVariant.java @@ -1,88 +1,88 @@ package net.cyklotron.cms.modules.actions.appearance; import org.jcontainer.dna.Logger; import org.objectledge.context.Context; import org.objectledge.coral.session.CoralSession; import org.objectledge.filesystem.FileSystem; import org.objectledge.parameters.Parameters; import org.objectledge.pipeline.ProcessingException; import org.objectledge.templating.TemplatingContext; import org.objectledge.web.HttpContext; import org.objectledge.web.mvc.MVCContext; import net.cyklotron.cms.CmsDataFactory; import net.cyklotron.cms.integration.IntegrationService; import net.cyklotron.cms.preferences.PreferencesService; import net.cyklotron.cms.site.SiteResource; import net.cyklotron.cms.skins.ScreenVariantResource; import net.cyklotron.cms.skins.SkinService; import net.cyklotron.cms.structure.NavigationNodeResource; import net.cyklotron.cms.structure.StructureService; import net.cyklotron.cms.style.StyleService; public class SelectScreenVariant extends BaseAppearanceAction { protected PreferencesService preferencesService; public SelectScreenVariant(Logger logger, StructureService structureService, CmsDataFactory cmsDataFactory, StyleService styleService, FileSystem fileSystem, SkinService skinService, IntegrationService integrationService, PreferencesService preferencesService) { super(logger, structureService, cmsDataFactory, styleService, fileSystem, skinService, integrationService); this.preferencesService = preferencesService; } public void execute(Context context, Parameters parameters, MVCContext mvcContext, TemplatingContext templatingContext, HttpContext httpContext, CoralSession coralSession) throws ProcessingException { SiteResource site = getSite(context); NavigationNodeResource node = getNode(context); Parameters prefs = preferencesService.getCombinedNodePreferences(coralSession, node); String app = prefs.get("screen.app",null); - String screen = prefs.get("screen.class",null); - String screenVariantKey = "screen.variant."+app+"."+screen.replace(',','.'); + String screen = prefs.get("screen.class",null).replace(',','.'); + String screenVariantKey = "screen.variant."+app+"."+screen; String currentVariant = prefs.get(screenVariantKey,"Default"); String newVariant = parameters.get("selected","Default"); if(currentVariant.equals(newVariant)) { return; } ScreenVariantResource[] variants; try { String skin = skinService.getCurrentSkin(coralSession, site); variants = skinService.getScreenVariants(coralSession, site, skin, app, screen); } catch(Exception e) { throw new ProcessingException("failed to retrieve variant information"); } boolean variantExists = false; for(int i=0; i<variants.length; i++) { if(variants[i].getName().equals(currentVariant)) { variantExists = true; break; } } if(variantExists) { prefs = preferencesService.getNodePreferences(node); prefs.set(screenVariantKey, newVariant); node.update(); } else { throw new ProcessingException("cannot set a non existant variant"); } } }
true
true
public void execute(Context context, Parameters parameters, MVCContext mvcContext, TemplatingContext templatingContext, HttpContext httpContext, CoralSession coralSession) throws ProcessingException { SiteResource site = getSite(context); NavigationNodeResource node = getNode(context); Parameters prefs = preferencesService.getCombinedNodePreferences(coralSession, node); String app = prefs.get("screen.app",null); String screen = prefs.get("screen.class",null); String screenVariantKey = "screen.variant."+app+"."+screen.replace(',','.'); String currentVariant = prefs.get(screenVariantKey,"Default"); String newVariant = parameters.get("selected","Default"); if(currentVariant.equals(newVariant)) { return; } ScreenVariantResource[] variants; try { String skin = skinService.getCurrentSkin(coralSession, site); variants = skinService.getScreenVariants(coralSession, site, skin, app, screen); } catch(Exception e) { throw new ProcessingException("failed to retrieve variant information"); } boolean variantExists = false; for(int i=0; i<variants.length; i++) { if(variants[i].getName().equals(currentVariant)) { variantExists = true; break; } } if(variantExists) { prefs = preferencesService.getNodePreferences(node); prefs.set(screenVariantKey, newVariant); node.update(); } else { throw new ProcessingException("cannot set a non existant variant"); } }
public void execute(Context context, Parameters parameters, MVCContext mvcContext, TemplatingContext templatingContext, HttpContext httpContext, CoralSession coralSession) throws ProcessingException { SiteResource site = getSite(context); NavigationNodeResource node = getNode(context); Parameters prefs = preferencesService.getCombinedNodePreferences(coralSession, node); String app = prefs.get("screen.app",null); String screen = prefs.get("screen.class",null).replace(',','.'); String screenVariantKey = "screen.variant."+app+"."+screen; String currentVariant = prefs.get(screenVariantKey,"Default"); String newVariant = parameters.get("selected","Default"); if(currentVariant.equals(newVariant)) { return; } ScreenVariantResource[] variants; try { String skin = skinService.getCurrentSkin(coralSession, site); variants = skinService.getScreenVariants(coralSession, site, skin, app, screen); } catch(Exception e) { throw new ProcessingException("failed to retrieve variant information"); } boolean variantExists = false; for(int i=0; i<variants.length; i++) { if(variants[i].getName().equals(currentVariant)) { variantExists = true; break; } } if(variantExists) { prefs = preferencesService.getNodePreferences(node); prefs.set(screenVariantKey, newVariant); node.update(); } else { throw new ProcessingException("cannot set a non existant variant"); } }
diff --git a/src/core/org/luaj/lib/BaseLib.java b/src/core/org/luaj/lib/BaseLib.java index f00d69b..7dfc333 100644 --- a/src/core/org/luaj/lib/BaseLib.java +++ b/src/core/org/luaj/lib/BaseLib.java @@ -1,445 +1,448 @@ /** * */ package org.luaj.lib; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import org.luaj.vm.CallInfo; import org.luaj.vm.LClosure; import org.luaj.vm.LFunction; import org.luaj.vm.LInteger; import org.luaj.vm.LNil; import org.luaj.vm.LNumber; import org.luaj.vm.LString; import org.luaj.vm.LTable; import org.luaj.vm.LValue; import org.luaj.vm.Lua; import org.luaj.vm.LuaState; import org.luaj.vm.Platform; public class BaseLib extends LFunction { public static InputStream STDIN = null; public static PrintStream STDOUT = System.out; private static PrintStream stdout = System.out; private static final String[] NAMES = { "base", "print", "pairs", "getmetatable", "setmetatable", "type", "pcall", "ipairs", "error", "assert", "loadfile", "tonumber", "rawget", "rawset", "setfenv", "select", "collectgarbage", "dofile", "loadstring", "load", "tostring", "unpack", "next", }; private static final int INSTALL = 0; private static final int PRINT = 1; private static final int PAIRS = 2; private static final int GETMETATABLE = 3; private static final int SETMETATABLE = 4; private static final int TYPE = 5; private static final int PCALL = 6; private static final int IPAIRS = 7; private static final int ERROR = 8; private static final int ASSERT = 9; private static final int LOADFILE = 10; private static final int TONUMBER = 11; private static final int RAWGET = 12; private static final int RAWSET = 13; private static final int SETFENV = 14; private static final int SELECT = 15; private static final int COLLECTGARBAGE = 16; private static final int DOFILE = 17; private static final int LOADSTRING = 18; private static final int LOAD = 19; private static final int TOSTRING = 20; private static final int UNPACK = 21; private static final int NEXT = 22; public static void install(LTable globals) { for ( int i=1; i<NAMES.length; i++ ) globals.put( NAMES[i], new BaseLib(i) ); } private int id; private BaseLib( int id ) { this.id = id; } public String toString() { return NAMES[id]+"()"; } private static void setResult( LuaState vm, LValue value ) { vm.settop(0); vm.pushlvalue( value ); } private static void setErrorResult( LuaState vm, String message ) { vm.settop(0); vm.pushnil(); vm.pushstring( message ); } public boolean luaStackCall(LuaState vm) { switch ( id ) { case PRINT: { int n = vm.gettop(); for ( int i=2; i<=n; i++ ) { if ( i > 2 ) stdout.print( "\t" ); stdout.print( vm.tostring(i) ); } stdout.println(); vm.settop(0); break; } case PAIRS: case IPAIRS: { LValue v = vm.topointer(2); LValue r = v.luaPairs(id==PAIRS); vm.settop(0); vm.pushlvalue( r ); break; } case GETMETATABLE: { - int r = vm.getmetatable(2); - vm.settop(0); - vm.pushinteger(r); + if ( 0 == vm.getmetatable(2) ) + vm.settop(0); + else { + vm.insert(1); + vm.settop(1); + } break; } case SETMETATABLE: { vm.setmetatable(2); vm.remove(1); break; } case TYPE: { LValue v = vm.topointer(2); vm.settop(0); vm.pushlstring( v.luaGetTypeName() ); break; } case PCALL: { int n = vm.gettop(); int s = vm.pcall( n-2, Lua.LUA_MULTRET, 0 ); if ( s == 0 ) { // success, results are on stack above the pcall vm.remove( 1 ); vm.pushboolean( true ); vm.insert( 1 ); } else { // error, error message is on the stack vm.pushboolean( false ); vm.insert( 1 ); } break; } case ERROR: { vm.error(vm.tostring(2), vm.gettop()>2? vm.tointeger(3): 1); break; } case ASSERT: { if ( ! vm.toboolean(2) ) vm.error( vm.gettop()>2? vm.tostring(3): "assertion failed!", 0 ); vm.remove(1); break; } case LOADFILE: loadfile(vm, vm.tostring(2)); break; case TONUMBER: { LValue input = vm.topointer(2); vm.settop(0); if ( input instanceof LNumber ) { vm.pushlvalue(input); } else if ( input instanceof LString ) { int base = 10; if ( vm.gettop()>=3 ) { base = vm.tointeger(3); } vm.pushlvalue( ( (LString) input ).luaToNumber( base ) ); } vm.pushnil(); break; } case RAWGET: { LValue t = vm.topointer(2); LValue k = vm.topointer(3); vm.settop(0); if ( t instanceof LTable ) { vm.pushlvalue(( (LTable) t ).get( k )); } } break; case RAWSET: { LValue t = vm.topointer(2); LValue k = vm.topointer(3); LValue v = vm.topointer(4); vm.settop(0); if ( t instanceof LTable ) { ( (LTable) t ).put( k, v ); } else { vm.error( "expected table" ); } } break; case SETFENV: setfenv( (LuaState) vm ); break; case SELECT: select( vm ); break; case COLLECTGARBAGE: System.gc(); vm.settop(0); break; case DOFILE: dofile(vm); break; case LOADSTRING: loadstring(vm, vm.topointer(2), vm.tostring(3)); break; case LOAD: load(vm, vm.topointer(2), vm.tostring(3)); break; case TOSTRING: { LValue v = vm.topointer(2); vm.settop(0); vm.pushlvalue( v.luaAsString() ); break; } case UNPACK: unpack(vm); break; case NEXT: { setResult( vm, next(vm, vm.topointer(2), vm.tointeger(3)) ); break; } default: luaUnsupportedOperation(); } return false; } public static void redirectOutput( OutputStream newStdOut ) { stdout = new PrintStream( newStdOut ); } public static void restoreStandardOutput() { stdout = System.out; } private void select( LuaState vm ) { LValue arg = vm.topointer(2); if ( arg instanceof LNumber ) { final int start = Math.min(arg.toJavaInt(),vm.gettop()); for ( int i=0; i<=start; i++ ) vm.remove(1); return; } else if ( arg.toJavaString().equals( "#" ) ) { setResult( vm, LInteger.valueOf( vm.gettop() - 2 ) ); } } private void setfenv( LuaState state ) { LValue f = state.topointer(2); LValue newenv = state.topointer(3); LClosure c = null; // Lua reference manual says that first argument, f, can be a "Lua // function" or an integer. Lots of things extend LFunction, but only // instances of Closure are "Lua functions". if ( f instanceof LClosure ) { c = (LClosure) f; } else { int callStackDepth = f.toJavaInt(); if ( callStackDepth > 0 ) { CallInfo frame = state.getStackFrame( callStackDepth ); if ( frame != null ) { c = frame.closure; } } else { // This is supposed to set the environment of the current // "thread". But, we have not implemented coroutines yet. throw new RuntimeException( "not implemented" ); } } if ( c != null ) { if ( newenv instanceof LTable ) { c.env = (LTable) newenv; } state.settop(0); state.pushlvalue( c ); return; } state.settop(0); return; } // closes the input stream, provided its not null or System.in private static void closeSafely(InputStream is) { try { if ( is != null && is != STDIN ) is.close(); } catch (IOException e) { e.printStackTrace(); } } // closes the output stream, provided its not null or STDOUT private static void closeSafely(OutputStream os) { try { if ( os != null && os != STDOUT ) os.close(); } catch (IOException e) { e.printStackTrace(); } } // return true if laoded, false if error put onto the stack private static boolean loadis(LuaState vm, InputStream is, String chunkname ) { try { vm.settop(0); if ( 0 != vm.load(is, chunkname) ) { setErrorResult( vm, "cannot load "+chunkname+": "+vm.topointer(-1) ); return false; } else { return true; } } finally { closeSafely( is ); } } // return true if loaded, false if error put onto stack public static boolean loadfile( LuaState vm, String fileName ) { InputStream is; String script; if ( ! "".equals(fileName) ) { script = fileName; is = Platform.getInstance().openFile(fileName); if ( is == null ) { setErrorResult( vm, "cannot open "+fileName+": No such file or directory" ); return false; } } else { is = STDIN; script = "-"; } // use vm to load the script return loadis( vm, is, script ); } // if load succeeds, return 0 for success, 1 for error (as per lua spec) private void dofile( LuaState vm ) { String filename = vm.tostring(2); if ( loadfile( vm, filename ) ) { int s = vm.pcall(1, 0, 0); setResult( vm, LInteger.valueOf( s!=0? 1: 0 ) ); } else { vm.error("cannot open "+filename); } } // return true if loaded, false if error put onto stack private boolean loadstring(LuaState vm, LValue string, String chunkname) { return loadis( vm, string.luaAsString().toInputStream(), ("".equals(chunkname)? "(string)": chunkname) ); } // return true if loaded, false if error put onto stack private boolean load(LuaState vm, LValue chunkPartLoader, String chunkname) { if ( ! (chunkPartLoader instanceof LClosure) ) { vm.error("not a closure: "+chunkPartLoader); } // load all the parts LClosure c = (LClosure) chunkPartLoader; ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { while ( true ) { setResult(vm,c); if ( 0 != vm.pcall(0, 1, 0) ) { setErrorResult(vm, vm.tostring(2)); return false; } LValue v = vm.topointer(2); if ( v == LNil.NIL ) break; LString s = v.luaAsString(); s.write(baos, 0, s.length()); } // load the chunk return loadis( vm, new ByteArrayInputStream( baos.toByteArray() ), ("".equals(chunkname)? "=(load)": chunkname) ); } catch (IOException ioe) { setErrorResult(vm, ioe.getMessage()); return false; } finally { closeSafely( baos ); } } /** unpack (list [, i [, j]]) * * Returns the elements from the given table. This function is equivalent to * return list[i], list[i+1], ···, list[j] * * except that the above code can be written only for a fixed number of elements. * By default, i is 1 and j is the length of the list, as defined by the length operator (see §2.5.5). */ private void unpack(LuaState vm) { LValue v = vm.topointer(2); int i = vm.tointeger(3); int j = vm.tointeger(4); LTable list = (LTable) v; if ( i == 0 ) i = 1; if ( j == 0 ) j = list.luaLength(); vm.settop(0); for ( int k=i; k<=j; k++ ) vm.pushlvalue( list.get(k) ); } private LValue next(LuaState vm, LValue table, int index) { throw new java.lang.RuntimeException("next() not supported yet"); } }
true
true
public boolean luaStackCall(LuaState vm) { switch ( id ) { case PRINT: { int n = vm.gettop(); for ( int i=2; i<=n; i++ ) { if ( i > 2 ) stdout.print( "\t" ); stdout.print( vm.tostring(i) ); } stdout.println(); vm.settop(0); break; } case PAIRS: case IPAIRS: { LValue v = vm.topointer(2); LValue r = v.luaPairs(id==PAIRS); vm.settop(0); vm.pushlvalue( r ); break; } case GETMETATABLE: { int r = vm.getmetatable(2); vm.settop(0); vm.pushinteger(r); break; } case SETMETATABLE: { vm.setmetatable(2); vm.remove(1); break; } case TYPE: { LValue v = vm.topointer(2); vm.settop(0); vm.pushlstring( v.luaGetTypeName() ); break; } case PCALL: { int n = vm.gettop(); int s = vm.pcall( n-2, Lua.LUA_MULTRET, 0 ); if ( s == 0 ) { // success, results are on stack above the pcall vm.remove( 1 ); vm.pushboolean( true ); vm.insert( 1 ); } else { // error, error message is on the stack vm.pushboolean( false ); vm.insert( 1 ); } break; } case ERROR: { vm.error(vm.tostring(2), vm.gettop()>2? vm.tointeger(3): 1); break; } case ASSERT: { if ( ! vm.toboolean(2) ) vm.error( vm.gettop()>2? vm.tostring(3): "assertion failed!", 0 ); vm.remove(1); break; } case LOADFILE: loadfile(vm, vm.tostring(2)); break; case TONUMBER: { LValue input = vm.topointer(2); vm.settop(0); if ( input instanceof LNumber ) { vm.pushlvalue(input); } else if ( input instanceof LString ) { int base = 10; if ( vm.gettop()>=3 ) { base = vm.tointeger(3); } vm.pushlvalue( ( (LString) input ).luaToNumber( base ) ); } vm.pushnil(); break; } case RAWGET: { LValue t = vm.topointer(2); LValue k = vm.topointer(3); vm.settop(0); if ( t instanceof LTable ) { vm.pushlvalue(( (LTable) t ).get( k )); } } break; case RAWSET: { LValue t = vm.topointer(2); LValue k = vm.topointer(3); LValue v = vm.topointer(4); vm.settop(0); if ( t instanceof LTable ) { ( (LTable) t ).put( k, v ); } else { vm.error( "expected table" ); } } break; case SETFENV: setfenv( (LuaState) vm ); break; case SELECT: select( vm ); break; case COLLECTGARBAGE: System.gc(); vm.settop(0); break; case DOFILE: dofile(vm); break; case LOADSTRING: loadstring(vm, vm.topointer(2), vm.tostring(3)); break; case LOAD: load(vm, vm.topointer(2), vm.tostring(3)); break; case TOSTRING: { LValue v = vm.topointer(2); vm.settop(0); vm.pushlvalue( v.luaAsString() ); break; } case UNPACK: unpack(vm); break; case NEXT: { setResult( vm, next(vm, vm.topointer(2), vm.tointeger(3)) ); break; } default: luaUnsupportedOperation(); } return false; }
public boolean luaStackCall(LuaState vm) { switch ( id ) { case PRINT: { int n = vm.gettop(); for ( int i=2; i<=n; i++ ) { if ( i > 2 ) stdout.print( "\t" ); stdout.print( vm.tostring(i) ); } stdout.println(); vm.settop(0); break; } case PAIRS: case IPAIRS: { LValue v = vm.topointer(2); LValue r = v.luaPairs(id==PAIRS); vm.settop(0); vm.pushlvalue( r ); break; } case GETMETATABLE: { if ( 0 == vm.getmetatable(2) ) vm.settop(0); else { vm.insert(1); vm.settop(1); } break; } case SETMETATABLE: { vm.setmetatable(2); vm.remove(1); break; } case TYPE: { LValue v = vm.topointer(2); vm.settop(0); vm.pushlstring( v.luaGetTypeName() ); break; } case PCALL: { int n = vm.gettop(); int s = vm.pcall( n-2, Lua.LUA_MULTRET, 0 ); if ( s == 0 ) { // success, results are on stack above the pcall vm.remove( 1 ); vm.pushboolean( true ); vm.insert( 1 ); } else { // error, error message is on the stack vm.pushboolean( false ); vm.insert( 1 ); } break; } case ERROR: { vm.error(vm.tostring(2), vm.gettop()>2? vm.tointeger(3): 1); break; } case ASSERT: { if ( ! vm.toboolean(2) ) vm.error( vm.gettop()>2? vm.tostring(3): "assertion failed!", 0 ); vm.remove(1); break; } case LOADFILE: loadfile(vm, vm.tostring(2)); break; case TONUMBER: { LValue input = vm.topointer(2); vm.settop(0); if ( input instanceof LNumber ) { vm.pushlvalue(input); } else if ( input instanceof LString ) { int base = 10; if ( vm.gettop()>=3 ) { base = vm.tointeger(3); } vm.pushlvalue( ( (LString) input ).luaToNumber( base ) ); } vm.pushnil(); break; } case RAWGET: { LValue t = vm.topointer(2); LValue k = vm.topointer(3); vm.settop(0); if ( t instanceof LTable ) { vm.pushlvalue(( (LTable) t ).get( k )); } } break; case RAWSET: { LValue t = vm.topointer(2); LValue k = vm.topointer(3); LValue v = vm.topointer(4); vm.settop(0); if ( t instanceof LTable ) { ( (LTable) t ).put( k, v ); } else { vm.error( "expected table" ); } } break; case SETFENV: setfenv( (LuaState) vm ); break; case SELECT: select( vm ); break; case COLLECTGARBAGE: System.gc(); vm.settop(0); break; case DOFILE: dofile(vm); break; case LOADSTRING: loadstring(vm, vm.topointer(2), vm.tostring(3)); break; case LOAD: load(vm, vm.topointer(2), vm.tostring(3)); break; case TOSTRING: { LValue v = vm.topointer(2); vm.settop(0); vm.pushlvalue( v.luaAsString() ); break; } case UNPACK: unpack(vm); break; case NEXT: { setResult( vm, next(vm, vm.topointer(2), vm.tointeger(3)) ); break; } default: luaUnsupportedOperation(); } return false; }
diff --git a/owsproxyclient/src/com/camptocamp/owsproxy/OWSClient.java b/owsproxyclient/src/com/camptocamp/owsproxy/OWSClient.java index 66bea60..a29f9ab 100644 --- a/owsproxyclient/src/com/camptocamp/owsproxy/OWSClient.java +++ b/owsproxyclient/src/com/camptocamp/owsproxy/OWSClient.java @@ -1,276 +1,275 @@ package com.camptocamp.owsproxy; import java.awt.Color; import java.awt.Component; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.ClipboardOwner; import java.awt.datatransfer.StringSelection; import java.awt.datatransfer.Transferable; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.net.MalformedURLException; import java.net.URL; import java.util.Observable; import java.util.Observer; import java.util.logging.Level; import javax.swing.JComponent; import owsproxyclient.OWSClientGUI; import owsproxyclient.ProxySettingsDialog; import owsproxyclient.State; import com.camptocamp.owsproxy.logging.OWSLogger; import com.camptocamp.owsproxy.parameters.ConnectionParameters; public class OWSClient implements Observer { ConnectionManager connManager; private owsproxyclient.OWSClientGUI client; Color textColor; private ProxySettingsDialog proxyDialog; /** The settings obtained from proxyDialog for configuring the proxy. This was added mainly so that * the cancel button on the proxyDialog could be implemented*/ private State proxySettings=new State("","",false,"",new char[0]); public OWSClient() { connManager = new ConnectionManager(); connManager.addObserver(this); java.awt.EventQueue.invokeLater(new Runnable() { public void run() { initGUI(); } }); } private void copyToClipboard(String text) { StringSelection selection = new StringSelection(text); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(selection, new ClipboardOwner() { public void lostOwnership(Clipboard clipboard, Transferable contents) { // ignored } }); } public void update(Observable observable, Object arg) { if (!(arg instanceof ConnectionEvent)) return; ConnectionEvent connEvent = (ConnectionEvent) arg; OWSLogger.DEV.finer("Got event: " + connEvent); client.proxyURL.setText(""); client.connectButton .setEnabled(connEvent.status == ConnectionEvent.ConnectionStatus.IDLE); client.disconnectButton .setEnabled(connEvent.status != ConnectionEvent.ConnectionStatus.IDLE); // resets state if (textColor == null) textColor = client.statusLabel.getForeground(); client.statusLabel.setForeground(textColor); JComponent proxyComponents[] = new JComponent[] { client.proxyUrlLabel, client.proxyUrlLabel, client.copyClipboardButton }; for (Component c : proxyComponents) { c.setEnabled(false); } client.statusLabel2.setText(" "); String msg; switch (connEvent.status) { case IDLE: msg = Translations.getString("OWSProxy_not_connected"); break; case CONNECTING: msg = Translations.getString("OWSProxy_not_connected"); break; case RUNNING: for (Component c : proxyComponents) { c.setEnabled(true); } client.statusLabel.setForeground(new Color(0, 128, 0)); msg = Translations.getString("Connected"); client.proxyURL.setText(connManager.getListeningAddress()); break; case UNAUTHORIZED: client.statusLabel.setForeground(Color.RED); msg = Translations.getString("Unauthorized"); client.statusLabel2.setText(connEvent.message); break; case ERROR: client.statusLabel.setForeground(Color.RED); msg = Translations.getString("Error"); client.statusLabel2.setText(connEvent.message); break; case PROXY_AUTH_REQUIRED: client.statusLabel.setForeground(Color.RED); msg = Translations.getString("Proxy_Auth"); client.statusLabel2.setText(connEvent.message); break; default: throw new RuntimeException("Should not happen: "+ connEvent); } client.statusLabel.setText(msg); OWSLogger.DEV.info("Event " + arg); if (OWSLogger.DEV.isLoggable(Level.FINER)) client.errorDetail.setText(arg.toString()); } private void initGUI() { client = new owsproxyclient.OWSClientGUI(); client.setVisible(true); client.errorDetail.setVisible(OWSLogger.DEV.isLoggable(Level.FINER)); if (OWSLogger.DEV.isLoggable(Level.FINER)) { client.serviceURL.setText("http://localhost"); client.usernameField.setText("tomcat"); client.passwordField.setText("tomcat"); } client.connectButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { new Thread(new Runnable() { public void run() { // XXX validate these fields String host = client.serviceURL.getText(); String username = client.usernameField.getText(); String password = new String(client.passwordField .getPassword()); String proxyHost = proxyDialog.url.getText().trim(); int proxyPort; String proxyUser = ""; String proxyPass = ""; if (proxyHost.length() == 0 || proxyHost.equals("http://")) { proxyHost = proxyUser = proxyPass = null; proxyPort = -1; } else { proxyPort = Integer.parseInt(proxyDialog.port .getText()); if (proxyDialog.useAuthentication.isSelected()) { proxyUser = proxyDialog.username.getText(); proxyPass = new String(proxyDialog.password .getPassword()); } } connManager.connect(new ConnectionParameters(host, username, password, proxyHost, proxyPort, proxyUser, proxyPass)); } }).start(); } }); client.validationLabel.setText(" "); client.serviceURL.addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent event) { String host = client.serviceURL.getText(); client.validationLabel.setText(" "); client.connectButton.setEnabled(true); try { new URL(host); } catch (MalformedURLException e) { client.connectButton.setEnabled(false); - String invalidURLMsg = java.util.ResourceBundle.getBundle( - "owsproxyclient/translations").getString( + String invalidURLMsg = Translations.getString( "Invalid_URL"); client.validationLabel.setText(invalidURLMsg); } } }); client.disconnectButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { connManager.disconnect(); } }); client.copyClipboardButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { copyToClipboard(client.proxyURL.getText()); } }); initAdvancedDialog(client); connManager.fireIdleEvent(); } private void initAdvancedDialog(OWSClientGUI client2) { this.proxyDialog = new ProxySettingsDialog(client, true); proxyDialog.okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { proxyDialog.setVisible(false); proxySettings=proxyDialog.copyState(); } }); proxyDialog.cancelButton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { State params = proxySettings; if( params.url.length()==0 ){ proxyDialog.url.setText("http://"); } else { proxyDialog.url.setText(params.url); } if( params.port.length()==0 ){ proxyDialog.port.setText("3128"); } else { proxyDialog.port.setText(String.valueOf(params.port)); } proxyDialog.useAuthentication.setSelected(params.useAuthentication); proxyDialog.username.setText(params.username); proxyDialog.password.setText(new String(params.password)); proxyDialog.validatePort(); } }); client.proxyButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { proxyDialog.setVisible(true); } }); } /** * @param args */ public static void main(String[] args) { new OWSClient(); } }
true
true
private void initGUI() { client = new owsproxyclient.OWSClientGUI(); client.setVisible(true); client.errorDetail.setVisible(OWSLogger.DEV.isLoggable(Level.FINER)); if (OWSLogger.DEV.isLoggable(Level.FINER)) { client.serviceURL.setText("http://localhost"); client.usernameField.setText("tomcat"); client.passwordField.setText("tomcat"); } client.connectButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { new Thread(new Runnable() { public void run() { // XXX validate these fields String host = client.serviceURL.getText(); String username = client.usernameField.getText(); String password = new String(client.passwordField .getPassword()); String proxyHost = proxyDialog.url.getText().trim(); int proxyPort; String proxyUser = ""; String proxyPass = ""; if (proxyHost.length() == 0 || proxyHost.equals("http://")) { proxyHost = proxyUser = proxyPass = null; proxyPort = -1; } else { proxyPort = Integer.parseInt(proxyDialog.port .getText()); if (proxyDialog.useAuthentication.isSelected()) { proxyUser = proxyDialog.username.getText(); proxyPass = new String(proxyDialog.password .getPassword()); } } connManager.connect(new ConnectionParameters(host, username, password, proxyHost, proxyPort, proxyUser, proxyPass)); } }).start(); } }); client.validationLabel.setText(" "); client.serviceURL.addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent event) { String host = client.serviceURL.getText(); client.validationLabel.setText(" "); client.connectButton.setEnabled(true); try { new URL(host); } catch (MalformedURLException e) { client.connectButton.setEnabled(false); String invalidURLMsg = java.util.ResourceBundle.getBundle( "owsproxyclient/translations").getString( "Invalid_URL"); client.validationLabel.setText(invalidURLMsg); } } }); client.disconnectButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { connManager.disconnect(); } }); client.copyClipboardButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { copyToClipboard(client.proxyURL.getText()); } }); initAdvancedDialog(client); connManager.fireIdleEvent(); }
private void initGUI() { client = new owsproxyclient.OWSClientGUI(); client.setVisible(true); client.errorDetail.setVisible(OWSLogger.DEV.isLoggable(Level.FINER)); if (OWSLogger.DEV.isLoggable(Level.FINER)) { client.serviceURL.setText("http://localhost"); client.usernameField.setText("tomcat"); client.passwordField.setText("tomcat"); } client.connectButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { new Thread(new Runnable() { public void run() { // XXX validate these fields String host = client.serviceURL.getText(); String username = client.usernameField.getText(); String password = new String(client.passwordField .getPassword()); String proxyHost = proxyDialog.url.getText().trim(); int proxyPort; String proxyUser = ""; String proxyPass = ""; if (proxyHost.length() == 0 || proxyHost.equals("http://")) { proxyHost = proxyUser = proxyPass = null; proxyPort = -1; } else { proxyPort = Integer.parseInt(proxyDialog.port .getText()); if (proxyDialog.useAuthentication.isSelected()) { proxyUser = proxyDialog.username.getText(); proxyPass = new String(proxyDialog.password .getPassword()); } } connManager.connect(new ConnectionParameters(host, username, password, proxyHost, proxyPort, proxyUser, proxyPass)); } }).start(); } }); client.validationLabel.setText(" "); client.serviceURL.addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent event) { String host = client.serviceURL.getText(); client.validationLabel.setText(" "); client.connectButton.setEnabled(true); try { new URL(host); } catch (MalformedURLException e) { client.connectButton.setEnabled(false); String invalidURLMsg = Translations.getString( "Invalid_URL"); client.validationLabel.setText(invalidURLMsg); } } }); client.disconnectButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { connManager.disconnect(); } }); client.copyClipboardButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { copyToClipboard(client.proxyURL.getText()); } }); initAdvancedDialog(client); connManager.fireIdleEvent(); }
diff --git a/src/java/net/sf/kraken/protocols/xmpp/packet/ProbePacket.java b/src/java/net/sf/kraken/protocols/xmpp/packet/ProbePacket.java index c58f5c7..b2cb5f6 100644 --- a/src/java/net/sf/kraken/protocols/xmpp/packet/ProbePacket.java +++ b/src/java/net/sf/kraken/protocols/xmpp/packet/ProbePacket.java @@ -1,47 +1,47 @@ /** * $Revision$ * $Date$ * * Copyright (C) 2008 Daniel Henninger. All rights reserved. * * This software is published under the terms of the GNU Public License (GPL), * a copy of which is included in this distribution. */ package net.sf.kraken.protocols.xmpp.packet; import org.jivesoftware.smack.packet.Packet; import org.jivesoftware.smack.util.StringUtils; /** * @author Daniel Henninger */ public class ProbePacket extends Packet { /** * Creates a new presence probe packet. * * @param from JID of presence requestor. * @param to JID to request presence of. */ public ProbePacket(String from, String to) { setTo(to); setFrom(from); } @Override public String toXML() { StringBuilder buf = new StringBuilder(); buf.append("<presence"); if (getTo() != null) { buf.append(" to=\"").append(StringUtils.escapeForXML(getTo())).append("\""); } - if (getFrom() != null) { - buf.append(" from=\"").append(StringUtils.escapeForXML(getFrom())).append("\""); - } + //if (getFrom() != null) { + // buf.append(" from=\"").append(StringUtils.escapeForXML(getFrom())).append("\""); + //} buf.append(" type=\"probe\""); buf.append("/>"); return buf.toString(); } }
true
true
public String toXML() { StringBuilder buf = new StringBuilder(); buf.append("<presence"); if (getTo() != null) { buf.append(" to=\"").append(StringUtils.escapeForXML(getTo())).append("\""); } if (getFrom() != null) { buf.append(" from=\"").append(StringUtils.escapeForXML(getFrom())).append("\""); } buf.append(" type=\"probe\""); buf.append("/>"); return buf.toString(); }
public String toXML() { StringBuilder buf = new StringBuilder(); buf.append("<presence"); if (getTo() != null) { buf.append(" to=\"").append(StringUtils.escapeForXML(getTo())).append("\""); } //if (getFrom() != null) { // buf.append(" from=\"").append(StringUtils.escapeForXML(getFrom())).append("\""); //} buf.append(" type=\"probe\""); buf.append("/>"); return buf.toString(); }
diff --git a/uCars/src/com/useful/ucars/ucars.java b/uCars/src/com/useful/ucars/ucars.java index 226fd9f..0bb3c50 100644 --- a/uCars/src/com/useful/ucars/ucars.java +++ b/uCars/src/com/useful/ucars/ucars.java @@ -1,537 +1,534 @@ package com.useful.ucars; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Level; import net.milkbowl.vault.economy.Economy; import org.bukkit.ChatColor; import org.bukkit.block.Block; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.java.JavaPlugin; import com.comphenix.protocol.ProtocolLibrary; import com.comphenix.protocol.ProtocolManager; import com.comphenix.protocol.events.ConnectionSide; import com.comphenix.protocol.events.ListenerPriority; import com.comphenix.protocol.events.PacketAdapter; import com.comphenix.protocol.events.PacketContainer; import com.comphenix.protocol.events.PacketEvent; public class ucars extends JavaPlugin { // The main file public static HashMap<String, Double> carBoosts = new HashMap<String, Double>(); public static HashMap<String, Double> fuel = new HashMap<String, Double>(); public static YamlConfiguration lang = new YamlConfiguration(); public static ucars plugin; public static FileConfiguration config; public static Boolean vault = false; public static Economy economy = null; public static Colors colors; public Boolean protocolLib = false; public Object protocolManager = null; public List<ItemStack> ufuelitems = new ArrayList<ItemStack>(); public ListStore licensedPlayers = null; public uCarsCommandExecutor cmdExecutor = null; public static uCarsListener listener = null; public static String colorise(String prefix) { return ChatColor.translateAlternateColorCodes('&', prefix); } public ListStore getLicensedPlayers(){ return this.licensedPlayers; } public void setLicensedPlayers(ListStore licensed){ this.licensedPlayers = licensed; return; } private void copy(InputStream in, File file) { try { OutputStream out = new FileOutputStream(file); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); // System.out.write(buf, 0, len); } out.close(); in.close(); } catch (Exception e) { e.printStackTrace(); } } @SuppressWarnings("unchecked") public static HashMap<String, Double> loadHashMapDouble(String path) { try { ObjectInputStream ois = new ObjectInputStream(new FileInputStream( path)); Object result = ois.readObject(); ois.close(); // you can feel free to cast result to HashMap<String, Integer> if // you know there's that HashMap in the file return (HashMap<String, Double>) result; } catch (Exception e) { e.printStackTrace(); return null; } } public static void saveHashMap(HashMap<String, Double> map, String path) { try { ObjectOutputStream oos = new ObjectOutputStream( new FileOutputStream(path)); oos.writeObject(map); oos.flush(); oos.close(); // Handle I/O exceptions } catch (Exception e) { e.printStackTrace(); } } private boolean setupEconomy() { RegisteredServiceProvider<Economy> economyProvider = getServer() .getServicesManager().getRegistration( net.milkbowl.vault.economy.Economy.class); if (economyProvider != null) { economy = economyProvider.getProvider(); } return (economy != null); } private Boolean setupProtocol(){ try { this.protocolLib = true; this.protocolManager = ProtocolLibrary.getProtocolManager(); ((ProtocolManager)this.protocolManager).addPacketListener(new PacketAdapter(plugin, ConnectionSide.CLIENT_SIDE, ListenerPriority.NORMAL, 0x1b) { @Override public void onPacketReceiving(PacketEvent event) { if (event.getPacketID() == 0x1b) { PacketContainer packet = event.getPacket(); float sideways = packet.getFloat().read(0); float forwards = packet.getFloat().read(1); new MotionManager(event.getPlayer(), forwards, sideways); } } }); } catch (Exception e) { return false; } return true; } public void onEnable() { plugin = this; File langFile = new File(getDataFolder().getAbsolutePath() + File.separator + "lang.yml"); if (langFile.exists() == false || langFile.length() < 1) { try { langFile.createNewFile(); // newC.save(configFile); } catch (IOException e) { } } try { lang.load(langFile); } catch (Exception e1) { getLogger().log(Level.WARNING, "Error creating/loading lang file! Regenerating.."); } if (new File(getDataFolder().getAbsolutePath() + File.separator + "config.yml").exists() == false || new File(getDataFolder().getAbsolutePath() + File.separator + "config.yml").length() < 1) { // YamlConfiguration newC = new YamlConfiguration(); // newC.set("time.created", System.currentTimeMillis()); File configFile = new File(getDataFolder().getAbsolutePath() + File.separator + "config.yml"); try { configFile.createNewFile(); // newC.save(configFile); } catch (IOException e) { } copy(getResource("ucarsConfigHeader.yml"), configFile); } config = getConfig(); try { // config.load(this.getDataFolder().getAbsolutePath() + // File.separator + "config.yml"); if (!config.contains("general.cars.# description")) { config.set("general.cars.# description", "If enabled this will allow for drivable cars(Minecarts not on rails)"); } if(!lang.contains("lang.messages.place")){ lang.set("lang.messages.place", "&eYou placed a car! Cars can be driven with similar controls to a horse!"); } if(!lang.contains("lang.error.pluginNull")){ lang.set("lang.error.pluginNull", "&4Error in ucars: Caused by: plugin = null? Report on bukkitdev immediately!"); } if(!lang.contains("lang.messages.noDrivePerm")){ lang.set("lang.messages.noDrivePerm", "You don't have the permission ucars.cars required to drive a car!"); } if(!lang.contains("lang.messages.noPlacePerm")){ lang.set("lang.messages.noPlacePerm", "You don't have the permission %perm% required to place a car!"); } if(!lang.contains("lang.messages.noPlaceHere")){ lang.set("lang.messages.noPlaceHere", "&4You are not allowed to place a car here!"); } if(!lang.contains("lang.messages.hitByCar")){ lang.set("lang.messages.hitByCar", "You were hit by a car!"); } if(!lang.contains("lang.cars.remove")){ lang.set("lang.cars.remove", "&e%amount%&a cars in world &e%world%&a were removed!"); } if(!lang.contains("lang.boosts.already")){ lang.set("lang.boosts.already", "&4Already boosting!"); } if(!lang.contains("lang.boosts.low")){ lang.set("lang.boosts.low", "Initiated low level boost!"); } if(!lang.contains("lang.boosts.med")){ lang.set("lang.boosts.med", "Initiated medium level boost!"); } if(!lang.contains("lang.boosts.high")){ lang.set("lang.boosts.high", "Initiated high level boost!"); } if(!lang.contains("lang.fuel.empty")){ lang.set("lang.fuel.empty", "You don't have any fuel left!"); } if(!lang.contains("lang.fuel.disabled")){ lang.set("lang.fuel.disabled", "Fuel is not enabled!"); } if(!lang.contains("lang.fuel.unit")){ lang.set("lang.fuel.unit", "litres"); } if(!lang.contains("lang.fuel.isItem")){ lang.set("lang.fuel.isItem", "&9[Important:]&eItem fuel is enabled-The above is irrelevant!"); } if(!lang.contains("lang.fuel.invalidAmount")){ lang.set("lang.fuel.invalidAmount", "Amount invalid!"); } if(!lang.contains("lang.fuel.noMoney")){ lang.set("lang.fuel.noMoney", "You have no money!"); } if(!lang.contains("lang.fuel.notEnoughMoney")){ lang.set("lang.fuel.notEnoughMoney", "That purchase costs %amount% %unit%! You only have %balance% %unit%!"); } if(!lang.contains("lang.fuel.success")){ lang.set("lang.fuel.success", "Successfully purchased %quantity% of fuel for %amount% %unit%! You now have %balance% %unit% left!"); } if(!lang.contains("lang.fuel.sellSuccess")){ lang.set("lang.fuel.sellSuccess", "Successfully sold %quantity% of fuel for %amount% %unit%! You now have %balance% %unit% left!"); } if(!lang.contains("lang.messages.rightClickWith")){ lang.set("lang.messages.rightClickWith", "Right click with "); } if(!lang.contains("lang.messages.driveOver")){ lang.set("lang.messages.driveOver", "Drive over "); } if(!lang.contains("lang.messages.playersOnly")){ lang.set("lang.messages.playersOnly", "Players only!"); } if(!lang.contains("lang.messages.reload")){ lang.set("lang.messages.reload", "The config has been reloaded!"); } if(!lang.contains("lang.messages.noProtocolLib")){ lang.set("lang.messages.noProtocolLib", "Hello operator, ProtocolLib (http://dev.bukkit.org/bukkit-plugins/protocollib/) was not detected and is required for ucars in MC 1.6 or higher. Please install it if necessary!"); } if(!lang.contains("lang.licenses.next")){ lang.set("lang.licenses.next", "Now do %command% to continue!"); } if(!lang.contains("lang.licenses.basics")){ lang.set("lang.licenses.basics", "A car is just a minecart placed on the ground, not rails. To place a car simply look and the floor while holding a minecart and right click!"); } if(!lang.contains("lang.licenses.controls")){ lang.set("lang.licenses.controls", "1) Look where you would like to go. 2) Use the 'w' key to go forward and 's' to go backwards. 3) Use the 'd' key to slow down/brake and the 'a' key to shoot a turret (if turret enabled)!"); } if(!lang.contains("lang.licenses.effects")){ lang.set("lang.licenses.effects", "Car speed can change depending on what block you may drive over. These can be short term boosts or a speedmod block. Do /ucars for more info on boosts!"); } if(!lang.contains("lang.licenses.itemBoosts")){ lang.set("lang.licenses.itemBoosts", "Right clicking with certain items can give you different boosts. Do /ucars for more info!"); } if(!lang.contains("lang.licenses.success")){ lang.set("lang.licenses.success", "Congratulations! You can now drive a ucar!"); } if(!lang.contains("lang.licenses.noLicense")){ lang.set("lang.licenses.noLicense", "To drive a car you need a license, do /ulicense to obtain one!"); } if (!config.contains("general.cars.enable")) { config.set("general.cars.enable", true); } if (!config.contains("general.permissions.enable")) { config.set("general.permissions.enable", true); } if (!config.contains("general.cars.defSpeed")) { config.set("general.cars.defSpeed", (double) 30); } if (!config.contains("general.cars.effectBlocks.enable")) { config.set("general.cars.effectBlocks.enable", true); } if (!config.contains("general.cars.lowBoost")) { config.set("general.cars.lowBoost", "263"); } if (!config.contains("general.cars.medBoost")) { config.set("general.cars.medBoost", "265"); } if (!config.contains("general.cars.highBoost")) { config.set("general.cars.highBoost", "264"); } if (!config.contains("general.cars.blockBoost")) { config.set("general.cars.blockBoost", "41"); } if (!config.contains("general.cars.HighblockBoost")) { config.set("general.cars.HighblockBoost", "57"); } if (!config.contains("general.cars.ResetblockBoost")) { config.set("general.cars.ResetblockBoost", "133"); } if (!config.contains("general.cars.turret")) { config.set("general.cars.turret", false); } if (!config.contains("general.cars.jumpBlock")) { config.set("general.cars.jumpBlock", "42"); } if (!config.contains("general.cars.jumpAmount")) { config.set("general.cars.jumpAmount", (double)60); } if (!config.contains("general.cars.teleportBlock")) { config.set("general.cars.teleportBlock", "159:2"); } if (!config.contains("general.cars.trafficLights.enable")) { config.set("general.cars.trafficLights.enable", true); } if (!config.contains("general.cars.trafficLights.waitingBlock")) { config.set("general.cars.trafficLights.waitingBlock", "155"); } if (!config.contains("general.cars.hitBy.enable")) { config.set("general.cars.hitBy.enable", false); } if (!config.contains("general.cars.hitBy.enableMonsterDamage")) { config.set("general.cars.hitBy.enableMonsterDamage", true); } if (!config.contains("general.cars.hitBy.power")) { config.set("general.cars.hitBy.power", (double) 5); } if (!config.contains("general.cars.hitBy.damage")) { config.set("general.cars.hitBy.damage", (double) 1.5); } if (!config.contains("general.cars.roadBlocks.enable")) { config.set("general.cars.roadBlocks.enable", false); } if (!config.contains("general.cars.roadBlocks.ids")) { config.set("general.cars.roadBlocks.ids", "35:15,35:8,35:0,35:7"); } if (!config.contains("general.cars.licenses.enable")) { config.set("general.cars.licenses.enable", false); } if (!config.contains("general.cars.fuel.enable")) { config.set("general.cars.fuel.enable", false); } if (!config.contains("general.cars.fuel.price")) { config.set("general.cars.fuel.price", (double) 2); } if (!config.contains("general.cars.fuel.check")) { config.set("general.cars.fuel.check", "288:0"); } if (!config.contains("general.cars.fuel.bypassPerm")) { config.set("general.cars.fuel.bypassPerm", "ucars.bypassfuel"); } if (!config.contains("general.cars.fuel.items.enable")) { config.set("general.cars.fuel.items.enable", false); } if (!config.contains("general.cars.fuel.items.ids")) { config.set("general.cars.fuel.items.ids", "5,263:0,263:1"); } if(!config.contains("general.cars.fuel.sellFuel")){ config.set("general.cars.fuel.sellFuel", true); } if (!config.contains("general.cars.barriers")) { config.set("general.cars.barriers", "139,85,107,113"); } if (!config.contains("general.cars.speedMods")) { config.set("general.cars.speedMods", "88:0-10,19:0-20"); } if (!config.contains("general.cars.placePerm.enable")) { config.set("general.cars.placePerm.enable", false); } if (!config.contains("general.cars.placePerm.perm")) { config.set("general.cars.placePerm.perm", "ucars.place"); } if (!config.contains("general.cars.health.default")) { config.set("general.cars.health.default", (double)10.0); } if (!config.contains("general.cars.health.underwaterDamage")) { config.set("general.cars.health.underwaterDamage", (double)0.0); } if (!config.contains("general.cars.health.lavaDamage")) { config.set("general.cars.health.lavaDamage", (double)0.0); } if (!config.contains("general.cars.health.cactusDamage")) { config.set("general.cars.health.cactusDamage", (double)0.0); } if (!config.contains("general.cars.health.crashDamage")) { config.set("general.cars.health.crashDamage", (double)0.0); } - if (!config.contains("general.cars.ulicense.enable")) { - config.set("general.cars.ulicense.enable", false); - } if (!config.contains("colorScheme.success")) { config.set("colorScheme.success", "&a"); } if (!config.contains("colorScheme.error")) { config.set("colorScheme.error", "&c"); } if (!config.contains("colorScheme.info")) { config.set("colorScheme.info", "&e"); } if (!config.contains("colorScheme.title")) { config.set("colorScheme.title", "&9"); } if (!config.contains("colorScheme.tp")) { config.set("colorScheme.tp", "&5"); } if (config.getBoolean("general.cars.fuel.enable") && !config.getBoolean("general.cars.fuel.items.enable")) { try { if (!setupEconomy()) { plugin.getLogger() .warning( "Attempted to enable fuel but vault NOT found. Please install vault to use fuel!"); plugin.getLogger().warning("Disabling fuel system..."); config.set("general.cars.fuel.enable", false); } else { vault = true; fuel = new HashMap<String, Double>(); File fuels = new File(plugin.getDataFolder() .getAbsolutePath() + File.separator + "fuel.bin"); if (fuels.exists() && fuels.length() > 1) { fuel = loadHashMapDouble(plugin.getDataFolder() .getAbsolutePath() + File.separator + "fuel.bin"); if (fuel == null) { fuel = new HashMap<String, Double>(); } } } } catch (Exception e) { plugin.getLogger() .warning( "Attempted to enable fuel but vault NOT found. Please install vault to use fuel!"); plugin.getLogger().warning("Disabling fuel system..."); config.set("general.cars.fuel.enable", false); } } } catch (Exception e) { } saveConfig(); try { lang.save(langFile); } catch (IOException e1) { getLogger().info("Error parsing lang file!"); } String idsraw = ucars.config .getString("general.cars.fuel.items.ids"); String[] ids = idsraw.split(","); ufuelitems = new ArrayList<ItemStack>(); for (String raw : ids) { ItemStack stack = ItemStackFromId.get(raw); if (stack != null) { ufuelitems.add(stack); } } colors = new Colors(config.getString("colorScheme.success"), config.getString("colorScheme.error"), config.getString("colorScheme.info"), config.getString("colorScheme.title"), config.getString("colorScheme.title")); PluginDescriptionFile pldesc = plugin.getDescription(); Map<String, Map<String, Object>> commands = pldesc.getCommands(); Set<String> keys = commands.keySet(); for (String k : keys) { try { cmdExecutor = new uCarsCommandExecutor(this); getCommand(k).setExecutor(cmdExecutor); } catch (Exception e) { getLogger().log(Level.SEVERE, "Error registering command " + k.toString()); e.printStackTrace(); } } ucars.listener = new uCarsListener(null); getServer().getPluginManager().registerEvents(ucars.listener, this); if(getServer().getPluginManager().getPlugin("ProtocolLib")!=null){ Boolean success = setupProtocol(); if(!success){ this.protocolLib = false; getLogger().log(Level.WARNING, "ProtocolLib (http://http://dev.bukkit.org/bukkit-plugins/protocollib/) was not found! For servers running MC 1.6 or above this is required for ucars to work!"); } } else{ this.protocolLib = false; getLogger().log(Level.WARNING, "ProtocolLib (http://http://dev.bukkit.org/bukkit-plugins/protocollib/) was not found! For servers running MC 1.6 or above this is required for ucars to work!"); } this.licensedPlayers = new ListStore(new File(getDataFolder()+File.separator+"licenses.txt")); this.licensedPlayers.load(); getLogger().info("uCars has been enabled!"); return; } public void onDisable() { saveHashMap(fuel, plugin.getDataFolder().getAbsolutePath() + File.separator + "fuel.bin"); this.licensedPlayers.save(); getLogger().info("uCars has been disabled!"); return; } public Boolean isBlockEqualToConfigIds(String configPath, Block block) { // split by , then split by : then compare! String ids = config.getString(configPath); String[] rawids = ids.split(","); for (String raw : rawids) { String[] parts = raw.split(":"); if (parts.length < 1) { } else if (parts.length < 2) { int id = Integer.parseInt(parts[0]); if (id == block.getTypeId()) { return true; } } else { int id = Integer.parseInt(parts[0]); int data = Integer.parseInt(parts[1]); int bdata = block.getData(); if (id == block.getTypeId() && bdata == data) { return true; } } } return false; } }
true
true
public void onEnable() { plugin = this; File langFile = new File(getDataFolder().getAbsolutePath() + File.separator + "lang.yml"); if (langFile.exists() == false || langFile.length() < 1) { try { langFile.createNewFile(); // newC.save(configFile); } catch (IOException e) { } } try { lang.load(langFile); } catch (Exception e1) { getLogger().log(Level.WARNING, "Error creating/loading lang file! Regenerating.."); } if (new File(getDataFolder().getAbsolutePath() + File.separator + "config.yml").exists() == false || new File(getDataFolder().getAbsolutePath() + File.separator + "config.yml").length() < 1) { // YamlConfiguration newC = new YamlConfiguration(); // newC.set("time.created", System.currentTimeMillis()); File configFile = new File(getDataFolder().getAbsolutePath() + File.separator + "config.yml"); try { configFile.createNewFile(); // newC.save(configFile); } catch (IOException e) { } copy(getResource("ucarsConfigHeader.yml"), configFile); } config = getConfig(); try { // config.load(this.getDataFolder().getAbsolutePath() + // File.separator + "config.yml"); if (!config.contains("general.cars.# description")) { config.set("general.cars.# description", "If enabled this will allow for drivable cars(Minecarts not on rails)"); } if(!lang.contains("lang.messages.place")){ lang.set("lang.messages.place", "&eYou placed a car! Cars can be driven with similar controls to a horse!"); } if(!lang.contains("lang.error.pluginNull")){ lang.set("lang.error.pluginNull", "&4Error in ucars: Caused by: plugin = null? Report on bukkitdev immediately!"); } if(!lang.contains("lang.messages.noDrivePerm")){ lang.set("lang.messages.noDrivePerm", "You don't have the permission ucars.cars required to drive a car!"); } if(!lang.contains("lang.messages.noPlacePerm")){ lang.set("lang.messages.noPlacePerm", "You don't have the permission %perm% required to place a car!"); } if(!lang.contains("lang.messages.noPlaceHere")){ lang.set("lang.messages.noPlaceHere", "&4You are not allowed to place a car here!"); } if(!lang.contains("lang.messages.hitByCar")){ lang.set("lang.messages.hitByCar", "You were hit by a car!"); } if(!lang.contains("lang.cars.remove")){ lang.set("lang.cars.remove", "&e%amount%&a cars in world &e%world%&a were removed!"); } if(!lang.contains("lang.boosts.already")){ lang.set("lang.boosts.already", "&4Already boosting!"); } if(!lang.contains("lang.boosts.low")){ lang.set("lang.boosts.low", "Initiated low level boost!"); } if(!lang.contains("lang.boosts.med")){ lang.set("lang.boosts.med", "Initiated medium level boost!"); } if(!lang.contains("lang.boosts.high")){ lang.set("lang.boosts.high", "Initiated high level boost!"); } if(!lang.contains("lang.fuel.empty")){ lang.set("lang.fuel.empty", "You don't have any fuel left!"); } if(!lang.contains("lang.fuel.disabled")){ lang.set("lang.fuel.disabled", "Fuel is not enabled!"); } if(!lang.contains("lang.fuel.unit")){ lang.set("lang.fuel.unit", "litres"); } if(!lang.contains("lang.fuel.isItem")){ lang.set("lang.fuel.isItem", "&9[Important:]&eItem fuel is enabled-The above is irrelevant!"); } if(!lang.contains("lang.fuel.invalidAmount")){ lang.set("lang.fuel.invalidAmount", "Amount invalid!"); } if(!lang.contains("lang.fuel.noMoney")){ lang.set("lang.fuel.noMoney", "You have no money!"); } if(!lang.contains("lang.fuel.notEnoughMoney")){ lang.set("lang.fuel.notEnoughMoney", "That purchase costs %amount% %unit%! You only have %balance% %unit%!"); } if(!lang.contains("lang.fuel.success")){ lang.set("lang.fuel.success", "Successfully purchased %quantity% of fuel for %amount% %unit%! You now have %balance% %unit% left!"); } if(!lang.contains("lang.fuel.sellSuccess")){ lang.set("lang.fuel.sellSuccess", "Successfully sold %quantity% of fuel for %amount% %unit%! You now have %balance% %unit% left!"); } if(!lang.contains("lang.messages.rightClickWith")){ lang.set("lang.messages.rightClickWith", "Right click with "); } if(!lang.contains("lang.messages.driveOver")){ lang.set("lang.messages.driveOver", "Drive over "); } if(!lang.contains("lang.messages.playersOnly")){ lang.set("lang.messages.playersOnly", "Players only!"); } if(!lang.contains("lang.messages.reload")){ lang.set("lang.messages.reload", "The config has been reloaded!"); } if(!lang.contains("lang.messages.noProtocolLib")){ lang.set("lang.messages.noProtocolLib", "Hello operator, ProtocolLib (http://dev.bukkit.org/bukkit-plugins/protocollib/) was not detected and is required for ucars in MC 1.6 or higher. Please install it if necessary!"); } if(!lang.contains("lang.licenses.next")){ lang.set("lang.licenses.next", "Now do %command% to continue!"); } if(!lang.contains("lang.licenses.basics")){ lang.set("lang.licenses.basics", "A car is just a minecart placed on the ground, not rails. To place a car simply look and the floor while holding a minecart and right click!"); } if(!lang.contains("lang.licenses.controls")){ lang.set("lang.licenses.controls", "1) Look where you would like to go. 2) Use the 'w' key to go forward and 's' to go backwards. 3) Use the 'd' key to slow down/brake and the 'a' key to shoot a turret (if turret enabled)!"); } if(!lang.contains("lang.licenses.effects")){ lang.set("lang.licenses.effects", "Car speed can change depending on what block you may drive over. These can be short term boosts or a speedmod block. Do /ucars for more info on boosts!"); } if(!lang.contains("lang.licenses.itemBoosts")){ lang.set("lang.licenses.itemBoosts", "Right clicking with certain items can give you different boosts. Do /ucars for more info!"); } if(!lang.contains("lang.licenses.success")){ lang.set("lang.licenses.success", "Congratulations! You can now drive a ucar!"); } if(!lang.contains("lang.licenses.noLicense")){ lang.set("lang.licenses.noLicense", "To drive a car you need a license, do /ulicense to obtain one!"); } if (!config.contains("general.cars.enable")) { config.set("general.cars.enable", true); } if (!config.contains("general.permissions.enable")) { config.set("general.permissions.enable", true); } if (!config.contains("general.cars.defSpeed")) { config.set("general.cars.defSpeed", (double) 30); } if (!config.contains("general.cars.effectBlocks.enable")) { config.set("general.cars.effectBlocks.enable", true); } if (!config.contains("general.cars.lowBoost")) { config.set("general.cars.lowBoost", "263"); } if (!config.contains("general.cars.medBoost")) { config.set("general.cars.medBoost", "265"); } if (!config.contains("general.cars.highBoost")) { config.set("general.cars.highBoost", "264"); } if (!config.contains("general.cars.blockBoost")) { config.set("general.cars.blockBoost", "41"); } if (!config.contains("general.cars.HighblockBoost")) { config.set("general.cars.HighblockBoost", "57"); } if (!config.contains("general.cars.ResetblockBoost")) { config.set("general.cars.ResetblockBoost", "133"); } if (!config.contains("general.cars.turret")) { config.set("general.cars.turret", false); } if (!config.contains("general.cars.jumpBlock")) { config.set("general.cars.jumpBlock", "42"); } if (!config.contains("general.cars.jumpAmount")) { config.set("general.cars.jumpAmount", (double)60); } if (!config.contains("general.cars.teleportBlock")) { config.set("general.cars.teleportBlock", "159:2"); } if (!config.contains("general.cars.trafficLights.enable")) { config.set("general.cars.trafficLights.enable", true); } if (!config.contains("general.cars.trafficLights.waitingBlock")) { config.set("general.cars.trafficLights.waitingBlock", "155"); } if (!config.contains("general.cars.hitBy.enable")) { config.set("general.cars.hitBy.enable", false); } if (!config.contains("general.cars.hitBy.enableMonsterDamage")) { config.set("general.cars.hitBy.enableMonsterDamage", true); } if (!config.contains("general.cars.hitBy.power")) { config.set("general.cars.hitBy.power", (double) 5); } if (!config.contains("general.cars.hitBy.damage")) { config.set("general.cars.hitBy.damage", (double) 1.5); } if (!config.contains("general.cars.roadBlocks.enable")) { config.set("general.cars.roadBlocks.enable", false); } if (!config.contains("general.cars.roadBlocks.ids")) { config.set("general.cars.roadBlocks.ids", "35:15,35:8,35:0,35:7"); } if (!config.contains("general.cars.licenses.enable")) { config.set("general.cars.licenses.enable", false); } if (!config.contains("general.cars.fuel.enable")) { config.set("general.cars.fuel.enable", false); } if (!config.contains("general.cars.fuel.price")) { config.set("general.cars.fuel.price", (double) 2); } if (!config.contains("general.cars.fuel.check")) { config.set("general.cars.fuel.check", "288:0"); } if (!config.contains("general.cars.fuel.bypassPerm")) { config.set("general.cars.fuel.bypassPerm", "ucars.bypassfuel"); } if (!config.contains("general.cars.fuel.items.enable")) { config.set("general.cars.fuel.items.enable", false); } if (!config.contains("general.cars.fuel.items.ids")) { config.set("general.cars.fuel.items.ids", "5,263:0,263:1"); } if(!config.contains("general.cars.fuel.sellFuel")){ config.set("general.cars.fuel.sellFuel", true); } if (!config.contains("general.cars.barriers")) { config.set("general.cars.barriers", "139,85,107,113"); } if (!config.contains("general.cars.speedMods")) { config.set("general.cars.speedMods", "88:0-10,19:0-20"); } if (!config.contains("general.cars.placePerm.enable")) { config.set("general.cars.placePerm.enable", false); } if (!config.contains("general.cars.placePerm.perm")) { config.set("general.cars.placePerm.perm", "ucars.place"); } if (!config.contains("general.cars.health.default")) { config.set("general.cars.health.default", (double)10.0); } if (!config.contains("general.cars.health.underwaterDamage")) { config.set("general.cars.health.underwaterDamage", (double)0.0); } if (!config.contains("general.cars.health.lavaDamage")) { config.set("general.cars.health.lavaDamage", (double)0.0); } if (!config.contains("general.cars.health.cactusDamage")) { config.set("general.cars.health.cactusDamage", (double)0.0); } if (!config.contains("general.cars.health.crashDamage")) { config.set("general.cars.health.crashDamage", (double)0.0); } if (!config.contains("general.cars.ulicense.enable")) { config.set("general.cars.ulicense.enable", false); } if (!config.contains("colorScheme.success")) { config.set("colorScheme.success", "&a"); } if (!config.contains("colorScheme.error")) { config.set("colorScheme.error", "&c"); } if (!config.contains("colorScheme.info")) { config.set("colorScheme.info", "&e"); } if (!config.contains("colorScheme.title")) { config.set("colorScheme.title", "&9"); } if (!config.contains("colorScheme.tp")) { config.set("colorScheme.tp", "&5"); } if (config.getBoolean("general.cars.fuel.enable") && !config.getBoolean("general.cars.fuel.items.enable")) { try { if (!setupEconomy()) { plugin.getLogger() .warning( "Attempted to enable fuel but vault NOT found. Please install vault to use fuel!"); plugin.getLogger().warning("Disabling fuel system..."); config.set("general.cars.fuel.enable", false); } else { vault = true; fuel = new HashMap<String, Double>(); File fuels = new File(plugin.getDataFolder() .getAbsolutePath() + File.separator + "fuel.bin"); if (fuels.exists() && fuels.length() > 1) { fuel = loadHashMapDouble(plugin.getDataFolder() .getAbsolutePath() + File.separator + "fuel.bin"); if (fuel == null) { fuel = new HashMap<String, Double>(); } } } } catch (Exception e) { plugin.getLogger() .warning( "Attempted to enable fuel but vault NOT found. Please install vault to use fuel!"); plugin.getLogger().warning("Disabling fuel system..."); config.set("general.cars.fuel.enable", false); } } } catch (Exception e) { } saveConfig(); try { lang.save(langFile); } catch (IOException e1) { getLogger().info("Error parsing lang file!"); } String idsraw = ucars.config .getString("general.cars.fuel.items.ids"); String[] ids = idsraw.split(","); ufuelitems = new ArrayList<ItemStack>(); for (String raw : ids) { ItemStack stack = ItemStackFromId.get(raw); if (stack != null) { ufuelitems.add(stack); } } colors = new Colors(config.getString("colorScheme.success"), config.getString("colorScheme.error"), config.getString("colorScheme.info"), config.getString("colorScheme.title"), config.getString("colorScheme.title")); PluginDescriptionFile pldesc = plugin.getDescription(); Map<String, Map<String, Object>> commands = pldesc.getCommands(); Set<String> keys = commands.keySet(); for (String k : keys) { try { cmdExecutor = new uCarsCommandExecutor(this); getCommand(k).setExecutor(cmdExecutor); } catch (Exception e) { getLogger().log(Level.SEVERE, "Error registering command " + k.toString()); e.printStackTrace(); } } ucars.listener = new uCarsListener(null); getServer().getPluginManager().registerEvents(ucars.listener, this); if(getServer().getPluginManager().getPlugin("ProtocolLib")!=null){ Boolean success = setupProtocol(); if(!success){ this.protocolLib = false; getLogger().log(Level.WARNING, "ProtocolLib (http://http://dev.bukkit.org/bukkit-plugins/protocollib/) was not found! For servers running MC 1.6 or above this is required for ucars to work!"); } } else{ this.protocolLib = false; getLogger().log(Level.WARNING, "ProtocolLib (http://http://dev.bukkit.org/bukkit-plugins/protocollib/) was not found! For servers running MC 1.6 or above this is required for ucars to work!"); } this.licensedPlayers = new ListStore(new File(getDataFolder()+File.separator+"licenses.txt")); this.licensedPlayers.load(); getLogger().info("uCars has been enabled!"); return; }
public void onEnable() { plugin = this; File langFile = new File(getDataFolder().getAbsolutePath() + File.separator + "lang.yml"); if (langFile.exists() == false || langFile.length() < 1) { try { langFile.createNewFile(); // newC.save(configFile); } catch (IOException e) { } } try { lang.load(langFile); } catch (Exception e1) { getLogger().log(Level.WARNING, "Error creating/loading lang file! Regenerating.."); } if (new File(getDataFolder().getAbsolutePath() + File.separator + "config.yml").exists() == false || new File(getDataFolder().getAbsolutePath() + File.separator + "config.yml").length() < 1) { // YamlConfiguration newC = new YamlConfiguration(); // newC.set("time.created", System.currentTimeMillis()); File configFile = new File(getDataFolder().getAbsolutePath() + File.separator + "config.yml"); try { configFile.createNewFile(); // newC.save(configFile); } catch (IOException e) { } copy(getResource("ucarsConfigHeader.yml"), configFile); } config = getConfig(); try { // config.load(this.getDataFolder().getAbsolutePath() + // File.separator + "config.yml"); if (!config.contains("general.cars.# description")) { config.set("general.cars.# description", "If enabled this will allow for drivable cars(Minecarts not on rails)"); } if(!lang.contains("lang.messages.place")){ lang.set("lang.messages.place", "&eYou placed a car! Cars can be driven with similar controls to a horse!"); } if(!lang.contains("lang.error.pluginNull")){ lang.set("lang.error.pluginNull", "&4Error in ucars: Caused by: plugin = null? Report on bukkitdev immediately!"); } if(!lang.contains("lang.messages.noDrivePerm")){ lang.set("lang.messages.noDrivePerm", "You don't have the permission ucars.cars required to drive a car!"); } if(!lang.contains("lang.messages.noPlacePerm")){ lang.set("lang.messages.noPlacePerm", "You don't have the permission %perm% required to place a car!"); } if(!lang.contains("lang.messages.noPlaceHere")){ lang.set("lang.messages.noPlaceHere", "&4You are not allowed to place a car here!"); } if(!lang.contains("lang.messages.hitByCar")){ lang.set("lang.messages.hitByCar", "You were hit by a car!"); } if(!lang.contains("lang.cars.remove")){ lang.set("lang.cars.remove", "&e%amount%&a cars in world &e%world%&a were removed!"); } if(!lang.contains("lang.boosts.already")){ lang.set("lang.boosts.already", "&4Already boosting!"); } if(!lang.contains("lang.boosts.low")){ lang.set("lang.boosts.low", "Initiated low level boost!"); } if(!lang.contains("lang.boosts.med")){ lang.set("lang.boosts.med", "Initiated medium level boost!"); } if(!lang.contains("lang.boosts.high")){ lang.set("lang.boosts.high", "Initiated high level boost!"); } if(!lang.contains("lang.fuel.empty")){ lang.set("lang.fuel.empty", "You don't have any fuel left!"); } if(!lang.contains("lang.fuel.disabled")){ lang.set("lang.fuel.disabled", "Fuel is not enabled!"); } if(!lang.contains("lang.fuel.unit")){ lang.set("lang.fuel.unit", "litres"); } if(!lang.contains("lang.fuel.isItem")){ lang.set("lang.fuel.isItem", "&9[Important:]&eItem fuel is enabled-The above is irrelevant!"); } if(!lang.contains("lang.fuel.invalidAmount")){ lang.set("lang.fuel.invalidAmount", "Amount invalid!"); } if(!lang.contains("lang.fuel.noMoney")){ lang.set("lang.fuel.noMoney", "You have no money!"); } if(!lang.contains("lang.fuel.notEnoughMoney")){ lang.set("lang.fuel.notEnoughMoney", "That purchase costs %amount% %unit%! You only have %balance% %unit%!"); } if(!lang.contains("lang.fuel.success")){ lang.set("lang.fuel.success", "Successfully purchased %quantity% of fuel for %amount% %unit%! You now have %balance% %unit% left!"); } if(!lang.contains("lang.fuel.sellSuccess")){ lang.set("lang.fuel.sellSuccess", "Successfully sold %quantity% of fuel for %amount% %unit%! You now have %balance% %unit% left!"); } if(!lang.contains("lang.messages.rightClickWith")){ lang.set("lang.messages.rightClickWith", "Right click with "); } if(!lang.contains("lang.messages.driveOver")){ lang.set("lang.messages.driveOver", "Drive over "); } if(!lang.contains("lang.messages.playersOnly")){ lang.set("lang.messages.playersOnly", "Players only!"); } if(!lang.contains("lang.messages.reload")){ lang.set("lang.messages.reload", "The config has been reloaded!"); } if(!lang.contains("lang.messages.noProtocolLib")){ lang.set("lang.messages.noProtocolLib", "Hello operator, ProtocolLib (http://dev.bukkit.org/bukkit-plugins/protocollib/) was not detected and is required for ucars in MC 1.6 or higher. Please install it if necessary!"); } if(!lang.contains("lang.licenses.next")){ lang.set("lang.licenses.next", "Now do %command% to continue!"); } if(!lang.contains("lang.licenses.basics")){ lang.set("lang.licenses.basics", "A car is just a minecart placed on the ground, not rails. To place a car simply look and the floor while holding a minecart and right click!"); } if(!lang.contains("lang.licenses.controls")){ lang.set("lang.licenses.controls", "1) Look where you would like to go. 2) Use the 'w' key to go forward and 's' to go backwards. 3) Use the 'd' key to slow down/brake and the 'a' key to shoot a turret (if turret enabled)!"); } if(!lang.contains("lang.licenses.effects")){ lang.set("lang.licenses.effects", "Car speed can change depending on what block you may drive over. These can be short term boosts or a speedmod block. Do /ucars for more info on boosts!"); } if(!lang.contains("lang.licenses.itemBoosts")){ lang.set("lang.licenses.itemBoosts", "Right clicking with certain items can give you different boosts. Do /ucars for more info!"); } if(!lang.contains("lang.licenses.success")){ lang.set("lang.licenses.success", "Congratulations! You can now drive a ucar!"); } if(!lang.contains("lang.licenses.noLicense")){ lang.set("lang.licenses.noLicense", "To drive a car you need a license, do /ulicense to obtain one!"); } if (!config.contains("general.cars.enable")) { config.set("general.cars.enable", true); } if (!config.contains("general.permissions.enable")) { config.set("general.permissions.enable", true); } if (!config.contains("general.cars.defSpeed")) { config.set("general.cars.defSpeed", (double) 30); } if (!config.contains("general.cars.effectBlocks.enable")) { config.set("general.cars.effectBlocks.enable", true); } if (!config.contains("general.cars.lowBoost")) { config.set("general.cars.lowBoost", "263"); } if (!config.contains("general.cars.medBoost")) { config.set("general.cars.medBoost", "265"); } if (!config.contains("general.cars.highBoost")) { config.set("general.cars.highBoost", "264"); } if (!config.contains("general.cars.blockBoost")) { config.set("general.cars.blockBoost", "41"); } if (!config.contains("general.cars.HighblockBoost")) { config.set("general.cars.HighblockBoost", "57"); } if (!config.contains("general.cars.ResetblockBoost")) { config.set("general.cars.ResetblockBoost", "133"); } if (!config.contains("general.cars.turret")) { config.set("general.cars.turret", false); } if (!config.contains("general.cars.jumpBlock")) { config.set("general.cars.jumpBlock", "42"); } if (!config.contains("general.cars.jumpAmount")) { config.set("general.cars.jumpAmount", (double)60); } if (!config.contains("general.cars.teleportBlock")) { config.set("general.cars.teleportBlock", "159:2"); } if (!config.contains("general.cars.trafficLights.enable")) { config.set("general.cars.trafficLights.enable", true); } if (!config.contains("general.cars.trafficLights.waitingBlock")) { config.set("general.cars.trafficLights.waitingBlock", "155"); } if (!config.contains("general.cars.hitBy.enable")) { config.set("general.cars.hitBy.enable", false); } if (!config.contains("general.cars.hitBy.enableMonsterDamage")) { config.set("general.cars.hitBy.enableMonsterDamage", true); } if (!config.contains("general.cars.hitBy.power")) { config.set("general.cars.hitBy.power", (double) 5); } if (!config.contains("general.cars.hitBy.damage")) { config.set("general.cars.hitBy.damage", (double) 1.5); } if (!config.contains("general.cars.roadBlocks.enable")) { config.set("general.cars.roadBlocks.enable", false); } if (!config.contains("general.cars.roadBlocks.ids")) { config.set("general.cars.roadBlocks.ids", "35:15,35:8,35:0,35:7"); } if (!config.contains("general.cars.licenses.enable")) { config.set("general.cars.licenses.enable", false); } if (!config.contains("general.cars.fuel.enable")) { config.set("general.cars.fuel.enable", false); } if (!config.contains("general.cars.fuel.price")) { config.set("general.cars.fuel.price", (double) 2); } if (!config.contains("general.cars.fuel.check")) { config.set("general.cars.fuel.check", "288:0"); } if (!config.contains("general.cars.fuel.bypassPerm")) { config.set("general.cars.fuel.bypassPerm", "ucars.bypassfuel"); } if (!config.contains("general.cars.fuel.items.enable")) { config.set("general.cars.fuel.items.enable", false); } if (!config.contains("general.cars.fuel.items.ids")) { config.set("general.cars.fuel.items.ids", "5,263:0,263:1"); } if(!config.contains("general.cars.fuel.sellFuel")){ config.set("general.cars.fuel.sellFuel", true); } if (!config.contains("general.cars.barriers")) { config.set("general.cars.barriers", "139,85,107,113"); } if (!config.contains("general.cars.speedMods")) { config.set("general.cars.speedMods", "88:0-10,19:0-20"); } if (!config.contains("general.cars.placePerm.enable")) { config.set("general.cars.placePerm.enable", false); } if (!config.contains("general.cars.placePerm.perm")) { config.set("general.cars.placePerm.perm", "ucars.place"); } if (!config.contains("general.cars.health.default")) { config.set("general.cars.health.default", (double)10.0); } if (!config.contains("general.cars.health.underwaterDamage")) { config.set("general.cars.health.underwaterDamage", (double)0.0); } if (!config.contains("general.cars.health.lavaDamage")) { config.set("general.cars.health.lavaDamage", (double)0.0); } if (!config.contains("general.cars.health.cactusDamage")) { config.set("general.cars.health.cactusDamage", (double)0.0); } if (!config.contains("general.cars.health.crashDamage")) { config.set("general.cars.health.crashDamage", (double)0.0); } if (!config.contains("colorScheme.success")) { config.set("colorScheme.success", "&a"); } if (!config.contains("colorScheme.error")) { config.set("colorScheme.error", "&c"); } if (!config.contains("colorScheme.info")) { config.set("colorScheme.info", "&e"); } if (!config.contains("colorScheme.title")) { config.set("colorScheme.title", "&9"); } if (!config.contains("colorScheme.tp")) { config.set("colorScheme.tp", "&5"); } if (config.getBoolean("general.cars.fuel.enable") && !config.getBoolean("general.cars.fuel.items.enable")) { try { if (!setupEconomy()) { plugin.getLogger() .warning( "Attempted to enable fuel but vault NOT found. Please install vault to use fuel!"); plugin.getLogger().warning("Disabling fuel system..."); config.set("general.cars.fuel.enable", false); } else { vault = true; fuel = new HashMap<String, Double>(); File fuels = new File(plugin.getDataFolder() .getAbsolutePath() + File.separator + "fuel.bin"); if (fuels.exists() && fuels.length() > 1) { fuel = loadHashMapDouble(plugin.getDataFolder() .getAbsolutePath() + File.separator + "fuel.bin"); if (fuel == null) { fuel = new HashMap<String, Double>(); } } } } catch (Exception e) { plugin.getLogger() .warning( "Attempted to enable fuel but vault NOT found. Please install vault to use fuel!"); plugin.getLogger().warning("Disabling fuel system..."); config.set("general.cars.fuel.enable", false); } } } catch (Exception e) { } saveConfig(); try { lang.save(langFile); } catch (IOException e1) { getLogger().info("Error parsing lang file!"); } String idsraw = ucars.config .getString("general.cars.fuel.items.ids"); String[] ids = idsraw.split(","); ufuelitems = new ArrayList<ItemStack>(); for (String raw : ids) { ItemStack stack = ItemStackFromId.get(raw); if (stack != null) { ufuelitems.add(stack); } } colors = new Colors(config.getString("colorScheme.success"), config.getString("colorScheme.error"), config.getString("colorScheme.info"), config.getString("colorScheme.title"), config.getString("colorScheme.title")); PluginDescriptionFile pldesc = plugin.getDescription(); Map<String, Map<String, Object>> commands = pldesc.getCommands(); Set<String> keys = commands.keySet(); for (String k : keys) { try { cmdExecutor = new uCarsCommandExecutor(this); getCommand(k).setExecutor(cmdExecutor); } catch (Exception e) { getLogger().log(Level.SEVERE, "Error registering command " + k.toString()); e.printStackTrace(); } } ucars.listener = new uCarsListener(null); getServer().getPluginManager().registerEvents(ucars.listener, this); if(getServer().getPluginManager().getPlugin("ProtocolLib")!=null){ Boolean success = setupProtocol(); if(!success){ this.protocolLib = false; getLogger().log(Level.WARNING, "ProtocolLib (http://http://dev.bukkit.org/bukkit-plugins/protocollib/) was not found! For servers running MC 1.6 or above this is required for ucars to work!"); } } else{ this.protocolLib = false; getLogger().log(Level.WARNING, "ProtocolLib (http://http://dev.bukkit.org/bukkit-plugins/protocollib/) was not found! For servers running MC 1.6 or above this is required for ucars to work!"); } this.licensedPlayers = new ListStore(new File(getDataFolder()+File.separator+"licenses.txt")); this.licensedPlayers.load(); getLogger().info("uCars has been enabled!"); return; }
diff --git a/src/com/github/Indiv0/ChestEmpty/ChestEmpty.java b/src/com/github/Indiv0/ChestEmpty/ChestEmpty.java index 3db13f1..4edaf52 100644 --- a/src/com/github/Indiv0/ChestEmpty/ChestEmpty.java +++ b/src/com/github/Indiv0/ChestEmpty/ChestEmpty.java @@ -1,199 +1,199 @@ package com.github.Indiv0.ChestEmpty; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map.Entry; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.Chest; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; import org.mcstats.MetricsLite; public class ChestEmpty extends JavaPlugin { // Stores the players currently emptying chests. private ArrayList<String> playersSelecting = new ArrayList<String>(); // Stores the chests and their last inventories prior to deletion. private HashMap<Block, ItemStack[]> lastDeletedItems = new HashMap<Block, ItemStack[]>(); // Initializes an ItemCraftListener. public final BlockSelectionListener blockListener = new BlockSelectionListener(this); public void onEnable() { // Retrieves an instance of the PluginManager. PluginManager pm = getServer().getPluginManager(); // Registers the blockListener with the PluginManager. pm.registerEvents(this.blockListener, this); // Enable PluginMetrics. enableMetrics(); // Prints a message to the server confirming successful initialization of the plugin. PluginDescriptionFile pdfFile = this.getDescription(); getLogger().info(pdfFile.getName() + " " + pdfFile.getVersion() + " is enabled."); } public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { // Checks to see if the command is the "/chestempty" command. if(!cmd.getName().equalsIgnoreCase("chestempty")) return false; // Checks to make sure a player is performing the command. if(!(sender instanceof Player)) { sender.sendMessage("This command can only be run by a player."); return false; } // Checks to make sure user has proper permissions. if(!sender.hasPermission("chestempty.use")) return false; // Makes sure at least one argument has been provided. if(args.length == 0) { sender.sendMessage("To use ChestEmpty, type \"/chestempty\" followed by: toggle or undo."); return false; } // Makes sure the appropriate amount of arguments has been provided. if(args.length > 1) { sender.sendMessage("Too many arguments. Valid arguments are: toggle or undo."); return false; } // Checks to see if the argument(s) provided is not one of the valid options. if(!args[0].equals("toggle") && !args[0].equals("undo")) { sender.sendMessage("Invalid argument. Valid arguments are: toggle or undo"); return false; } // Gets the name of the player calling the command. String playerName = ((Player)sender).getDisplayName(); // Toggles the chestempty selection feature for the user. if(args[0].equals("toggle")) { toggleSelecting(playerName, sender); return true; } // Undoes the previous chestempty operation for that user. if(args[0].equals("undo")) { if(isSelecting(playerName)) { sender.sendMessage("Please exit selection mode first."); return false; } undoDeleteChestContents(sender); return true; } return false; } private void enableMetrics() { try { MetricsLite metrics = new MetricsLite(this); metrics.start(); } catch (IOException ex) { System.out.println("An error occured while attempting to connect to PluginMetrics."); } } private void undoDeleteChestContents(CommandSender sender) { Player player = (Player) sender; // Checks to see if the cache has a backup for that user. if (!player.hasMetadata("ChestBackupID")) { sender.sendMessage("Player has not emptied any chests."); return; } if (lastDeletedItems.isEmpty()) { sender.sendMessage("No chest backups exist."); player.removeMetadata("ChestBackupID", this); return; } // Checks every chest within the cache (this is probably a performance bottleneck). Iterator<Entry<Block, ItemStack[]>> iter = lastDeletedItems.entrySet().iterator(); while (iter.hasNext()) { - Block block = (Block) iter.next(); + Block block = (Block) iter.next().getKey(); ArrayList<Block> blocksToRemove = new ArrayList<Block>(); // Checks if the player's metadata stores the same hashCode as the hashCode of the block // (i.e. the same chest is being referenced). - if(player.getMetadata("ChestBackupID").get(0).asInt() == block.hashCode()) + if(player.getMetadata("ChestBackupID").get(0).asInt() != block.hashCode()) continue; // Removes the hashcode of the chest from the player's metadata. player.removeMetadata("ChestBackupID", this); blocksToRemove.add(block); // Checks to make sure the block has not been converted into another block since // the chest was emptied. if(block.getType() != Material.CHEST) { sender.sendMessage("Cannot restore inventory: block no longer a chest."); continue; } Chest chest = (Chest) block.getState(); // Returns the deleted items into the chest. // This should be tested for what happens when the chest is full and items get // restored. restore: for(ItemStack itemStack : lastDeletedItems.get(block)) { if(itemStack == null) continue restore; chest.getInventory().addItem(itemStack); } // Removes any restored chests from the cache. iter.remove(); sender.sendMessage("Items successfully restored."); return; } } public void addChestInventoryBackup(Chest chest, Player player) { Block block = (Block) chest.getBlock(); // Searches for, and removes any previously added inventory backups for that block. Iterator<Entry<Block, ItemStack[]>> iter = lastDeletedItems.entrySet().iterator(); while (iter.hasNext()) // If the chest has already been backed up, remove the iterator. if (iter.next().getKey().hashCode() == block.hashCode()) iter.remove(); // Adds the inventory of a chest into the cache, and stores its hashCode in the player's metadata. player.setMetadata("ChestBackupID", new FixedMetadataValue(this, block.hashCode())); lastDeletedItems.put(block, chest.getInventory().getContents()); } public void toggleSelecting(String playerName, CommandSender sender) { // Toggles whether or not the player is currently in selection mode. if(isSelecting(playerName)) { playersSelecting.remove(playerName); sender.sendMessage("Selection mode disabled."); } else { playersSelecting.add(playerName); sender.sendMessage("Selection mode activated."); } } public boolean isSelecting(String playerName) { // Checks to see if the player is currently in selection mode. return playersSelecting.contains(playerName); } }
false
true
private void undoDeleteChestContents(CommandSender sender) { Player player = (Player) sender; // Checks to see if the cache has a backup for that user. if (!player.hasMetadata("ChestBackupID")) { sender.sendMessage("Player has not emptied any chests."); return; } if (lastDeletedItems.isEmpty()) { sender.sendMessage("No chest backups exist."); player.removeMetadata("ChestBackupID", this); return; } // Checks every chest within the cache (this is probably a performance bottleneck). Iterator<Entry<Block, ItemStack[]>> iter = lastDeletedItems.entrySet().iterator(); while (iter.hasNext()) { Block block = (Block) iter.next(); ArrayList<Block> blocksToRemove = new ArrayList<Block>(); // Checks if the player's metadata stores the same hashCode as the hashCode of the block // (i.e. the same chest is being referenced). if(player.getMetadata("ChestBackupID").get(0).asInt() == block.hashCode()) continue; // Removes the hashcode of the chest from the player's metadata. player.removeMetadata("ChestBackupID", this); blocksToRemove.add(block); // Checks to make sure the block has not been converted into another block since // the chest was emptied. if(block.getType() != Material.CHEST) { sender.sendMessage("Cannot restore inventory: block no longer a chest."); continue; } Chest chest = (Chest) block.getState(); // Returns the deleted items into the chest. // This should be tested for what happens when the chest is full and items get // restored. restore: for(ItemStack itemStack : lastDeletedItems.get(block)) { if(itemStack == null) continue restore; chest.getInventory().addItem(itemStack); } // Removes any restored chests from the cache. iter.remove(); sender.sendMessage("Items successfully restored."); return; } }
private void undoDeleteChestContents(CommandSender sender) { Player player = (Player) sender; // Checks to see if the cache has a backup for that user. if (!player.hasMetadata("ChestBackupID")) { sender.sendMessage("Player has not emptied any chests."); return; } if (lastDeletedItems.isEmpty()) { sender.sendMessage("No chest backups exist."); player.removeMetadata("ChestBackupID", this); return; } // Checks every chest within the cache (this is probably a performance bottleneck). Iterator<Entry<Block, ItemStack[]>> iter = lastDeletedItems.entrySet().iterator(); while (iter.hasNext()) { Block block = (Block) iter.next().getKey(); ArrayList<Block> blocksToRemove = new ArrayList<Block>(); // Checks if the player's metadata stores the same hashCode as the hashCode of the block // (i.e. the same chest is being referenced). if(player.getMetadata("ChestBackupID").get(0).asInt() != block.hashCode()) continue; // Removes the hashcode of the chest from the player's metadata. player.removeMetadata("ChestBackupID", this); blocksToRemove.add(block); // Checks to make sure the block has not been converted into another block since // the chest was emptied. if(block.getType() != Material.CHEST) { sender.sendMessage("Cannot restore inventory: block no longer a chest."); continue; } Chest chest = (Chest) block.getState(); // Returns the deleted items into the chest. // This should be tested for what happens when the chest is full and items get // restored. restore: for(ItemStack itemStack : lastDeletedItems.get(block)) { if(itemStack == null) continue restore; chest.getInventory().addItem(itemStack); } // Removes any restored chests from the cache. iter.remove(); sender.sendMessage("Items successfully restored."); return; } }
diff --git a/src/org/biojava/bio/gui/sequence/FeatureLabelRenderer.java b/src/org/biojava/bio/gui/sequence/FeatureLabelRenderer.java index b82618e25..91794e5ee 100644 --- a/src/org/biojava/bio/gui/sequence/FeatureLabelRenderer.java +++ b/src/org/biojava/bio/gui/sequence/FeatureLabelRenderer.java @@ -1,181 +1,181 @@ /* * BioJava development code * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. If you do not have a copy, * see: * * http://www.gnu.org/copyleft/lesser.html * * Copyright for this code is held jointly by the individual * authors. These should be listed in @author doc comments. * * For more information on the BioJava project and its aims, * or to join the biojava-l mailing list, visit the home page * at: * * http://www.biojava.org/ * */ package org.biojava.bio.gui.sequence; import java.awt.Color; import java.awt.Graphics2D; import java.awt.event.MouseEvent; import java.awt.font.FontRenderContext; import java.awt.geom.AffineTransform; import org.biojava.bio.Annotation; import org.biojava.bio.BioError; import org.biojava.bio.seq.Feature; import org.biojava.bio.seq.FeatureHolder; import org.biojava.bio.symbol.Location; import org.biojava.utils.AbstractChangeable; import org.biojava.utils.ChangeEvent; import org.biojava.utils.ChangeSupport; import org.biojava.utils.ChangeType; import org.biojava.utils.ChangeVetoException; /** * @author unknown * @author Matthew Pocock */ public class FeatureLabelRenderer extends AbstractChangeable implements FeatureRenderer { public static final ChangeType LABEL_MAKER = new ChangeType( "The label maker has changed", "org.biojava.bio.gui.sequence.FeatureLabelRenderer", "LABEL_MAKER", SequenceRenderContext.REPAINT ); private static FontRenderContext FRC = new FontRenderContext( new AffineTransform(), false, true ); private LabelMaker labelMaker; public FeatureLabelRenderer() {} public FeatureLabelRenderer(LabelMaker labelMaker) { try { setLabelMaker(labelMaker); } catch (ChangeVetoException cve) { throw new BioError("Assertion Failure: could not set label maker",cve); } } public LabelMaker getLabelMaker() { return this.labelMaker; } public void setLabelMaker(LabelMaker labelMaker) throws ChangeVetoException { if(hasListeners()) { ChangeSupport cs = getChangeSupport(LABEL_MAKER); ChangeEvent ce = new ChangeEvent( this, LABEL_MAKER, labelMaker, this.labelMaker ); synchronized(cs) { cs.firePreChangeEvent(ce); this.labelMaker = labelMaker; cs.firePostChangeEvent(ce); } } else { this.labelMaker = labelMaker; } } public double getDepth(SequenceRenderContext src) { return src.getFont().getMaxCharBounds(FRC).getHeight(); } public double getMinimumLeader(SequenceRenderContext src) { return 0.0; } public double getMinimumTrailer(SequenceRenderContext src) { return 0.0; } public void renderFeature( Graphics2D g, Feature feat, SequenceRenderContext src ) { Location loc = feat.getLocation(); String label = labelMaker.makeLabel(feat); g.setPaint(Color.black); int min = Math.max(loc.getMin(), src.getRange().getMin()); int max = Math.min(loc.getMax(), src.getRange().getMax()); int mid = (min + max) / 2; g.drawString( label, (float) (src.sequenceToGraphics(mid)), - (float) (getDepth(src) + 2.0) + (float) (getDepth(src) - 2.0) ); } public FeatureHolder processMouseEvent( FeatureHolder hits, SequenceRenderContext src, MouseEvent me ) { return hits; } public static interface LabelMaker { String makeLabel(Feature f); } public static class SourceLabelMaker implements LabelMaker { public String makeLabel(Feature f) { return f.getSource(); } } public static class TypeLabelMaker implements LabelMaker { public String makeLabel(Feature f) { return f.getType(); } } public static class AnnotationLabelMaker implements LabelMaker { private Object key; public AnnotationLabelMaker() { } public AnnotationLabelMaker(Object key) { setKey(key); } public void setKey(Object key) { this.key = key; } public Object getKey() { return key; } public String makeLabel(Feature feat) { Annotation ann = feat.getAnnotation(); if(ann.containsProperty(key)) { return ann.getProperty(key).toString(); } else { return ""; } } } }
true
true
public void renderFeature( Graphics2D g, Feature feat, SequenceRenderContext src ) { Location loc = feat.getLocation(); String label = labelMaker.makeLabel(feat); g.setPaint(Color.black); int min = Math.max(loc.getMin(), src.getRange().getMin()); int max = Math.min(loc.getMax(), src.getRange().getMax()); int mid = (min + max) / 2; g.drawString( label, (float) (src.sequenceToGraphics(mid)), (float) (getDepth(src) + 2.0) ); }
public void renderFeature( Graphics2D g, Feature feat, SequenceRenderContext src ) { Location loc = feat.getLocation(); String label = labelMaker.makeLabel(feat); g.setPaint(Color.black); int min = Math.max(loc.getMin(), src.getRange().getMin()); int max = Math.min(loc.getMax(), src.getRange().getMax()); int mid = (min + max) / 2; g.drawString( label, (float) (src.sequenceToGraphics(mid)), (float) (getDepth(src) - 2.0) ); }
diff --git a/src/java/org/apache/cassandra/service/StorageService.java b/src/java/org/apache/cassandra/service/StorageService.java index ed76ba94..7bf97e30 100644 --- a/src/java/org/apache/cassandra/service/StorageService.java +++ b/src/java/org/apache/cassandra/service/StorageService.java @@ -1,2066 +1,2066 @@ /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.cassandra.service; import java.io.IOError; import java.io.IOException; import java.lang.management.ManagementFactory; import java.net.InetAddress; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.EnumMap; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import javax.management.MBeanServer; import javax.management.ObjectName; import org.apache.cassandra.concurrent.JMXEnabledThreadPoolExecutor; import org.apache.cassandra.concurrent.NamedThreadFactory; import org.apache.cassandra.concurrent.RetryingScheduledThreadPoolExecutor; import org.apache.cassandra.concurrent.Stage; import org.apache.cassandra.concurrent.StageManager; import org.apache.cassandra.config.CFMetaData; import org.apache.cassandra.config.ColumnDefinition; import org.apache.cassandra.config.ConfigurationException; import org.apache.cassandra.config.DatabaseDescriptor; import org.apache.cassandra.config.KSMetaData; import org.apache.cassandra.config.RawColumnDefinition; import org.apache.cassandra.config.RawColumnFamily; import org.apache.cassandra.config.RawKeyspace; import org.apache.cassandra.db.BinaryVerbHandler; import org.apache.cassandra.db.ColumnFamilyStore; import org.apache.cassandra.db.DecoratedKey; import org.apache.cassandra.db.DefinitionsAnnounceVerbHandler; import org.apache.cassandra.db.DefinitionsUpdateResponseVerbHandler; import org.apache.cassandra.db.DefsTable; import org.apache.cassandra.db.HintedHandOffManager; import org.apache.cassandra.db.ReadCommand; import org.apache.cassandra.db.ReadRepairVerbHandler; import org.apache.cassandra.db.ReadVerbHandler; import org.apache.cassandra.db.Row; import org.apache.cassandra.db.RowMutationVerbHandler; import org.apache.cassandra.db.SchemaCheckVerbHandler; import org.apache.cassandra.db.SystemTable; import org.apache.cassandra.db.Table; import org.apache.cassandra.db.TruncateVerbHandler; import org.apache.cassandra.db.migration.AddKeyspace; import org.apache.cassandra.db.migration.Migration; import org.apache.cassandra.dht.BootStrapper; import org.apache.cassandra.dht.IPartitioner; import org.apache.cassandra.dht.Range; import org.apache.cassandra.dht.Token; import org.apache.cassandra.gms.ApplicationState; import org.apache.cassandra.gms.EndpointState; import org.apache.cassandra.gms.FailureDetector; import org.apache.cassandra.gms.GossipDigestAck2VerbHandler; import org.apache.cassandra.gms.GossipDigestAckVerbHandler; import org.apache.cassandra.gms.GossipDigestSynVerbHandler; import org.apache.cassandra.gms.Gossiper; import org.apache.cassandra.gms.IEndpointStateChangeSubscriber; import org.apache.cassandra.gms.IFailureDetector; import org.apache.cassandra.gms.VersionedValue; import org.apache.cassandra.io.DeletionService; import org.apache.cassandra.io.util.FileUtils; import org.apache.cassandra.locator.AbstractReplicationStrategy; import org.apache.cassandra.locator.IEndpointSnitch; import org.apache.cassandra.locator.TokenMetadata; import org.apache.cassandra.net.IAsyncResult; import org.apache.cassandra.net.Message; import org.apache.cassandra.net.MessagingService; import org.apache.cassandra.net.ResponseVerbHandler; import org.apache.cassandra.service.AntiEntropyService.TreeRequestVerbHandler; import org.apache.cassandra.streaming.ReplicationFinishedVerbHandler; import org.apache.cassandra.streaming.StreamIn; import org.apache.cassandra.streaming.StreamOut; import org.apache.cassandra.streaming.StreamReplyVerbHandler; import org.apache.cassandra.streaming.StreamRequestVerbHandler; import org.apache.cassandra.streaming.StreamingService; import org.apache.cassandra.thrift.Constants; import org.apache.cassandra.thrift.UnavailableException; import org.apache.cassandra.utils.ByteBufferUtil; import org.apache.cassandra.utils.FBUtilities; import org.apache.cassandra.utils.SkipNullRepresenter; import org.apache.cassandra.utils.WrappedRunnable; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Level; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.yaml.snakeyaml.Dumper; import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.nodes.Tag; import com.google.common.base.Charsets; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; /* * This abstraction contains the token/identifier of this node * on the identifier space. This token gets gossiped around. * This class will also maintain histograms of the load information * of other nodes in the cluster. */ public class StorageService implements IEndpointStateChangeSubscriber, StorageServiceMBean { private static Logger logger_ = LoggerFactory.getLogger(StorageService.class); public static final int RING_DELAY = 30 * 1000; // delay after which we assume ring has stablized /* All verb handler identifiers */ public enum Verb { MUTATION, BINARY, READ_REPAIR, READ, REQUEST_RESPONSE, // client-initiated reads and writes STREAM_INITIATE, // Deprecated STREAM_INITIATE_DONE, // Deprecated STREAM_REPLY, STREAM_REQUEST, RANGE_SLICE, BOOTSTRAP_TOKEN, TREE_REQUEST, TREE_RESPONSE, JOIN, // Deprecated GOSSIP_DIGEST_SYN, GOSSIP_DIGEST_ACK, GOSSIP_DIGEST_ACK2, DEFINITIONS_ANNOUNCE, DEFINITIONS_UPDATE_RESPONSE, TRUNCATE, SCHEMA_CHECK, INDEX_SCAN, REPLICATION_FINISHED, INTERNAL_RESPONSE, // responses to internal calls ; // remember to add new verbs at the end, since we serialize by ordinal } public static final Verb[] VERBS = Verb.values(); public static final EnumMap<StorageService.Verb, Stage> verbStages = new EnumMap<StorageService.Verb, Stage>(StorageService.Verb.class) {{ put(Verb.MUTATION, Stage.MUTATION); put(Verb.BINARY, Stage.MUTATION); put(Verb.READ_REPAIR, Stage.MUTATION); put(Verb.READ, Stage.READ); put(Verb.REQUEST_RESPONSE, Stage.REQUEST_RESPONSE); put(Verb.STREAM_REPLY, Stage.MISC); // TODO does this really belong on misc? I've just copied old behavior here put(Verb.STREAM_REQUEST, Stage.STREAM); put(Verb.RANGE_SLICE, Stage.READ); put(Verb.BOOTSTRAP_TOKEN, Stage.MISC); put(Verb.TREE_REQUEST, Stage.ANTIENTROPY); put(Verb.TREE_RESPONSE, Stage.ANTIENTROPY); put(Verb.GOSSIP_DIGEST_ACK, Stage.GOSSIP); put(Verb.GOSSIP_DIGEST_ACK2, Stage.GOSSIP); put(Verb.GOSSIP_DIGEST_SYN, Stage.GOSSIP); put(Verb.DEFINITIONS_ANNOUNCE, Stage.READ); put(Verb.DEFINITIONS_UPDATE_RESPONSE, Stage.READ); put(Verb.TRUNCATE, Stage.MUTATION); put(Verb.SCHEMA_CHECK, Stage.MIGRATION); put(Verb.INDEX_SCAN, Stage.READ); put(Verb.REPLICATION_FINISHED, Stage.MISC); put(Verb.INTERNAL_RESPONSE, Stage.INTERNAL_RESPONSE); }}; private static IPartitioner partitioner_ = DatabaseDescriptor.getPartitioner(); public static VersionedValue.VersionedValueFactory valueFactory = new VersionedValue.VersionedValueFactory(partitioner_); public static RetryingScheduledThreadPoolExecutor scheduledTasks = new RetryingScheduledThreadPoolExecutor("ScheduledTasks"); public static final StorageService instance = new StorageService(); public static IPartitioner getPartitioner() { return partitioner_; } public Collection<Range> getLocalRanges(String table) { return getRangesForEndpoint(table, FBUtilities.getLocalAddress()); } public Range getLocalPrimaryRange() { return getPrimaryRangeForEndpoint(FBUtilities.getLocalAddress()); } /* This abstraction maintains the token/endpoint metadata information */ private TokenMetadata tokenMetadata_ = new TokenMetadata(); /* This thread pool does consistency checks when the client doesn't care about consistency */ private ExecutorService consistencyManager_ = new JMXEnabledThreadPoolExecutor(DatabaseDescriptor.getConsistencyThreads(), DatabaseDescriptor.getConsistencyThreads(), StageManager.KEEPALIVE, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new NamedThreadFactory("ReadRepair"), "request"); private Set<InetAddress> replicatingNodes; private InetAddress removingNode; /* Are we starting this node in bootstrap mode? */ private boolean isBootstrapMode; /* when intialized as a client, we shouldn't write to the system table. */ private boolean isClientMode; private boolean initialized; private String operationMode; private MigrationManager migrationManager = new MigrationManager(); /* Used for tracking drain progress */ private volatile int totalCFs, remainingCFs; public void finishBootstrapping() { isBootstrapMode = false; SystemTable.setBootstrapped(true); setToken(getLocalToken()); Gossiper.instance.addLocalApplicationState(ApplicationState.STATUS, valueFactory.normal(getLocalToken())); logger_.info("Bootstrap/move completed! Now serving reads."); setMode("Normal", false); } /** This method updates the local token on disk */ public void setToken(Token token) { if (logger_.isDebugEnabled()) logger_.debug("Setting token to {}", token); SystemTable.updateToken(token); tokenMetadata_.updateNormalToken(token, FBUtilities.getLocalAddress()); } public StorageService() { MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); try { mbs.registerMBean(this, new ObjectName("org.apache.cassandra.db:type=StorageService")); } catch (Exception e) { throw new RuntimeException(e); } /* register the verb handlers */ MessagingService.instance.registerVerbHandlers(Verb.BINARY, new BinaryVerbHandler()); MessagingService.instance.registerVerbHandlers(Verb.MUTATION, new RowMutationVerbHandler()); MessagingService.instance.registerVerbHandlers(Verb.READ_REPAIR, new ReadRepairVerbHandler()); MessagingService.instance.registerVerbHandlers(Verb.READ, new ReadVerbHandler()); MessagingService.instance.registerVerbHandlers(Verb.RANGE_SLICE, new RangeSliceVerbHandler()); MessagingService.instance.registerVerbHandlers(Verb.INDEX_SCAN, new IndexScanVerbHandler()); // see BootStrapper for a summary of how the bootstrap verbs interact MessagingService.instance.registerVerbHandlers(Verb.BOOTSTRAP_TOKEN, new BootStrapper.BootstrapTokenVerbHandler()); MessagingService.instance.registerVerbHandlers(Verb.STREAM_REQUEST, new StreamRequestVerbHandler() ); MessagingService.instance.registerVerbHandlers(Verb.STREAM_REPLY, new StreamReplyVerbHandler()); MessagingService.instance.registerVerbHandlers(Verb.REPLICATION_FINISHED, new ReplicationFinishedVerbHandler()); MessagingService.instance.registerVerbHandlers(Verb.REQUEST_RESPONSE, new ResponseVerbHandler()); MessagingService.instance.registerVerbHandlers(Verb.INTERNAL_RESPONSE, new ResponseVerbHandler()); MessagingService.instance.registerVerbHandlers(Verb.TREE_REQUEST, new TreeRequestVerbHandler()); MessagingService.instance.registerVerbHandlers(Verb.TREE_RESPONSE, new AntiEntropyService.TreeResponseVerbHandler()); MessagingService.instance.registerVerbHandlers(Verb.GOSSIP_DIGEST_SYN, new GossipDigestSynVerbHandler()); MessagingService.instance.registerVerbHandlers(Verb.GOSSIP_DIGEST_ACK, new GossipDigestAckVerbHandler()); MessagingService.instance.registerVerbHandlers(Verb.GOSSIP_DIGEST_ACK2, new GossipDigestAck2VerbHandler()); MessagingService.instance.registerVerbHandlers(Verb.DEFINITIONS_ANNOUNCE, new DefinitionsAnnounceVerbHandler()); MessagingService.instance.registerVerbHandlers(Verb.DEFINITIONS_UPDATE_RESPONSE, new DefinitionsUpdateResponseVerbHandler()); MessagingService.instance.registerVerbHandlers(Verb.TRUNCATE, new TruncateVerbHandler()); MessagingService.instance.registerVerbHandlers(Verb.SCHEMA_CHECK, new SchemaCheckVerbHandler()); // spin up the streaming serivice so it is available for jmx tools. if (StreamingService.instance == null) throw new RuntimeException("Streaming service is unavailable."); } public void stopClient() { Gossiper.instance.unregister(migrationManager); Gossiper.instance.unregister(this); Gossiper.instance.stop(); MessagingService.shutdown(); StageManager.shutdownNow(); } public synchronized void initClient() throws IOException { if (initialized) { if (!isClientMode) throw new UnsupportedOperationException("StorageService does not support switching modes."); return; } initialized = true; isClientMode = true; logger_.info("Starting up client gossip"); setMode("Client", false); Gossiper.instance.register(this); Gossiper.instance.start(FBUtilities.getLocalAddress(), (int)(System.currentTimeMillis() / 1000)); // needed for node-ring gathering. MessagingService.instance.listen(FBUtilities.getLocalAddress()); // sleep a while to allow gossip to warm up (the other nodes need to know about this one before they can reply). try { Thread.sleep(5000L); } catch (Exception ex) { throw new IOError(ex); } MigrationManager.announce(DatabaseDescriptor.getDefsVersion(), DatabaseDescriptor.getSeeds()); } public synchronized void initServer() throws IOException, org.apache.cassandra.config.ConfigurationException { logger_.info("Cassandra version: " + FBUtilities.getReleaseVersionString()); logger_.info("Thrift API version: " + Constants.VERSION); if (initialized) { if (isClientMode) throw new UnsupportedOperationException("StorageService does not support switching modes."); return; } initialized = true; isClientMode = false; try { GCInspector.instance.start(); } catch (Throwable t) { logger_.warn("Unable to start GCInspector (currently only supported on the Sun JVM)"); } if (Boolean.valueOf(System.getProperty("cassandra.load_ring_state", "true"))) { logger_.info("Loading persisted ring state"); for (Map.Entry<Token, InetAddress> entry : SystemTable.loadTokens().entrySet()) { tokenMetadata_.updateNormalToken(entry.getKey(), entry.getValue()); Gossiper.instance.addSavedEndpoint(entry.getValue()); } } logger_.info("Starting up server gossip"); // have to start the gossip service before we can see any info on other nodes. this is necessary // for bootstrap to get the load info it needs. // (we won't be part of the storage ring though until we add a nodeId to our state, below.) Gossiper.instance.register(this); Gossiper.instance.register(migrationManager); Gossiper.instance.start(FBUtilities.getLocalAddress(), SystemTable.incrementAndGetGeneration()); // needed for node-ring gathering. MessagingService.instance.listen(FBUtilities.getLocalAddress()); StorageLoadBalancer.instance.startBroadcasting(); MigrationManager.announce(DatabaseDescriptor.getDefsVersion(), DatabaseDescriptor.getSeeds()); if (DatabaseDescriptor.isAutoBootstrap() && DatabaseDescriptor.getSeeds().contains(FBUtilities.getLocalAddress()) && !SystemTable.isBootstrapped()) logger_.info("This node will not auto bootstrap because it is configured to be a seed node."); if (DatabaseDescriptor.isAutoBootstrap() && !(DatabaseDescriptor.getSeeds().contains(FBUtilities.getLocalAddress()) || SystemTable.isBootstrapped())) { setMode("Joining: getting load information", true); StorageLoadBalancer.instance.waitForLoadInfo(); if (logger_.isDebugEnabled()) logger_.debug("... got load info"); if (tokenMetadata_.isMember(FBUtilities.getLocalAddress())) { String s = "This node is already a member of the token ring; bootstrap aborted. (If replacing a dead node, remove the old one from the ring first.)"; throw new UnsupportedOperationException(s); } setMode("Joining: getting bootstrap token", true); Token token = BootStrapper.getBootstrapToken(tokenMetadata_, StorageLoadBalancer.instance.getLoadInfo()); // don't bootstrap if there are no tables defined. if (DatabaseDescriptor.getNonSystemTables().size() > 0) { bootstrap(token); assert !isBootstrapMode; // bootstrap will block until finished } else { isBootstrapMode = false; SystemTable.setBootstrapped(true); - tokenMetadata_.updateNormalToken(token, FBUtilities.getLocalAddress()); + setToken(token); Gossiper.instance.addLocalApplicationState(ApplicationState.STATUS, valueFactory.normal(token)); setMode("Normal", false); } } else { Token token = SystemTable.getSavedToken(); if (token == null) { String initialToken = DatabaseDescriptor.getInitialToken(); if (initialToken == null) { token = partitioner_.getRandomToken(); logger_.warn("Generated random token " + token + ". Random tokens will result in an unbalanced ring; see http://wiki.apache.org/cassandra/Operations"); } else { token = partitioner_.getTokenFactory().fromString(initialToken); logger_.info("Saved token not found. Using " + token + " from configuration"); } SystemTable.updateToken(token); } else { logger_.info("Using saved token " + token); } SystemTable.setBootstrapped(true); tokenMetadata_.updateNormalToken(token, FBUtilities.getLocalAddress()); Gossiper.instance.addLocalApplicationState(ApplicationState.STATUS, valueFactory.normal(token)); setMode("Normal", false); } assert tokenMetadata_.sortedTokens().size() > 0; } private void setMode(String m, boolean log) { operationMode = m; if (log) logger_.info(m); } private void bootstrap(Token token) throws IOException { isBootstrapMode = true; SystemTable.updateToken(token); // DON'T use setToken, that makes us part of the ring locally which is incorrect until we are done bootstrapping Gossiper.instance.addLocalApplicationState(ApplicationState.STATUS, valueFactory.bootstrapping(token)); setMode("Joining: sleeping " + RING_DELAY + " ms for pending range setup", true); try { Thread.sleep(RING_DELAY); } catch (InterruptedException e) { throw new AssertionError(e); } setMode("Bootstrapping", true); new BootStrapper(FBUtilities.getLocalAddress(), token, tokenMetadata_).bootstrap(); // handles token update } public boolean isBootstrapMode() { return isBootstrapMode; } public TokenMetadata getTokenMetadata() { return tokenMetadata_; } /** * This method performs the requisite operations to make * sure that the N replicas are in sync. We do this in the * background when we do not care much about consistency. */ public void doConsistencyCheck(Row row, List<InetAddress> endpoints, ReadCommand command) { consistencyManager_.submit(new ConsistencyChecker(command.table, row, endpoints, command)); } /** * for a keyspace, return the ranges and corresponding hosts for a given keyspace. * @param keyspace * @return */ public Map<Range, List<String>> getRangeToEndpointMap(String keyspace) { // some people just want to get a visual representation of things. Allow null and set it to the first // non-system table. if (keyspace == null) keyspace = DatabaseDescriptor.getNonSystemTables().get(0); /* All the ranges for the tokens */ Map<Range, List<String>> map = new HashMap<Range, List<String>>(); for (Map.Entry<Range,List<InetAddress>> entry : getRangeToAddressMap(keyspace).entrySet()) { map.put(entry.getKey(), stringify(entry.getValue())); } return map; } public Map<Range, List<String>> getPendingRangeToEndpointMap(String keyspace) { // some people just want to get a visual representation of things. Allow null and set it to the first // non-system table. if (keyspace == null) keyspace = DatabaseDescriptor.getNonSystemTables().get(0); Map<Range, List<String>> map = new HashMap<Range, List<String>>(); for (Map.Entry<Range, Collection<InetAddress>> entry : tokenMetadata_.getPendingRanges(keyspace).entrySet()) { List<InetAddress> l = new ArrayList<InetAddress>(entry.getValue()); map.put(entry.getKey(), stringify(l)); } return map; } public Map<Range, List<InetAddress>> getRangeToAddressMap(String keyspace) { List<Range> ranges = getAllRanges(tokenMetadata_.sortedTokens()); return constructRangeToEndpointMap(keyspace, ranges); } public Map<Token, String> getTokenToEndpointMap() { Map<Token, InetAddress> mapInetAddress = tokenMetadata_.getTokenToEndpointMap(); Map<Token, String> mapString = new HashMap<Token, String>(mapInetAddress.size()); for (Map.Entry<Token, InetAddress> entry : mapInetAddress.entrySet()) { mapString.put(entry.getKey(), entry.getValue().getHostAddress()); } return mapString; } /** * Construct the range to endpoint mapping based on the true view * of the world. * @param ranges * @return mapping of ranges to the replicas responsible for them. */ private Map<Range, List<InetAddress>> constructRangeToEndpointMap(String keyspace, List<Range> ranges) { Map<Range, List<InetAddress>> rangeToEndpointMap = new HashMap<Range, List<InetAddress>>(); for (Range range : ranges) { rangeToEndpointMap.put(range, Table.open(keyspace).replicationStrategy.getNaturalEndpoints(range.right)); } return rangeToEndpointMap; } /* * onChange only ever sees one ApplicationState piece change at a time, so we perform a kind of state machine here. * We are concerned with two events: knowing the token associated with an endpoint, and knowing its operation mode. * Nodes can start in either bootstrap or normal mode, and from bootstrap mode can change mode to normal. * A node in bootstrap mode needs to have pendingranges set in TokenMetadata; a node in normal mode * should instead be part of the token ring. * * Normal MOVE_STATE progression of a node should be like this: * STATE_BOOTSTRAPPING,token * if bootstrapping. stays this way until all files are received. * STATE_NORMAL,token * ready to serve reads and writes. * STATE_NORMAL,token,REMOVE_TOKEN,token * specialized normal state in which this node acts as a proxy to tell the cluster about a dead node whose * token is being removed. this value becomes the permanent state of this node (unless it coordinates another * removetoken in the future). * STATE_LEAVING,token * get ready to leave the cluster as part of a decommission or move * STATE_LEFT,token * set after decommission or move is completed. * * Note: Any time a node state changes from STATE_NORMAL, it will not be visible to new nodes. So it follows that * you should never bootstrap a new node during a removetoken, decommission or move. */ public void onChange(InetAddress endpoint, ApplicationState state, VersionedValue value) { if (state != ApplicationState.STATUS) return; String apStateValue = value.value; String[] pieces = apStateValue.split(VersionedValue.DELIMITER_STR, -1); assert (pieces.length > 0); String moveName = pieces[0]; if (moveName.equals(VersionedValue.STATUS_BOOTSTRAPPING)) handleStateBootstrap(endpoint, pieces); else if (moveName.equals(VersionedValue.STATUS_NORMAL)) handleStateNormal(endpoint, pieces); else if (moveName.equals(VersionedValue.STATUS_LEAVING)) handleStateLeaving(endpoint, pieces); else if (moveName.equals(VersionedValue.STATUS_LEFT)) handleStateLeft(endpoint, pieces); } /** * Handle node bootstrap * * @param endpoint bootstrapping node * @param pieces STATE_BOOTSTRAPPING,bootstrap token as string */ private void handleStateBootstrap(InetAddress endpoint, String[] pieces) { assert pieces.length == 2; Token token = getPartitioner().getTokenFactory().fromString(pieces[1]); if (logger_.isDebugEnabled()) logger_.debug("Node " + endpoint + " state bootstrapping, token " + token); // if this node is present in token metadata, either we have missed intermediate states // or the node had crashed. Print warning if needed, clear obsolete stuff and // continue. if (tokenMetadata_.isMember(endpoint)) { // If isLeaving is false, we have missed both LEAVING and LEFT. However, if // isLeaving is true, we have only missed LEFT. Waiting time between completing // leave operation and rebootstrapping is relatively short, so the latter is quite // common (not enough time for gossip to spread). Therefore we report only the // former in the log. if (!tokenMetadata_.isLeaving(endpoint)) logger_.info("Node " + endpoint + " state jump to bootstrap"); tokenMetadata_.removeEndpoint(endpoint); } tokenMetadata_.addBootstrapToken(token, endpoint); calculatePendingRanges(); } /** * Handle node move to normal state. That is, node is entering token ring and participating * in reads. * * @param endpoint node * @param pieces STATE_NORMAL,token[,other_state,token] */ private void handleStateNormal(InetAddress endpoint, String[] pieces) { assert pieces.length >= 2; Token token = getPartitioner().getTokenFactory().fromString(pieces[1]); if (logger_.isDebugEnabled()) logger_.debug("Node " + endpoint + " state normal, token " + token); if (tokenMetadata_.isMember(endpoint)) logger_.info("Node " + endpoint + " state jump to normal"); // we don't want to update if this node is responsible for the token and it has a later startup time than endpoint. InetAddress currentNode = tokenMetadata_.getEndpoint(token); if (currentNode == null) { logger_.debug("New node " + endpoint + " at token " + token); tokenMetadata_.updateNormalToken(token, endpoint); if (!isClientMode) SystemTable.updateToken(endpoint, token); } else if (endpoint.equals(currentNode)) { // nothing to do } else if (Gossiper.instance.compareEndpointStartup(endpoint, currentNode) > 0) { logger_.info(String.format("Nodes %s and %s have the same token %s. %s is the new owner", endpoint, currentNode, token, endpoint)); tokenMetadata_.updateNormalToken(token, endpoint); if (!isClientMode) SystemTable.updateToken(endpoint, token); } else { logger_.info(String.format("Nodes %s and %s have the same token %s. Ignoring %s", endpoint, currentNode, token, endpoint)); } if (pieces.length > 2) { assert pieces.length == 4; handleStateRemoving(endpoint, getPartitioner().getTokenFactory().fromString(pieces[3]), pieces[2]); } calculatePendingRanges(); } /** * Handle node preparing to leave the ring * * @param endpoint node * @param pieces STATE_LEAVING,token */ private void handleStateLeaving(InetAddress endpoint, String[] pieces) { assert pieces.length == 2; String moveValue = pieces[1]; Token token = getPartitioner().getTokenFactory().fromString(moveValue); if (logger_.isDebugEnabled()) logger_.debug("Node " + endpoint + " state leaving, token " + token); // If the node is previously unknown or tokens do not match, update tokenmetadata to // have this node as 'normal' (it must have been using this token before the // leave). This way we'll get pending ranges right. if (!tokenMetadata_.isMember(endpoint)) { logger_.info("Node " + endpoint + " state jump to leaving"); tokenMetadata_.updateNormalToken(token, endpoint); } else if (!tokenMetadata_.getToken(endpoint).equals(token)) { logger_.warn("Node " + endpoint + " 'leaving' token mismatch. Long network partition?"); tokenMetadata_.updateNormalToken(token, endpoint); } // at this point the endpoint is certainly a member with this token, so let's proceed // normally tokenMetadata_.addLeavingEndpoint(endpoint); calculatePendingRanges(); } /** * Handle node leaving the ring. This can be either because of decommission or loadbalance * * @param endpoint If reason for leaving is decommission or loadbalance * endpoint is the leaving node. * @param pieces STATE_LEFT,token */ private void handleStateLeft(InetAddress endpoint, String[] pieces) { assert pieces.length == 2; Token token = getPartitioner().getTokenFactory().fromString(pieces[1]); if (logger_.isDebugEnabled()) logger_.debug("Node " + endpoint + " state left, token " + token); excise(token, endpoint); } /** * Handle node being actively removed from the ring. * * @param endpoint node */ private void handleStateRemoving(InetAddress endpoint, Token removeToken, String state) { InetAddress removeEndpoint = tokenMetadata_.getEndpoint(removeToken); if (removeEndpoint == null) return; if (removeEndpoint.equals(FBUtilities.getLocalAddress())) { logger_.info("Received removeToken gossip about myself. Is this node a replacement for a removed one?"); return; } if (VersionedValue.REMOVED_TOKEN.equals(state)) { excise(removeToken, removeEndpoint); } else if (VersionedValue.REMOVING_TOKEN.equals(state)) { if (logger_.isDebugEnabled()) logger_.debug("Token " + removeToken + " removed manually (endpoint was " + removeEndpoint + ")"); // Note that the endpoint is being removed tokenMetadata_.addLeavingEndpoint(removeEndpoint); calculatePendingRanges(); // grab any data we are now responsible for and notify responsible node restoreReplicaCount(removeEndpoint, endpoint); } } private void excise(Token token, InetAddress endpoint) { Gossiper.instance.removeEndpoint(endpoint); tokenMetadata_.removeEndpoint(endpoint); HintedHandOffManager.deleteHintsForEndPoint(endpoint); tokenMetadata_.removeBootstrapToken(token); calculatePendingRanges(); if (!isClientMode) { logger_.info("Removing token " + token + " for " + endpoint); SystemTable.removeToken(token); } } /** * Calculate pending ranges according to bootsrapping and leaving nodes. Reasoning is: * * (1) When in doubt, it is better to write too much to a node than too little. That is, if * there are multiple nodes moving, calculate the biggest ranges a node could have. Cleaning * up unneeded data afterwards is better than missing writes during movement. * (2) When a node leaves, ranges for other nodes can only grow (a node might get additional * ranges, but it will not lose any of its current ranges as a result of a leave). Therefore * we will first remove _all_ leaving tokens for the sake of calculation and then check what * ranges would go where if all nodes are to leave. This way we get the biggest possible * ranges with regard current leave operations, covering all subsets of possible final range * values. * (3) When a node bootstraps, ranges of other nodes can only get smaller. Without doing * complex calculations to see if multiple bootstraps overlap, we simply base calculations * on the same token ring used before (reflecting situation after all leave operations have * completed). Bootstrapping nodes will be added and removed one by one to that metadata and * checked what their ranges would be. This will give us the biggest possible ranges the * node could have. It might be that other bootstraps make our actual final ranges smaller, * but it does not matter as we can clean up the data afterwards. * * NOTE: This is heavy and ineffective operation. This will be done only once when a node * changes state in the cluster, so it should be manageable. */ private void calculatePendingRanges() { for (String table : DatabaseDescriptor.getNonSystemTables()) calculatePendingRanges(Table.open(table).replicationStrategy, table); } // public & static for testing purposes public static void calculatePendingRanges(AbstractReplicationStrategy strategy, String table) { TokenMetadata tm = StorageService.instance.getTokenMetadata(); Multimap<Range, InetAddress> pendingRanges = HashMultimap.create(); Map<Token, InetAddress> bootstrapTokens = tm.getBootstrapTokens(); Set<InetAddress> leavingEndpoints = tm.getLeavingEndpoints(); if (bootstrapTokens.isEmpty() && leavingEndpoints.isEmpty()) { if (logger_.isDebugEnabled()) logger_.debug("No bootstrapping or leaving nodes -> empty pending ranges for {}", table); tm.setPendingRanges(table, pendingRanges); return; } Multimap<InetAddress, Range> addressRanges = strategy.getAddressRanges(); // Copy of metadata reflecting the situation after all leave operations are finished. TokenMetadata allLeftMetadata = tm.cloneAfterAllLeft(); // get all ranges that will be affected by leaving nodes Set<Range> affectedRanges = new HashSet<Range>(); for (InetAddress endpoint : leavingEndpoints) affectedRanges.addAll(addressRanges.get(endpoint)); // for each of those ranges, find what new nodes will be responsible for the range when // all leaving nodes are gone. for (Range range : affectedRanges) { Collection<InetAddress> currentEndpoints = strategy.calculateNaturalEndpoints(range.right, tm); Collection<InetAddress> newEndpoints = strategy.calculateNaturalEndpoints(range.right, allLeftMetadata); newEndpoints.removeAll(currentEndpoints); pendingRanges.putAll(range, newEndpoints); } // At this stage pendingRanges has been updated according to leave operations. We can // now finish the calculation by checking bootstrapping nodes. // For each of the bootstrapping nodes, simply add and remove them one by one to // allLeftMetadata and check in between what their ranges would be. for (Map.Entry<Token, InetAddress> entry : bootstrapTokens.entrySet()) { InetAddress endpoint = entry.getValue(); allLeftMetadata.updateNormalToken(entry.getKey(), endpoint); for (Range range : strategy.getAddressRanges(allLeftMetadata).get(endpoint)) pendingRanges.put(range, endpoint); allLeftMetadata.removeEndpoint(endpoint); } tm.setPendingRanges(table, pendingRanges); if (logger_.isDebugEnabled()) logger_.debug("Pending ranges:\n" + (pendingRanges.isEmpty() ? "<empty>" : tm.printPendingRanges())); } /** * Finds living endpoints responsible for the given ranges * * @param table the table ranges belong to * @param ranges the ranges to find sources for * @return multimap of addresses to ranges the address is responsible for */ private Multimap<InetAddress, Range> getNewSourceRanges(String table, Set<Range> ranges) { InetAddress myAddress = FBUtilities.getLocalAddress(); Multimap<Range, InetAddress> rangeAddresses = Table.open(table).replicationStrategy.getRangeAddresses(tokenMetadata_); Multimap<InetAddress, Range> sourceRanges = HashMultimap.create(); IFailureDetector failureDetector = FailureDetector.instance; // find alive sources for our new ranges for (Range range : ranges) { Collection<InetAddress> possibleRanges = rangeAddresses.get(range); IEndpointSnitch snitch = DatabaseDescriptor.getEndpointSnitch(); List<InetAddress> sources = snitch.getSortedListByProximity(myAddress, possibleRanges); assert (!sources.contains(myAddress)); for (InetAddress source : sources) { if (failureDetector.isAlive(source)) { sourceRanges.put(source, range); break; } } } return sourceRanges; } /** * Sends a notification to a node indicating we have finished replicating data. * * @param local the local address * @param remote node to send notification to */ private void sendReplicationNotification(InetAddress local, InetAddress remote) { // notify the remote token Message msg = new Message(local, StorageService.Verb.REPLICATION_FINISHED, new byte[0]); IFailureDetector failureDetector = FailureDetector.instance; while (failureDetector.isAlive(remote)) { IAsyncResult iar = MessagingService.instance.sendRR(msg, remote); try { iar.get(DatabaseDescriptor.getRpcTimeout(), TimeUnit.MILLISECONDS); return; // done } catch(TimeoutException e) { // try again } } } /** * Called when an endpoint is removed from the ring. This function checks * whether this node becomes responsible for new ranges as a * consequence and streams data if needed. * * This is rather ineffective, but it does not matter so much * since this is called very seldom * * @param endpoint the node that left */ private void restoreReplicaCount(InetAddress endpoint, final InetAddress notifyEndpoint) { final Multimap<InetAddress, String> fetchSources = HashMultimap.create(); Multimap<String, Map.Entry<InetAddress, Collection<Range>>> rangesToFetch = HashMultimap.create(); final InetAddress myAddress = FBUtilities.getLocalAddress(); for (String table : DatabaseDescriptor.getNonSystemTables()) { Multimap<Range, InetAddress> changedRanges = getChangedRangesForLeaving(table, endpoint); Set<Range> myNewRanges = new HashSet<Range>(); for (Map.Entry<Range, InetAddress> entry : changedRanges.entries()) { if (entry.getValue().equals(myAddress)) myNewRanges.add(entry.getKey()); } Multimap<InetAddress, Range> sourceRanges = getNewSourceRanges(table, myNewRanges); for (Map.Entry<InetAddress, Collection<Range>> entry : sourceRanges.asMap().entrySet()) { fetchSources.put(entry.getKey(), table); rangesToFetch.put(table, entry); } } for (final String table : rangesToFetch.keySet()) { for (Map.Entry<InetAddress, Collection<Range>> entry : rangesToFetch.get(table)) { final InetAddress source = entry.getKey(); Collection<Range> ranges = entry.getValue(); final Runnable callback = new Runnable() { public void run() { synchronized (fetchSources) { fetchSources.remove(source, table); if (fetchSources.isEmpty()) sendReplicationNotification(myAddress, notifyEndpoint); } } }; if (logger_.isDebugEnabled()) logger_.debug("Requesting from " + source + " ranges " + StringUtils.join(ranges, ", ")); StreamIn.requestRanges(source, table, ranges, callback); } } } // needs to be modified to accept either a table or ARS. private Multimap<Range, InetAddress> getChangedRangesForLeaving(String table, InetAddress endpoint) { // First get all ranges the leaving endpoint is responsible for Collection<Range> ranges = getRangesForEndpoint(table, endpoint); if (logger_.isDebugEnabled()) logger_.debug("Node " + endpoint + " ranges [" + StringUtils.join(ranges, ", ") + "]"); Map<Range, List<InetAddress>> currentReplicaEndpoints = new HashMap<Range, List<InetAddress>>(); // Find (for each range) all nodes that store replicas for these ranges as well for (Range range : ranges) currentReplicaEndpoints.put(range, Table.open(table).replicationStrategy.calculateNaturalEndpoints(range.right, tokenMetadata_)); TokenMetadata temp = tokenMetadata_.cloneAfterAllLeft(); // endpoint might or might not be 'leaving'. If it was not leaving (that is, removetoken // command was used), it is still present in temp and must be removed. if (temp.isMember(endpoint)) temp.removeEndpoint(endpoint); Multimap<Range, InetAddress> changedRanges = HashMultimap.create(); // Go through the ranges and for each range check who will be // storing replicas for these ranges when the leaving endpoint // is gone. Whoever is present in newReplicaEndpoins list, but // not in the currentReplicaEndpoins list, will be needing the // range. for (Range range : ranges) { Collection<InetAddress> newReplicaEndpoints = Table.open(table).replicationStrategy.calculateNaturalEndpoints(range.right, temp); newReplicaEndpoints.removeAll(currentReplicaEndpoints.get(range)); if (logger_.isDebugEnabled()) if (newReplicaEndpoints.isEmpty()) logger_.debug("Range " + range + " already in all replicas"); else logger_.debug("Range " + range + " will be responsibility of " + StringUtils.join(newReplicaEndpoints, ", ")); changedRanges.putAll(range, newReplicaEndpoints); } return changedRanges; } public void onJoin(InetAddress endpoint, EndpointState epState) { for (Map.Entry<ApplicationState, VersionedValue> entry : epState.getApplicationStateMap().entrySet()) { onChange(endpoint, entry.getKey(), entry.getValue()); } } public void onAlive(InetAddress endpoint, EndpointState state) { if (!isClientMode) deliverHints(endpoint); } public void onRemove(InetAddress endpoint) { tokenMetadata_.removeEndpoint(endpoint); calculatePendingRanges(); } public void onDead(InetAddress endpoint, EndpointState state) { MessagingService.instance.convict(endpoint); } /** raw load value */ public double getLoad() { double bytes = 0; for (String tableName : DatabaseDescriptor.getTables()) { Table table = Table.open(tableName); for (ColumnFamilyStore cfs : table.getColumnFamilyStores()) bytes += cfs.getLiveDiskSpaceUsed(); } return bytes; } public String getLoadString() { return FileUtils.stringifyFileSize(getLoad()); } public Map<String, String> getLoadMap() { Map<String, String> map = new HashMap<String, String>(); for (Map.Entry<InetAddress,Double> entry : StorageLoadBalancer.instance.getLoadInfo().entrySet()) { map.put(entry.getKey().getHostAddress(), FileUtils.stringifyFileSize(entry.getValue())); } // gossiper doesn't see its own updates, so we need to special-case the local node map.put(FBUtilities.getLocalAddress().getHostAddress(), getLoadString()); return map; } /** * Deliver hints to the specified node when it has crashed * and come back up/ marked as alive after a network partition */ public final void deliverHints(InetAddress endpoint) { HintedHandOffManager.instance.deliverHints(endpoint); } public final void deliverHints(String host) throws UnknownHostException { HintedHandOffManager.instance.deliverHints(host); } public Token getLocalToken() { Token token = SystemTable.getSavedToken(); assert token != null; // should not be called before initServer sets this return token; } /* These methods belong to the MBean interface */ public String getToken() { return getLocalToken().toString(); } public String getReleaseVersion() { return FBUtilities.getReleaseVersionString(); } public List<String> getLeavingNodes() { return stringify(tokenMetadata_.getLeavingEndpoints()); } public List<String> getJoiningNodes() { return stringify(tokenMetadata_.getBootstrapTokens().values()); } public List<String> getLiveNodes() { return stringify(Gossiper.instance.getLiveMembers()); } public List<String> getUnreachableNodes() { return stringify(Gossiper.instance.getUnreachableMembers()); } private List<String> stringify(Iterable<InetAddress> endpoints) { List<String> stringEndpoints = new ArrayList<String>(); for (InetAddress ep : endpoints) { stringEndpoints.add(ep.getHostAddress()); } return stringEndpoints; } public int getCurrentGenerationNumber() { return Gossiper.instance.getCurrentGenerationNumber(FBUtilities.getLocalAddress()); } public void forceTableCleanup() throws IOException, ExecutionException, InterruptedException { List<String> tables = DatabaseDescriptor.getNonSystemTables(); for (String tName : tables) { Table table = Table.open(tName); table.forceCleanup(); } } public void forceTableCleanup(String tableName) throws IOException, ExecutionException, InterruptedException { Table table = getValidTable(tableName); table.forceCleanup(); } public void forceTableCompaction() throws IOException, ExecutionException, InterruptedException { for (Table table : Table.all()) table.forceCompaction(); } public void forceTableCompaction(String tableName) throws IOException, ExecutionException, InterruptedException { Table table = getValidTable(tableName); table.forceCompaction(); } /** * Takes the snapshot for a given table. * * @param tableName the name of the table. * @param tag the tag given to the snapshot (null is permissible) */ public void takeSnapshot(String tableName, String tag) throws IOException { Table tableInstance = getValidTable(tableName); tableInstance.snapshot(tag); } private Table getValidTable(String tableName) throws IOException { if (!DatabaseDescriptor.getTables().contains(tableName)) { throw new IOException("Table " + tableName + "does not exist"); } return Table.open(tableName); } /** * Takes a snapshot for every table. * * @param tag the tag given to the snapshot (null is permissible) */ public void takeAllSnapshot(String tag) throws IOException { for (Table table : Table.all()) table.snapshot(tag); } /** * Remove all the existing snapshots. */ public void clearSnapshot() throws IOException { for (Table table : Table.all()) table.clearSnapshot(); if (logger_.isDebugEnabled()) logger_.debug("Cleared out all snapshot directories"); } public Iterable<ColumnFamilyStore> getValidColumnFamilies(String tableName, String... cfNames) throws IOException { Table table = getValidTable(tableName); if (cfNames.length == 0) // all stores are interesting return table.getColumnFamilyStores(); // filter out interesting stores Set<ColumnFamilyStore> valid = new HashSet<ColumnFamilyStore>(); for (String cfName : cfNames) { ColumnFamilyStore cfStore = table.getColumnFamilyStore(cfName); if (cfStore == null) { // this means there was a cf passed in that is not recognized in the keyspace. report it and continue. logger_.warn(String.format("Invalid column family specified: %s. Proceeding with others.", cfName)); continue; } valid.add(cfStore); } return valid; } /** * Flush all memtables for a table and column families. * @param tableName * @param columnFamilies * @throws IOException */ public void forceTableFlush(final String tableName, final String... columnFamilies) throws IOException, ExecutionException, InterruptedException { for (ColumnFamilyStore cfStore : getValidColumnFamilies(tableName, columnFamilies)) { logger_.debug("Forcing binary flush on keyspace " + tableName + ", CF " + cfStore.getColumnFamilyName()); cfStore.forceFlushBinary(); logger_.debug("Forcing flush on keyspace " + tableName + ", CF " + cfStore.getColumnFamilyName()); cfStore.forceBlockingFlush(); } } /** * Trigger proactive repair for a table and column families. * @param tableName * @param columnFamilies * @throws IOException */ public void forceTableRepair(final String tableName, final String... columnFamilies) throws IOException { String[] families; if (columnFamilies.length == 0) { ArrayList<String> names = new ArrayList<String>(); for (ColumnFamilyStore cfStore : getValidColumnFamilies(tableName)) { names.add(cfStore.getColumnFamilyName()); } families = names.toArray(new String[] {}); } else { families = columnFamilies; } AntiEntropyService.RepairSession sess = AntiEntropyService.instance.getRepairSession(tableName, families); try { sess.start(); // block until the repair has completed sess.join(); } catch (InterruptedException e) { throw new IOException("Repair session " + sess + " failed.", e); } } /* End of MBean interface methods */ /** * This method returns the predecessor of the endpoint ep on the identifier * space. */ InetAddress getPredecessor(InetAddress ep) { Token token = tokenMetadata_.getToken(ep); return tokenMetadata_.getEndpoint(tokenMetadata_.getPredecessor(token)); } /* * This method returns the successor of the endpoint ep on the identifier * space. */ public InetAddress getSuccessor(InetAddress ep) { Token token = tokenMetadata_.getToken(ep); return tokenMetadata_.getEndpoint(tokenMetadata_.getSuccessor(token)); } /** * Get the primary range for the specified endpoint. * @param ep endpoint we are interested in. * @return range for the specified endpoint. */ public Range getPrimaryRangeForEndpoint(InetAddress ep) { return tokenMetadata_.getPrimaryRangeFor(tokenMetadata_.getToken(ep)); } /** * Get all ranges an endpoint is responsible for. * @param ep endpoint we are interested in. * @return ranges for the specified endpoint. */ Collection<Range> getRangesForEndpoint(String table, InetAddress ep) { return Table.open(table).replicationStrategy.getAddressRanges().get(ep); } /** * Get all ranges that span the ring given a set * of tokens. All ranges are in sorted order of * ranges. * @return ranges in sorted order */ public List<Range> getAllRanges(List<Token> sortedTokens) { if (logger_.isDebugEnabled()) logger_.debug("computing ranges for " + StringUtils.join(sortedTokens, ", ")); if (sortedTokens.isEmpty()) return Collections.emptyList(); List<Range> ranges = new ArrayList<Range>(); int size = sortedTokens.size(); for (int i = 1; i < size; ++i) { Range range = new Range(sortedTokens.get(i - 1), sortedTokens.get(i)); ranges.add(range); } Range range = new Range(sortedTokens.get(size - 1), sortedTokens.get(0)); ranges.add(range); return ranges; } /** * This method returns the N endpoints that are responsible for storing the * specified key i.e for replication. * * @param key - key for which we need to find the endpoint return value - * the endpoint responsible for this key */ public List<InetAddress> getNaturalEndpoints(String table, ByteBuffer key) { return getNaturalEndpoints(table, partitioner_.getToken(key)); } /** * This method returns the N endpoints that are responsible for storing the * specified key i.e for replication. * * @param token - token for which we need to find the endpoint return value - * the endpoint responsible for this token */ public List<InetAddress> getNaturalEndpoints(String table, Token token) { return Table.open(table).replicationStrategy.getNaturalEndpoints(token); } /** * This method attempts to return N endpoints that are responsible for storing the * specified key i.e for replication. * * @param key - key for which we need to find the endpoint return value - * the endpoint responsible for this key */ public List<InetAddress> getLiveNaturalEndpoints(String table, ByteBuffer key) { return getLiveNaturalEndpoints(table, partitioner_.getToken(key)); } public List<InetAddress> getLiveNaturalEndpoints(String table, Token token) { List<InetAddress> liveEps = new ArrayList<InetAddress>(); List<InetAddress> endpoints = Table.open(table).replicationStrategy.getNaturalEndpoints(token); for (InetAddress endpoint : endpoints) { if (FailureDetector.instance.isAlive(endpoint)) liveEps.add(endpoint); } return liveEps; } /** * This function finds the closest live endpoint that contains a given key. */ public InetAddress findSuitableEndpoint(String table, ByteBuffer key) throws IOException, UnavailableException { List<InetAddress> endpoints = getNaturalEndpoints(table, key); DatabaseDescriptor.getEndpointSnitch().sortByProximity(FBUtilities.getLocalAddress(), endpoints); if (logger_.isDebugEnabled()) logger_.debug("Sorted endpoints are " + StringUtils.join(endpoints, ",")); for (InetAddress endpoint : endpoints) { if (FailureDetector.instance.isAlive(endpoint)) return endpoint; } throw new UnavailableException(); // no nodes that could contain key are alive } public void setLog4jLevel(String classQualifier, String rawLevel) { Level level = Level.toLevel(rawLevel); org.apache.log4j.Logger.getLogger(classQualifier).setLevel(level); logger_.info("set log level to " + level + " for classes under '" + classQualifier + "' (if the level doesn't look like '" + rawLevel + "' then log4j couldn't parse '" + rawLevel + "')"); } /** * @return list of Tokens (_not_ keys!) breaking up the data this node is responsible for into pieces of roughly keysPerSplit */ public List<Token> getSplits(String table, String cfName, Range range, int keysPerSplit) { List<Token> tokens = new ArrayList<Token>(); // we use the actual Range token for the first and last brackets of the splits to ensure correctness tokens.add(range.left); List<DecoratedKey> keys = new ArrayList<DecoratedKey>(); Table t = Table.open(table); ColumnFamilyStore cfs = t.getColumnFamilyStore(cfName); for (DecoratedKey sample : cfs.allKeySamples()) { if (range.contains(sample.token)) keys.add(sample); } FBUtilities.sortSampledKeys(keys, range); int splits = keys.size() * DatabaseDescriptor.getIndexInterval() / keysPerSplit; if (keys.size() >= splits) { for (int i = 1; i < splits; i++) { int index = i * (keys.size() / splits); tokens.add(keys.get(index).token); } } tokens.add(range.right); return tokens; } /** return a token to which if a node bootstraps it will get about 1/2 of this node's range */ public Token getBootstrapToken() { Range range = getLocalPrimaryRange(); List<DecoratedKey> keys = new ArrayList<DecoratedKey>(); for (ColumnFamilyStore cfs : ColumnFamilyStore.all()) { for (DecoratedKey key : cfs.allKeySamples()) { if (range.contains(key.token)) keys.add(key); } } FBUtilities.sortSampledKeys(keys, range); if (keys.size() < 3) return partitioner_.midpoint(range.left, range.right); else return keys.get(keys.size() / 2).token; } /** * Broadcast leaving status and update local tokenMetadata_ accordingly */ private void startLeaving() { Gossiper.instance.addLocalApplicationState(ApplicationState.STATUS, valueFactory.leaving(getLocalToken())); tokenMetadata_.addLeavingEndpoint(FBUtilities.getLocalAddress()); calculatePendingRanges(); } public void decommission() throws InterruptedException { if (!tokenMetadata_.isMember(FBUtilities.getLocalAddress())) throw new UnsupportedOperationException("local node is not a member of the token ring yet"); if (tokenMetadata_.cloneAfterAllLeft().sortedTokens().size() < 2) throw new UnsupportedOperationException("no other normal nodes in the ring; decommission would be pointless"); for (String table : DatabaseDescriptor.getNonSystemTables()) { if (tokenMetadata_.getPendingRanges(table, FBUtilities.getLocalAddress()).size() > 0) throw new UnsupportedOperationException("data is currently moving to this node; unable to leave the ring"); } if (logger_.isDebugEnabled()) logger_.debug("DECOMMISSIONING"); startLeaving(); setMode("Leaving: sleeping " + RING_DELAY + " ms for pending range setup", true); Thread.sleep(RING_DELAY); Runnable finishLeaving = new Runnable() { public void run() { Gossiper.instance.stop(); MessagingService.shutdown(); StageManager.shutdownNow(); setMode("Decommissioned", true); // let op be responsible for killing the process } }; unbootstrap(finishLeaving); } private void leaveRing() { SystemTable.setBootstrapped(false); tokenMetadata_.removeEndpoint(FBUtilities.getLocalAddress()); calculatePendingRanges(); Gossiper.instance.addLocalApplicationState(ApplicationState.STATUS, valueFactory.left(getLocalToken())); try { Thread.sleep(2 * Gossiper.intervalInMillis_); } catch (InterruptedException e) { throw new AssertionError(e); } } private void unbootstrap(final Runnable onFinish) { final CountDownLatch latch = new CountDownLatch(DatabaseDescriptor.getNonSystemTables().size()); for (final String table : DatabaseDescriptor.getNonSystemTables()) { Multimap<Range, InetAddress> rangesMM = getChangedRangesForLeaving(table, FBUtilities.getLocalAddress()); if (logger_.isDebugEnabled()) logger_.debug("Ranges needing transfer are [" + StringUtils.join(rangesMM.keySet(), ",") + "]"); if (rangesMM.isEmpty()) { latch.countDown(); continue; } setMode("Leaving: streaming data to other nodes", true); final Set<Map.Entry<Range, InetAddress>> pending = new HashSet<Map.Entry<Range, InetAddress>>(rangesMM.entries()); for (final Map.Entry<Range, InetAddress> entry : rangesMM.entries()) { final Range range = entry.getKey(); final InetAddress newEndpoint = entry.getValue(); final Runnable callback = new Runnable() { public void run() { synchronized(pending) { pending.remove(entry); if (pending.isEmpty()) latch.countDown(); } } }; StageManager.getStage(Stage.STREAM).execute(new Runnable() { public void run() { // TODO each call to transferRanges re-flushes, this is potentially a lot of waste StreamOut.transferRanges(newEndpoint, table, Arrays.asList(range), callback); } }); } } // wait for the transfer runnables to signal the latch. logger_.debug("waiting for stream aks."); try { latch.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } logger_.debug("stream acks all received."); leaveRing(); onFinish.run(); } public void move(String newToken) throws IOException, InterruptedException { move(partitioner_.getTokenFactory().fromString(newToken)); } public void loadBalance() throws IOException, InterruptedException { move((Token)null); } /** * move the node to new token or find a new token to boot to according to load * * @param token new token to boot to, or if null, find balanced token to boot to */ private void move(final Token token) throws IOException, InterruptedException { for (String table : DatabaseDescriptor.getTables()) { if (tokenMetadata_.getPendingRanges(table, FBUtilities.getLocalAddress()).size() > 0) throw new UnsupportedOperationException("data is currently moving to this node; unable to leave the ring"); } if (token != null && tokenMetadata_.sortedTokens().contains(token)) throw new IOException("target token " + token + " is already owned by another node"); if (logger_.isDebugEnabled()) logger_.debug("Leaving: old token was " + getLocalToken()); startLeaving(); setMode("Leaving: sleeping " + RING_DELAY + " ms for pending range setup", true); Thread.sleep(RING_DELAY); Runnable finishMoving = new WrappedRunnable() { public void runMayThrow() throws IOException { Token bootstrapToken = token; if (bootstrapToken == null) { StorageLoadBalancer.instance.waitForLoadInfo(); bootstrapToken = BootStrapper.getBalancedToken(tokenMetadata_, StorageLoadBalancer.instance.getLoadInfo()); } logger_.info("re-bootstrapping to new token {}", bootstrapToken); bootstrap(bootstrapToken); } }; unbootstrap(finishMoving); } /** * Get the status of a token removal. */ public String getRemovalStatus() { if (removingNode == null) { return "No token removals in process."; } return String.format("Removing token (%s). Waiting for replication confirmation from [%s].", tokenMetadata_.getToken(removingNode), StringUtils.join(replicatingNodes, ",")); } /** * Force a remove operation to complete. This may be necessary if a remove operation * blocks forever due to node/stream failure. */ public void forceRemoveCompletion() { if (!replicatingNodes.isEmpty()) logger_.warn("Removal not confirmed for for " + StringUtils.join(this.replicatingNodes, ",")); replicatingNodes.clear(); } /** * Remove a node that has died. * * @param tokenString token for the node */ public void removeToken(String tokenString) { InetAddress myAddress = FBUtilities.getLocalAddress(); Token localToken = tokenMetadata_.getToken(myAddress); Token token = partitioner_.getTokenFactory().fromString(tokenString); InetAddress endpoint = tokenMetadata_.getEndpoint(token); if (endpoint == null) throw new UnsupportedOperationException("Token not found."); if (endpoint.equals(myAddress)) throw new UnsupportedOperationException("Cannot remove node's own token"); if (Gossiper.instance.getLiveMembers().contains(endpoint)) throw new UnsupportedOperationException("Node " + endpoint + " is alive and owns this token. Use decommission command to remove it from the ring"); // A leaving endpoint that is dead is already being removed. if (tokenMetadata_.isLeaving(endpoint)) throw new UnsupportedOperationException("Node " + endpoint + " is already being removed."); if (replicatingNodes != null) throw new UnsupportedOperationException("This node is already processing a removal. Wait for it to complete."); // Find the endpoints that are going to become responsible for data replicatingNodes = Collections.synchronizedSet(new HashSet<InetAddress>()); for (String table : DatabaseDescriptor.getNonSystemTables()) { // if the replication factor is 1 the data is lost so we shouldn't wait for confirmation if (DatabaseDescriptor.getReplicationFactor(table) == 1) continue; // get all ranges that change ownership (that is, a node needs // to take responsibility for new range) Multimap<Range, InetAddress> changedRanges = getChangedRangesForLeaving(table, endpoint); IFailureDetector failureDetector = FailureDetector.instance; for (InetAddress ep : changedRanges.values()) { if (failureDetector.isAlive(ep)) replicatingNodes.add(ep); else logger_.warn("Endpoint " + ep + " is down and will not receive data for re-replication of " + endpoint); } } removingNode = endpoint; tokenMetadata_.addLeavingEndpoint(endpoint); calculatePendingRanges(); // bundle two states together. include this nodes state to keep the status quo, // but indicate the leaving token so that it can be dealt with. Gossiper.instance.addLocalApplicationState(ApplicationState.STATUS, valueFactory.removingNonlocal(localToken, token)); // kick off streaming commands restoreReplicaCount(endpoint, myAddress); // wait for ReplicationFinishedVerbHandler to signal we're done while (!replicatingNodes.isEmpty()) { try { Thread.sleep(100); } catch (InterruptedException e) { throw new AssertionError(e); } } excise(token, endpoint); // indicate the token has left Gossiper.instance.addLocalApplicationState(ApplicationState.STATUS, valueFactory.removedNonlocal(localToken, token)); replicatingNodes = null; removingNode = null; } public void confirmReplication(InetAddress node) { assert replicatingNodes != null; replicatingNodes.remove(node); } public boolean isClientMode() { return isClientMode; } public synchronized void requestGC() { if (hasUnreclaimedSpace()) { logger_.info("requesting GC to free disk space"); System.gc(); try { Thread.sleep(1000); } catch (InterruptedException e) { throw new AssertionError(e); } } } private boolean hasUnreclaimedSpace() { for (ColumnFamilyStore cfs : ColumnFamilyStore.all()) { if (cfs.hasUnreclaimedSpace()) return true; } return false; } public String getOperationMode() { return operationMode; } public String getDrainProgress() { return String.format("Drained %s/%s ColumnFamilies", remainingCFs, totalCFs); } /** shuts node off to writes, empties memtables and the commit log. */ public synchronized void drain() throws IOException, InterruptedException, ExecutionException { ExecutorService mutationStage = StageManager.getStage(Stage.MUTATION); if (mutationStage.isTerminated()) { logger_.warn("Cannot drain node (did it already happen?)"); return; } setMode("Starting drain process", true); Gossiper.instance.stop(); setMode("Draining: shutting down MessageService", false); MessagingService.shutdown(); setMode("Draining: emptying MessageService pools", false); MessagingService.waitFor(); setMode("Draining: clearing mutation stage", false); mutationStage.shutdown(); mutationStage.awaitTermination(3600, TimeUnit.SECONDS); // lets flush. setMode("Draining: flushing column families", false); List<ColumnFamilyStore> cfses = new ArrayList<ColumnFamilyStore>(); for (String tableName : DatabaseDescriptor.getNonSystemTables()) { Table table = Table.open(tableName); cfses.addAll(table.getColumnFamilyStores()); } totalCFs = remainingCFs = cfses.size(); for (ColumnFamilyStore cfs : cfses) { cfs.forceBlockingFlush(); remainingCFs--; } ColumnFamilyStore.postFlushExecutor.shutdown(); ColumnFamilyStore.postFlushExecutor.awaitTermination(60, TimeUnit.SECONDS); // want to make sure that any segments deleted as a result of flushing are gone. DeletionService.waitFor(); setMode("Node is drained", true); } /** * load schema from yaml. This can only be done on a fresh system. * @throws ConfigurationException * @throws IOException */ public void loadSchemaFromYAML() throws ConfigurationException, IOException { // validate final Collection<KSMetaData> tables = DatabaseDescriptor.readTablesFromYaml(); for (KSMetaData table : tables) { if (!table.name.matches(Migration.NAME_VALIDATOR_REGEX)) throw new ConfigurationException("Invalid table name: " + table.name); for (CFMetaData cfm : table.cfMetaData().values()) if (!Migration.isLegalName(cfm.cfName)) throw new ConfigurationException("Invalid column family name: " + cfm.cfName); } Callable<Migration> call = new Callable<Migration>() { public Migration call() throws Exception { // blow up if there is a schema saved. if (DatabaseDescriptor.getDefsVersion().timestamp() > 0 || Migration.getLastMigrationId() != null) throw new ConfigurationException("Cannot import schema when one already exists"); Migration migration = null; for (KSMetaData table : tables) { migration = new AddKeyspace(table); migration.apply(); } return migration; } }; Migration migration; try { migration = StageManager.getStage(Stage.MIGRATION).submit(call).get(); } catch (InterruptedException e) { throw new RuntimeException(e); } catch (ExecutionException e) { if (e.getCause() instanceof ConfigurationException) throw (ConfigurationException)e.getCause(); else if (e.getCause() instanceof IOException) throw (IOException)e.getCause(); else if (e.getCause() instanceof Exception) throw new ConfigurationException(e.getCause().getMessage(), (Exception)e.getCause()); else throw new RuntimeException(e); } assert DatabaseDescriptor.getDefsVersion().timestamp() > 0; DefsTable.dumpToStorage(DatabaseDescriptor.getDefsVersion()); // flush system and definition tables. Collection<Future> flushers = new ArrayList<Future>(); flushers.addAll(Table.open(Table.SYSTEM_TABLE).flush()); for (Future f : flushers) { try { f.get(); } catch (Exception e) { ConfigurationException ce = new ConfigurationException(e.getMessage()); ce.initCause(e); throw ce; } } // we don't want to announce after every Migration.apply(). keep track of the last one and then announce the // current version. if (migration != null) migration.announce(); } public String exportSchema() throws IOException { List<RawKeyspace> keyspaces = new ArrayList<RawKeyspace>(); for (String ksname : DatabaseDescriptor.getNonSystemTables()) { KSMetaData ksm = DatabaseDescriptor.getTableDefinition(ksname); RawKeyspace rks = new RawKeyspace(); rks.name = ksm.name; rks.replica_placement_strategy = ksm.strategyClass.getName(); rks.replication_factor = ksm.replicationFactor; rks.column_families = new RawColumnFamily[ksm.cfMetaData().size()]; int i = 0; for (CFMetaData cfm : ksm.cfMetaData().values()) { RawColumnFamily rcf = new RawColumnFamily(); rcf.name = cfm.cfName; rcf.compare_with = cfm.comparator.getClass().getName(); rcf.default_validation_class = cfm.defaultValidator.getClass().getName(); rcf.compare_subcolumns_with = cfm.subcolumnComparator == null ? null : cfm.subcolumnComparator.getClass().getName(); rcf.column_type = cfm.cfType; rcf.comment = cfm.comment; rcf.keys_cached = cfm.keyCacheSize; rcf.read_repair_chance = cfm.readRepairChance; rcf.gc_grace_seconds = cfm.gcGraceSeconds; rcf.rows_cached = cfm.rowCacheSize; rcf.column_metadata = new RawColumnDefinition[cfm.column_metadata.size()]; int j = 0; for (ColumnDefinition cd : cfm.column_metadata.values()) { RawColumnDefinition rcd = new RawColumnDefinition(); rcd.index_name = cd.index_name; rcd.index_type = cd.index_type; rcd.name = ByteBufferUtil.string(cd.name, Charsets.UTF_8); rcd.validator_class = cd.validator.getClass().getName(); rcf.column_metadata[j++] = rcd; } if (j == 0) rcf.column_metadata = null; rks.column_families[i++] = rcf; } // whew. keyspaces.add(rks); } DumperOptions options = new DumperOptions(); /* Use a block YAML arrangement */ options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); SkipNullRepresenter representer = new SkipNullRepresenter(); /* Use Tag.MAP to avoid the class name being included as global tag */ representer.addClassTag(RawColumnFamily.class, Tag.MAP); representer.addClassTag(Keyspaces.class, Tag.MAP); representer.addClassTag(ColumnDefinition.class, Tag.MAP); Dumper dumper = new Dumper(representer, options); Yaml yaml = new Yaml(dumper); Keyspaces ks = new Keyspaces(); ks.keyspaces = keyspaces; return yaml.dump(ks); } public class Keyspaces { public List<RawKeyspace> keyspaces; } // Never ever do this at home. Used by tests. IPartitioner setPartitionerUnsafe(IPartitioner newPartitioner) { IPartitioner oldPartitioner = partitioner_; partitioner_ = newPartitioner; valueFactory = new VersionedValue.VersionedValueFactory(partitioner_); return oldPartitioner; } TokenMetadata setTokenMetadataUnsafe(TokenMetadata tmd) { TokenMetadata old = tokenMetadata_; tokenMetadata_ = tmd; return old; } public void truncate(String keyspace, String columnFamily) throws UnavailableException, TimeoutException, IOException { StorageProxy.truncateBlocking(keyspace, columnFamily); } public void saveCaches() throws ExecutionException, InterruptedException { List<Future<?>> futures = new ArrayList<Future<?>>(); logger_.debug("submitting cache saves"); for (ColumnFamilyStore cfs : ColumnFamilyStore.all()) { futures.add(cfs.submitKeyCacheWrite()); futures.add(cfs.submitRowCacheWrite()); } FBUtilities.waitOnFutures(futures); logger_.debug("cache saves completed"); } }
true
true
public synchronized void initServer() throws IOException, org.apache.cassandra.config.ConfigurationException { logger_.info("Cassandra version: " + FBUtilities.getReleaseVersionString()); logger_.info("Thrift API version: " + Constants.VERSION); if (initialized) { if (isClientMode) throw new UnsupportedOperationException("StorageService does not support switching modes."); return; } initialized = true; isClientMode = false; try { GCInspector.instance.start(); } catch (Throwable t) { logger_.warn("Unable to start GCInspector (currently only supported on the Sun JVM)"); } if (Boolean.valueOf(System.getProperty("cassandra.load_ring_state", "true"))) { logger_.info("Loading persisted ring state"); for (Map.Entry<Token, InetAddress> entry : SystemTable.loadTokens().entrySet()) { tokenMetadata_.updateNormalToken(entry.getKey(), entry.getValue()); Gossiper.instance.addSavedEndpoint(entry.getValue()); } } logger_.info("Starting up server gossip"); // have to start the gossip service before we can see any info on other nodes. this is necessary // for bootstrap to get the load info it needs. // (we won't be part of the storage ring though until we add a nodeId to our state, below.) Gossiper.instance.register(this); Gossiper.instance.register(migrationManager); Gossiper.instance.start(FBUtilities.getLocalAddress(), SystemTable.incrementAndGetGeneration()); // needed for node-ring gathering. MessagingService.instance.listen(FBUtilities.getLocalAddress()); StorageLoadBalancer.instance.startBroadcasting(); MigrationManager.announce(DatabaseDescriptor.getDefsVersion(), DatabaseDescriptor.getSeeds()); if (DatabaseDescriptor.isAutoBootstrap() && DatabaseDescriptor.getSeeds().contains(FBUtilities.getLocalAddress()) && !SystemTable.isBootstrapped()) logger_.info("This node will not auto bootstrap because it is configured to be a seed node."); if (DatabaseDescriptor.isAutoBootstrap() && !(DatabaseDescriptor.getSeeds().contains(FBUtilities.getLocalAddress()) || SystemTable.isBootstrapped())) { setMode("Joining: getting load information", true); StorageLoadBalancer.instance.waitForLoadInfo(); if (logger_.isDebugEnabled()) logger_.debug("... got load info"); if (tokenMetadata_.isMember(FBUtilities.getLocalAddress())) { String s = "This node is already a member of the token ring; bootstrap aborted. (If replacing a dead node, remove the old one from the ring first.)"; throw new UnsupportedOperationException(s); } setMode("Joining: getting bootstrap token", true); Token token = BootStrapper.getBootstrapToken(tokenMetadata_, StorageLoadBalancer.instance.getLoadInfo()); // don't bootstrap if there are no tables defined. if (DatabaseDescriptor.getNonSystemTables().size() > 0) { bootstrap(token); assert !isBootstrapMode; // bootstrap will block until finished } else { isBootstrapMode = false; SystemTable.setBootstrapped(true); tokenMetadata_.updateNormalToken(token, FBUtilities.getLocalAddress()); Gossiper.instance.addLocalApplicationState(ApplicationState.STATUS, valueFactory.normal(token)); setMode("Normal", false); } } else { Token token = SystemTable.getSavedToken(); if (token == null) { String initialToken = DatabaseDescriptor.getInitialToken(); if (initialToken == null) { token = partitioner_.getRandomToken(); logger_.warn("Generated random token " + token + ". Random tokens will result in an unbalanced ring; see http://wiki.apache.org/cassandra/Operations"); } else { token = partitioner_.getTokenFactory().fromString(initialToken); logger_.info("Saved token not found. Using " + token + " from configuration"); } SystemTable.updateToken(token); } else { logger_.info("Using saved token " + token); } SystemTable.setBootstrapped(true); tokenMetadata_.updateNormalToken(token, FBUtilities.getLocalAddress()); Gossiper.instance.addLocalApplicationState(ApplicationState.STATUS, valueFactory.normal(token)); setMode("Normal", false); } assert tokenMetadata_.sortedTokens().size() > 0; }
public synchronized void initServer() throws IOException, org.apache.cassandra.config.ConfigurationException { logger_.info("Cassandra version: " + FBUtilities.getReleaseVersionString()); logger_.info("Thrift API version: " + Constants.VERSION); if (initialized) { if (isClientMode) throw new UnsupportedOperationException("StorageService does not support switching modes."); return; } initialized = true; isClientMode = false; try { GCInspector.instance.start(); } catch (Throwable t) { logger_.warn("Unable to start GCInspector (currently only supported on the Sun JVM)"); } if (Boolean.valueOf(System.getProperty("cassandra.load_ring_state", "true"))) { logger_.info("Loading persisted ring state"); for (Map.Entry<Token, InetAddress> entry : SystemTable.loadTokens().entrySet()) { tokenMetadata_.updateNormalToken(entry.getKey(), entry.getValue()); Gossiper.instance.addSavedEndpoint(entry.getValue()); } } logger_.info("Starting up server gossip"); // have to start the gossip service before we can see any info on other nodes. this is necessary // for bootstrap to get the load info it needs. // (we won't be part of the storage ring though until we add a nodeId to our state, below.) Gossiper.instance.register(this); Gossiper.instance.register(migrationManager); Gossiper.instance.start(FBUtilities.getLocalAddress(), SystemTable.incrementAndGetGeneration()); // needed for node-ring gathering. MessagingService.instance.listen(FBUtilities.getLocalAddress()); StorageLoadBalancer.instance.startBroadcasting(); MigrationManager.announce(DatabaseDescriptor.getDefsVersion(), DatabaseDescriptor.getSeeds()); if (DatabaseDescriptor.isAutoBootstrap() && DatabaseDescriptor.getSeeds().contains(FBUtilities.getLocalAddress()) && !SystemTable.isBootstrapped()) logger_.info("This node will not auto bootstrap because it is configured to be a seed node."); if (DatabaseDescriptor.isAutoBootstrap() && !(DatabaseDescriptor.getSeeds().contains(FBUtilities.getLocalAddress()) || SystemTable.isBootstrapped())) { setMode("Joining: getting load information", true); StorageLoadBalancer.instance.waitForLoadInfo(); if (logger_.isDebugEnabled()) logger_.debug("... got load info"); if (tokenMetadata_.isMember(FBUtilities.getLocalAddress())) { String s = "This node is already a member of the token ring; bootstrap aborted. (If replacing a dead node, remove the old one from the ring first.)"; throw new UnsupportedOperationException(s); } setMode("Joining: getting bootstrap token", true); Token token = BootStrapper.getBootstrapToken(tokenMetadata_, StorageLoadBalancer.instance.getLoadInfo()); // don't bootstrap if there are no tables defined. if (DatabaseDescriptor.getNonSystemTables().size() > 0) { bootstrap(token); assert !isBootstrapMode; // bootstrap will block until finished } else { isBootstrapMode = false; SystemTable.setBootstrapped(true); setToken(token); Gossiper.instance.addLocalApplicationState(ApplicationState.STATUS, valueFactory.normal(token)); setMode("Normal", false); } } else { Token token = SystemTable.getSavedToken(); if (token == null) { String initialToken = DatabaseDescriptor.getInitialToken(); if (initialToken == null) { token = partitioner_.getRandomToken(); logger_.warn("Generated random token " + token + ". Random tokens will result in an unbalanced ring; see http://wiki.apache.org/cassandra/Operations"); } else { token = partitioner_.getTokenFactory().fromString(initialToken); logger_.info("Saved token not found. Using " + token + " from configuration"); } SystemTable.updateToken(token); } else { logger_.info("Using saved token " + token); } SystemTable.setBootstrapped(true); tokenMetadata_.updateNormalToken(token, FBUtilities.getLocalAddress()); Gossiper.instance.addLocalApplicationState(ApplicationState.STATUS, valueFactory.normal(token)); setMode("Normal", false); } assert tokenMetadata_.sortedTokens().size() > 0; }
diff --git a/Datenbanken/WahlWebsite/src/queries/Q5_WITH.java b/Datenbanken/WahlWebsite/src/queries/Q5_WITH.java index 38b53cb..6ff3936 100644 --- a/Datenbanken/WahlWebsite/src/queries/Q5_WITH.java +++ b/Datenbanken/WahlWebsite/src/queries/Q5_WITH.java @@ -1,67 +1,71 @@ package queries; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import database.DB; public class Q5_WITH extends Query { public Q5_WITH(String headline) { super(headline); } @Override protected String generateBody(ResultSet resultSet) throws SQLException { String[] headers = new String[] {"Bundesland", "Partei", "�berhangsmandate"}; List<List<String>> rows = new ArrayList<List<String>>(); while (resultSet.next()) { List<String> row = new ArrayList<String>(); row.add(resultSet.getString(DB.kBundeslandName)); row.add(resultSet.getString(DB.kParteiKuerzel)); row.add(resultSet.getString(DB.kAnzahlUeberhangsmandate)); rows.add(row); } Table table = new Table(headers, rows); return table.getHtml(); } @Override protected ResultSet doQuery() throws SQLException { String query = "WITH " + db.zweitStimmenNachBundesland() + " AS (" + stmtZweitStimmenNachBundesland() + "), " + db.zweitStimmenNachPartei() + " AS (" + stmtZweitStimmenNachPartei(db.zweitStimmenNachBundesland()) + "), " + + db.maxErststimmenNachWahlkreis() + " AS (" + + stmtMaxErststimmenNachWahlkreis(db.erstStimmenNachWahlkreis()) + "), " + db.direktMandateNummer() + " AS ( " + stmtDirektmandateNummer(db.maxErststimmenNachWahlkreis(), db.erstStimmenNachWahlkreis()) + "), " + db.direktMandateMaxNummer() + " AS ( " + stmtDirektmandateMaxNummer(db.direktMandateNummer()) + "), " + db.direktmandate() + " AS (" + stmtDirektmandate(db.direktMandateNummer(), db.direktMandateMaxNummer()) + "), " + db.fuenfProzentParteien() + " AS (" + stmtFuenfProzentParteien(db.zweitStimmenNachPartei()) + "), " + db.dreiDirektMandatParteien() + " AS (" + stmtDreiDirektmandateParteien(db.direktmandate()) + "), " + db.parteienImBundestag() + " AS (" + stmtParteienImBundestag(db.fuenfProzentParteien(), db.dreiDirektMandatParteien()) + "), " + db.divisoren() + " AS (" + stmtDivisoren() + "), " + db.zugriffsreihenfolgeSitzeNachPartei() + " AS (" + stmtZugriffsreihenfolgeSitzeNachPartei( db.parteienImBundestag(), db.zweitStimmenNachPartei(), db.divisoren()) + "), " + db.sitzeNachPartei() + " AS (" + stmtSitzeNachParteiTable( - db.zweitStimmenNachPartei(), db.parteienImBundestag(), db.zugriffsreihenfolgeSitzeNachPartei()) + ", " + db.zweitStimmenNachPartei(), db.parteienImBundestag(), db.zugriffsreihenfolgeSitzeNachPartei()) + "), " + db.zugriffsreihenfolgeSitzeNachLandeslisten() + " AS (" + stmtZugriffsreihenfolgeSitzeNachLandeslisten( - db.parteienImBundestag(), db.zweitStimmenNachBundesland(), db.divisoren()) + ", " + db.parteienImBundestag(), db.zweitStimmenNachBundesland(), db.divisoren()) + "), " + db.sitzeNachLandeslisten() + " AS (" + stmtSitzeNachLandeslisten(db.parteienImBundestag(), - db.zweitStimmenNachBundesland(), db.sitzeNachPartei(), db.zugriffsreihenfolgeSitzeNachLandeslisten()) + ", " + db.zweitStimmenNachBundesland(), db.sitzeNachPartei(), db.zugriffsreihenfolgeSitzeNachLandeslisten()) + "), " + + db.direktMandateProParteiUndBundesland() + " AS (" + + stmtDirektMandateProParteiUndBundesland(db.direktmandate()) + "), " + db.ueberhangsMandate() + " AS (" + stmtUeberhangsmandate(db.direktmandate(), db.sitzeNachLandeslisten(), db.direktMandateProParteiUndBundesland()) + ") " + "SELECT * FROM " + db.ueberhangsMandate(); return db.executeSQL(query); } }
false
true
protected ResultSet doQuery() throws SQLException { String query = "WITH " + db.zweitStimmenNachBundesland() + " AS (" + stmtZweitStimmenNachBundesland() + "), " + db.zweitStimmenNachPartei() + " AS (" + stmtZweitStimmenNachPartei(db.zweitStimmenNachBundesland()) + "), " + db.direktMandateNummer() + " AS ( " + stmtDirektmandateNummer(db.maxErststimmenNachWahlkreis(), db.erstStimmenNachWahlkreis()) + "), " + db.direktMandateMaxNummer() + " AS ( " + stmtDirektmandateMaxNummer(db.direktMandateNummer()) + "), " + db.direktmandate() + " AS (" + stmtDirektmandate(db.direktMandateNummer(), db.direktMandateMaxNummer()) + "), " + db.fuenfProzentParteien() + " AS (" + stmtFuenfProzentParteien(db.zweitStimmenNachPartei()) + "), " + db.dreiDirektMandatParteien() + " AS (" + stmtDreiDirektmandateParteien(db.direktmandate()) + "), " + db.parteienImBundestag() + " AS (" + stmtParteienImBundestag(db.fuenfProzentParteien(), db.dreiDirektMandatParteien()) + "), " + db.divisoren() + " AS (" + stmtDivisoren() + "), " + db.zugriffsreihenfolgeSitzeNachPartei() + " AS (" + stmtZugriffsreihenfolgeSitzeNachPartei( db.parteienImBundestag(), db.zweitStimmenNachPartei(), db.divisoren()) + "), " + db.sitzeNachPartei() + " AS (" + stmtSitzeNachParteiTable( db.zweitStimmenNachPartei(), db.parteienImBundestag(), db.zugriffsreihenfolgeSitzeNachPartei()) + ", " + db.zugriffsreihenfolgeSitzeNachLandeslisten() + " AS (" + stmtZugriffsreihenfolgeSitzeNachLandeslisten( db.parteienImBundestag(), db.zweitStimmenNachBundesland(), db.divisoren()) + ", " + db.sitzeNachLandeslisten() + " AS (" + stmtSitzeNachLandeslisten(db.parteienImBundestag(), db.zweitStimmenNachBundesland(), db.sitzeNachPartei(), db.zugriffsreihenfolgeSitzeNachLandeslisten()) + ", " + db.ueberhangsMandate() + " AS (" + stmtUeberhangsmandate(db.direktmandate(), db.sitzeNachLandeslisten(), db.direktMandateProParteiUndBundesland()) + ") " + "SELECT * FROM " + db.ueberhangsMandate(); return db.executeSQL(query); }
protected ResultSet doQuery() throws SQLException { String query = "WITH " + db.zweitStimmenNachBundesland() + " AS (" + stmtZweitStimmenNachBundesland() + "), " + db.zweitStimmenNachPartei() + " AS (" + stmtZweitStimmenNachPartei(db.zweitStimmenNachBundesland()) + "), " + db.maxErststimmenNachWahlkreis() + " AS (" + stmtMaxErststimmenNachWahlkreis(db.erstStimmenNachWahlkreis()) + "), " + db.direktMandateNummer() + " AS ( " + stmtDirektmandateNummer(db.maxErststimmenNachWahlkreis(), db.erstStimmenNachWahlkreis()) + "), " + db.direktMandateMaxNummer() + " AS ( " + stmtDirektmandateMaxNummer(db.direktMandateNummer()) + "), " + db.direktmandate() + " AS (" + stmtDirektmandate(db.direktMandateNummer(), db.direktMandateMaxNummer()) + "), " + db.fuenfProzentParteien() + " AS (" + stmtFuenfProzentParteien(db.zweitStimmenNachPartei()) + "), " + db.dreiDirektMandatParteien() + " AS (" + stmtDreiDirektmandateParteien(db.direktmandate()) + "), " + db.parteienImBundestag() + " AS (" + stmtParteienImBundestag(db.fuenfProzentParteien(), db.dreiDirektMandatParteien()) + "), " + db.divisoren() + " AS (" + stmtDivisoren() + "), " + db.zugriffsreihenfolgeSitzeNachPartei() + " AS (" + stmtZugriffsreihenfolgeSitzeNachPartei( db.parteienImBundestag(), db.zweitStimmenNachPartei(), db.divisoren()) + "), " + db.sitzeNachPartei() + " AS (" + stmtSitzeNachParteiTable( db.zweitStimmenNachPartei(), db.parteienImBundestag(), db.zugriffsreihenfolgeSitzeNachPartei()) + "), " + db.zugriffsreihenfolgeSitzeNachLandeslisten() + " AS (" + stmtZugriffsreihenfolgeSitzeNachLandeslisten( db.parteienImBundestag(), db.zweitStimmenNachBundesland(), db.divisoren()) + "), " + db.sitzeNachLandeslisten() + " AS (" + stmtSitzeNachLandeslisten(db.parteienImBundestag(), db.zweitStimmenNachBundesland(), db.sitzeNachPartei(), db.zugriffsreihenfolgeSitzeNachLandeslisten()) + "), " + db.direktMandateProParteiUndBundesland() + " AS (" + stmtDirektMandateProParteiUndBundesland(db.direktmandate()) + "), " + db.ueberhangsMandate() + " AS (" + stmtUeberhangsmandate(db.direktmandate(), db.sitzeNachLandeslisten(), db.direktMandateProParteiUndBundesland()) + ") " + "SELECT * FROM " + db.ueberhangsMandate(); return db.executeSQL(query); }
diff --git a/src/java/org/apache/cassandra/dht/OrderPreservingPartitioner.java b/src/java/org/apache/cassandra/dht/OrderPreservingPartitioner.java index 5a2e6b3b..031cbeb0 100644 --- a/src/java/org/apache/cassandra/dht/OrderPreservingPartitioner.java +++ b/src/java/org/apache/cassandra/dht/OrderPreservingPartitioner.java @@ -1,205 +1,205 @@ /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.cassandra.dht; import java.math.BigInteger; import java.nio.ByteBuffer; import java.nio.charset.CharacterCodingException; import java.util.*; import org.apache.cassandra.config.CFMetaData; import org.apache.cassandra.config.DatabaseDescriptor; import org.apache.cassandra.db.DecoratedKey; import org.apache.cassandra.service.StorageService; import org.apache.cassandra.utils.ByteBufferUtil; import org.apache.cassandra.utils.FBUtilities; import org.apache.cassandra.utils.Pair; public class OrderPreservingPartitioner implements IPartitioner<StringToken> { public static final StringToken MINIMUM = new StringToken(""); public static final BigInteger CHAR_MASK = new BigInteger("65535"); public DecoratedKey<StringToken> decorateKey(ByteBuffer key) { return new DecoratedKey<StringToken>(getToken(key), key); } public DecoratedKey<StringToken> convertFromDiskFormat(ByteBuffer key) { return new DecoratedKey<StringToken>(getToken(key), key); } public StringToken midpoint(Token ltoken, Token rtoken) { int sigchars = Math.max(((StringToken)ltoken).token.length(), ((StringToken)rtoken).token.length()); BigInteger left = bigForString(((StringToken)ltoken).token, sigchars); BigInteger right = bigForString(((StringToken)rtoken).token, sigchars); Pair<BigInteger,Boolean> midpair = FBUtilities.midpoint(left, right, 16*sigchars); return new StringToken(stringForBig(midpair.left, sigchars, midpair.right)); } /** * Copies the characters of the given string into a BigInteger. * * TODO: Does not acknowledge any codepoints above 0xFFFF... problem? */ private static BigInteger bigForString(String str, int sigchars) { assert str.length() <= sigchars; BigInteger big = BigInteger.ZERO; for (int i = 0; i < str.length(); i++) { int charpos = 16 * (sigchars - (i + 1)); BigInteger charbig = BigInteger.valueOf(str.charAt(i) & 0xFFFF); big = big.or(charbig.shiftLeft(charpos)); } return big; } /** * Convert a (positive) BigInteger into a String. * If remainder is true, an additional char with the high order bit enabled * will be added to the end of the String. */ private String stringForBig(BigInteger big, int sigchars, boolean remainder) { char[] chars = new char[sigchars + (remainder ? 1 : 0)]; if (remainder) // remaining bit is the most significant in the last char chars[sigchars] |= 0x8000; for (int i = 0; i < sigchars; i++) { int maskpos = 16 * (sigchars - (i + 1)); // apply bitmask and get char value chars[i] = (char)(big.and(CHAR_MASK.shiftLeft(maskpos)).shiftRight(maskpos).intValue() & 0xFFFF); } return new String(chars); } public StringToken getMinimumToken() { return MINIMUM; } public StringToken getRandomToken() { String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; Random r = new Random(); StringBuilder buffer = new StringBuilder(); for (int j = 0; j < 16; j++) { buffer.append(chars.charAt(r.nextInt(chars.length()))); } return new StringToken(buffer.toString()); } private final Token.TokenFactory<String> tokenFactory = new Token.TokenFactory<String>() { public ByteBuffer toByteArray(Token<String> stringToken) { return ByteBufferUtil.bytes(stringToken.token); } public Token<String> fromByteArray(ByteBuffer bytes) { try { return new StringToken(ByteBufferUtil.string(bytes)); } catch (CharacterCodingException e) { throw new RuntimeException(e); } } public String toString(Token<String> stringToken) { return stringToken.token; } public Token<String> fromString(String string) { return new StringToken(string); } }; public Token.TokenFactory<String> getTokenFactory() { return tokenFactory; } public boolean preservesOrder() { return true; } public StringToken getToken(ByteBuffer key) { String skey; try { skey = ByteBufferUtil.string(key); } catch (CharacterCodingException e) { throw new RuntimeException("The provided key was not UTF8 encoded.", e); } return new StringToken(skey); } public Map<Token, Float> describeOwnership(List<Token> sortedTokens) { // allTokens will contain the count and be returned, sorted_ranges is shorthand for token<->token math. Map<Token, Float> allTokens = new HashMap<Token, Float>(); List<Range> sortedRanges = new ArrayList<Range>(); // this initializes the counts to 0 and calcs the ranges in order. Token lastToken = sortedTokens.get(sortedTokens.size() - 1); for (Token node : sortedTokens) { allTokens.put(node, new Float(0.0)); sortedRanges.add(new Range(lastToken, node)); lastToken = node; } for (String ks : DatabaseDescriptor.getTables()) { for (CFMetaData cfmd : DatabaseDescriptor.getKSMetaData(ks).cfMetaData().values()) { for (Range r : sortedRanges) { // Looping over every KS:CF:Range, get the splits size and add it to the count - allTokens.put(r.right, allTokens.get(r.right) + StorageService.instance.getSplits(ks, cfmd.cfName, r, 1).size()); + allTokens.put(r.right, allTokens.get(r.right) + StorageService.instance.getSplits(ks, cfmd.cfName, r, DatabaseDescriptor.getIndexInterval()).size()); } } } // Sum every count up and divide count/total for the fractional ownership. Float total = new Float(0.0); for (Float f : allTokens.values()) total += f; for (Map.Entry<Token, Float> row : allTokens.entrySet()) allTokens.put(row.getKey(), row.getValue() / total); return allTokens; } }
true
true
public Map<Token, Float> describeOwnership(List<Token> sortedTokens) { // allTokens will contain the count and be returned, sorted_ranges is shorthand for token<->token math. Map<Token, Float> allTokens = new HashMap<Token, Float>(); List<Range> sortedRanges = new ArrayList<Range>(); // this initializes the counts to 0 and calcs the ranges in order. Token lastToken = sortedTokens.get(sortedTokens.size() - 1); for (Token node : sortedTokens) { allTokens.put(node, new Float(0.0)); sortedRanges.add(new Range(lastToken, node)); lastToken = node; } for (String ks : DatabaseDescriptor.getTables()) { for (CFMetaData cfmd : DatabaseDescriptor.getKSMetaData(ks).cfMetaData().values()) { for (Range r : sortedRanges) { // Looping over every KS:CF:Range, get the splits size and add it to the count allTokens.put(r.right, allTokens.get(r.right) + StorageService.instance.getSplits(ks, cfmd.cfName, r, 1).size()); } } } // Sum every count up and divide count/total for the fractional ownership. Float total = new Float(0.0); for (Float f : allTokens.values()) total += f; for (Map.Entry<Token, Float> row : allTokens.entrySet()) allTokens.put(row.getKey(), row.getValue() / total); return allTokens; }
public Map<Token, Float> describeOwnership(List<Token> sortedTokens) { // allTokens will contain the count and be returned, sorted_ranges is shorthand for token<->token math. Map<Token, Float> allTokens = new HashMap<Token, Float>(); List<Range> sortedRanges = new ArrayList<Range>(); // this initializes the counts to 0 and calcs the ranges in order. Token lastToken = sortedTokens.get(sortedTokens.size() - 1); for (Token node : sortedTokens) { allTokens.put(node, new Float(0.0)); sortedRanges.add(new Range(lastToken, node)); lastToken = node; } for (String ks : DatabaseDescriptor.getTables()) { for (CFMetaData cfmd : DatabaseDescriptor.getKSMetaData(ks).cfMetaData().values()) { for (Range r : sortedRanges) { // Looping over every KS:CF:Range, get the splits size and add it to the count allTokens.put(r.right, allTokens.get(r.right) + StorageService.instance.getSplits(ks, cfmd.cfName, r, DatabaseDescriptor.getIndexInterval()).size()); } } } // Sum every count up and divide count/total for the fractional ownership. Float total = new Float(0.0); for (Float f : allTokens.values()) total += f; for (Map.Entry<Token, Float> row : allTokens.entrySet()) allTokens.put(row.getKey(), row.getValue() / total); return allTokens; }
diff --git a/src/org/ita/neutrino/astparser/ASTMethod.java b/src/org/ita/neutrino/astparser/ASTMethod.java index 417c6db..9caed00 100644 --- a/src/org/ita/neutrino/astparser/ASTMethod.java +++ b/src/org/ita/neutrino/astparser/ASTMethod.java @@ -1,181 +1,181 @@ package org.ita.neutrino.astparser; import java.util.ArrayList; import java.util.List; import org.eclipse.jdt.core.dom.AST; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.Block; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.NormalAnnotation; import org.eclipse.jdt.core.dom.rewrite.ASTRewrite; import org.eclipse.jdt.core.dom.rewrite.ListRewrite; import org.ita.neutrino.codeparser.AbstractCodeElement; import org.ita.neutrino.codeparser.Annotation; import org.ita.neutrino.codeparser.Argument; import org.ita.neutrino.codeparser.CheckedExceptionClass; import org.ita.neutrino.codeparser.MutableMethod; import org.ita.neutrino.codeparser.Statement; import org.ita.neutrino.codeparser.Type; public class ASTMethod extends AbstractCodeElement implements MutableMethod, ASTWrapper<MethodDeclaration> { private ASTInnerElementAccessModifier accessModifier = new ASTInnerElementAccessModifier(); private String name; private ASTMethodDeclarationNonAccessModifier nonAccessModifier = new ASTMethodDeclarationNonAccessModifier(); private MethodDeclaration astObject; private ASTBlock body; private List<Annotation> annotationList = new ArrayList<Annotation>(); ASTBlock createBlock() { ASTBlock methodBlock = new ASTBlock(); methodBlock.setParent(this); return methodBlock; } @Override public ASTInnerElementAccessModifier getAccessModifier() { return accessModifier; } void setAccessModifier(ASTInnerElementAccessModifier accessModifier) { this.accessModifier = accessModifier; } void setName(String name) { this.name = name; } @Override public String getName() { return name; } void setParentType(Type parent) { this.parent = parent; } public Type getParent() { return (Type) super.getParent(); } @Override public List<Annotation> getAnnotations() { return annotationList; } @Override public ASTMethodDeclarationNonAccessModifier getNonAccessModifier() { return nonAccessModifier; } void setNonAccessModifier(ASTMethodDeclarationNonAccessModifier nonAccessModifier) { this.nonAccessModifier = nonAccessModifier; } @Override public Type getReturnType() { return null; } @Override public List<Argument> getArgumentList() { return null; } @Override public List<CheckedExceptionClass> getThrownExceptions() { return null; } @Override public void setASTObject(MethodDeclaration astObject) { this.astObject = astObject; } @Override public MethodDeclaration getASTObject() { return astObject; } @Override public ASTBlock getBody() { if (nonAccessModifier.isAbstract()) { return null; } if (body == null) { body = createBlock(); } return body; } @Override public String toString() { return name; } /** * Mutable method. */ @Override public void addAnnotation(Type annotation) { AST ast = astObject.getAST(); ASTRewrite rewrite = ((ASTSourceFile) getParent().getParent()).getASTObject().getRewrite(); NormalAnnotation astAnnotation = ast.newNormalAnnotation(); astAnnotation.setTypeName(ast.newName(annotation.getQualifiedName())); rewrite.getListRewrite(astObject, MethodDeclaration.MODIFIERS2_PROPERTY).insertFirst(astAnnotation, null); } @SuppressWarnings("unchecked") @Override public void addStatements(List<Statement> codeStatements, int index) { Block block = getASTObject().getBody(); AST ast = astObject.getAST(); ASTRewrite rewrite = ((ASTType) getParent()).getParent().getASTObject().getRewrite(); ListRewrite lrw = rewrite.getListRewrite(block, Block.STATEMENTS_PROPERTY); - int originalListSize = lrw.getOriginalList().size() - 1; + int originalListSize = lrw.getOriginalList().size(); - for (Statement statement : codeStatements) { - ASTAbstractStatement<ASTNode> astStatement = (ASTAbstractStatement<ASTNode>) statement; + for (int i=0; i<codeStatements.size(); i++) { + ASTAbstractStatement<ASTNode> astStatement = (ASTAbstractStatement<ASTNode>) codeStatements.get(i); ASTNode astNode = astStatement.getASTObject(); ASTNode copyOfAstNode = ASTNode.copySubtree(ast, astNode); // block.statements().add(copyOfAstNode); if (index == -1) { lrw.insertAt(copyOfAstNode, originalListSize, null); } else { - lrw.insertAt(copyOfAstNode, index, null); + lrw.insertAt(copyOfAstNode, index+i, null); } } } @Override public void removeStatements(int index, int count) { @SuppressWarnings("unchecked") List<ASTNode> statements = getASTObject().getBody().statements(); ASTRewrite rewrite = ((ASTType) getParent()).getParent().getASTObject().getRewrite(); ListRewrite listRewrite = rewrite.getListRewrite(getASTObject().getBody(), Block.STATEMENTS_PROPERTY); for (int i = index; i < index + count; i++) { listRewrite.remove(statements.get(i), null); } } }
false
true
public void addStatements(List<Statement> codeStatements, int index) { Block block = getASTObject().getBody(); AST ast = astObject.getAST(); ASTRewrite rewrite = ((ASTType) getParent()).getParent().getASTObject().getRewrite(); ListRewrite lrw = rewrite.getListRewrite(block, Block.STATEMENTS_PROPERTY); int originalListSize = lrw.getOriginalList().size() - 1; for (Statement statement : codeStatements) { ASTAbstractStatement<ASTNode> astStatement = (ASTAbstractStatement<ASTNode>) statement; ASTNode astNode = astStatement.getASTObject(); ASTNode copyOfAstNode = ASTNode.copySubtree(ast, astNode); // block.statements().add(copyOfAstNode); if (index == -1) { lrw.insertAt(copyOfAstNode, originalListSize, null); } else { lrw.insertAt(copyOfAstNode, index, null); } } }
public void addStatements(List<Statement> codeStatements, int index) { Block block = getASTObject().getBody(); AST ast = astObject.getAST(); ASTRewrite rewrite = ((ASTType) getParent()).getParent().getASTObject().getRewrite(); ListRewrite lrw = rewrite.getListRewrite(block, Block.STATEMENTS_PROPERTY); int originalListSize = lrw.getOriginalList().size(); for (int i=0; i<codeStatements.size(); i++) { ASTAbstractStatement<ASTNode> astStatement = (ASTAbstractStatement<ASTNode>) codeStatements.get(i); ASTNode astNode = astStatement.getASTObject(); ASTNode copyOfAstNode = ASTNode.copySubtree(ast, astNode); // block.statements().add(copyOfAstNode); if (index == -1) { lrw.insertAt(copyOfAstNode, originalListSize, null); } else { lrw.insertAt(copyOfAstNode, index+i, null); } } }
diff --git a/plugins/src/test/java/com/redshape/plugins/WorkflowTest.java b/plugins/src/test/java/com/redshape/plugins/WorkflowTest.java index 8c1080bf..7e331355 100644 --- a/plugins/src/test/java/com/redshape/plugins/WorkflowTest.java +++ b/plugins/src/test/java/com/redshape/plugins/WorkflowTest.java @@ -1,100 +1,100 @@ package com.redshape.plugins; import com.redshape.plugins.loaders.IPluginLoadersRegistry; import com.redshape.plugins.loaders.IPluginsLoader; import com.redshape.plugins.loaders.resources.IPluginResource; import com.redshape.plugins.meta.IMetaLoader; import com.redshape.plugins.meta.IMetaLoadersRegistry; import com.redshape.plugins.meta.IPluginInfo; import com.redshape.plugins.packagers.*; import com.redshape.plugins.registry.IPluginsRegistry; import com.redshape.plugins.starters.EngineType; import com.redshape.plugins.starters.IStarterEngine; import com.redshape.plugins.starters.IStartersRegistry; import com.redshape.utils.tests.AbstractContextAwareTest; import org.junit.Test; import java.net.URI; import java.net.URISyntaxException; import static org.junit.Assert.*; /** * Created by IntelliJ IDEA. * User: Nikelin * Date: 09.01.12 * Time: 17:48 * To change this template use File | Settings | File Templates. */ public class WorkflowTest extends AbstractContextAwareTest<String> { public WorkflowTest() { super("src/test/resources/context.xml"); } protected IPluginsRegistry getPluginsRegistry() { return this.getContext().getBean( IPluginsRegistry.class ); } protected IPluginLoadersRegistry getLoadersRegistry() { return this.getContext().getBean(IPluginLoadersRegistry.class); } protected IPackagesRegistry getPackagesRegistry() { return this.getContext().getBean(IPackagesRegistry.class); } protected IMetaLoadersRegistry getMetaLoadersRegistry() { return this.getContext().getBean(IMetaLoadersRegistry.class); } protected IStartersRegistry getStartersRegistry() { return this.getContext().getBean(IStartersRegistry.class); } protected URI getTestPluginURI() throws URISyntaxException { return new URI( this.getContext().getBean("pluginPath", String.class) ); } @Test public void testMain() throws URISyntaxException, LoaderException, PackagerException { URI testPluginURI = this.getTestPluginURI(); IPluginLoadersRegistry loadersRegistry = this.getLoadersRegistry(); IPluginsLoader loader = loadersRegistry.selectLoader( testPluginURI ); assertNotNull(loader); IPluginResource resource = loader.load(testPluginURI); assertNotNull(resource); assertTrue( resource.canRead() ); IPackagesRegistry packagesRegistry = this.getPackagesRegistry(); PackagingType packageType = this.getPackagesRegistry().detectType(resource); assertNotSame( PackagingType.UNKNOWN, packageType ); assertEquals( PackagingType.INLINE, packageType ); IPackageSupport packager = packagesRegistry.getSupport(packageType); assertNotNull(packager); IPackageDescriptor descriptor = packager.processResource(packageType, resource); assertNotNull(descriptor); IMetaLoadersRegistry metaLoadersRegistry = this.getMetaLoadersRegistry(); assertTrue( metaLoadersRegistry.isSupported(descriptor) ); IMetaLoader metaLoader = metaLoadersRegistry.selectLoader(descriptor); assertNotNull(metaLoader); IPluginInfo info = metaLoader.load(descriptor); assertEquals("3.0.0", info.getArchVersion() ); assertEquals("Test Plugin", info.getName() ); assertEquals("Redshape Ltd.", info.getPublisher().getCompany() ); assertEquals("http://redshape.ru", info.getPublisher().getURI().toString() ); assertNotNull(info.getStarterInfo()); assertEquals(EngineType.Java, info.getStarterInfo().getEngineType()); assertEquals("1.6", info.getStarterInfo().getVersion()); IStarterEngine engine = this.getStartersRegistry().selectEngine( info.getStarterInfo().getEngineType() ); assertNotNull(engine); - IPlugin plugin = engine.resolve(info); - IPluginsRegistry registry = this.getPluginsRegistry(); - registry.registerPlugin( info, plugin ); - engine.start(plugin); - engine.stop(plugin); +// IPlugin plugin = engine.resolve(info); +// IPluginsRegistry registry = this.getPluginsRegistry(); +// registry.registerPlugin( info, plugin ); +// engine.start(plugin); +// engine.stop(plugin); } }
true
true
public void testMain() throws URISyntaxException, LoaderException, PackagerException { URI testPluginURI = this.getTestPluginURI(); IPluginLoadersRegistry loadersRegistry = this.getLoadersRegistry(); IPluginsLoader loader = loadersRegistry.selectLoader( testPluginURI ); assertNotNull(loader); IPluginResource resource = loader.load(testPluginURI); assertNotNull(resource); assertTrue( resource.canRead() ); IPackagesRegistry packagesRegistry = this.getPackagesRegistry(); PackagingType packageType = this.getPackagesRegistry().detectType(resource); assertNotSame( PackagingType.UNKNOWN, packageType ); assertEquals( PackagingType.INLINE, packageType ); IPackageSupport packager = packagesRegistry.getSupport(packageType); assertNotNull(packager); IPackageDescriptor descriptor = packager.processResource(packageType, resource); assertNotNull(descriptor); IMetaLoadersRegistry metaLoadersRegistry = this.getMetaLoadersRegistry(); assertTrue( metaLoadersRegistry.isSupported(descriptor) ); IMetaLoader metaLoader = metaLoadersRegistry.selectLoader(descriptor); assertNotNull(metaLoader); IPluginInfo info = metaLoader.load(descriptor); assertEquals("3.0.0", info.getArchVersion() ); assertEquals("Test Plugin", info.getName() ); assertEquals("Redshape Ltd.", info.getPublisher().getCompany() ); assertEquals("http://redshape.ru", info.getPublisher().getURI().toString() ); assertNotNull(info.getStarterInfo()); assertEquals(EngineType.Java, info.getStarterInfo().getEngineType()); assertEquals("1.6", info.getStarterInfo().getVersion()); IStarterEngine engine = this.getStartersRegistry().selectEngine( info.getStarterInfo().getEngineType() ); assertNotNull(engine); IPlugin plugin = engine.resolve(info); IPluginsRegistry registry = this.getPluginsRegistry(); registry.registerPlugin( info, plugin ); engine.start(plugin); engine.stop(plugin); }
public void testMain() throws URISyntaxException, LoaderException, PackagerException { URI testPluginURI = this.getTestPluginURI(); IPluginLoadersRegistry loadersRegistry = this.getLoadersRegistry(); IPluginsLoader loader = loadersRegistry.selectLoader( testPluginURI ); assertNotNull(loader); IPluginResource resource = loader.load(testPluginURI); assertNotNull(resource); assertTrue( resource.canRead() ); IPackagesRegistry packagesRegistry = this.getPackagesRegistry(); PackagingType packageType = this.getPackagesRegistry().detectType(resource); assertNotSame( PackagingType.UNKNOWN, packageType ); assertEquals( PackagingType.INLINE, packageType ); IPackageSupport packager = packagesRegistry.getSupport(packageType); assertNotNull(packager); IPackageDescriptor descriptor = packager.processResource(packageType, resource); assertNotNull(descriptor); IMetaLoadersRegistry metaLoadersRegistry = this.getMetaLoadersRegistry(); assertTrue( metaLoadersRegistry.isSupported(descriptor) ); IMetaLoader metaLoader = metaLoadersRegistry.selectLoader(descriptor); assertNotNull(metaLoader); IPluginInfo info = metaLoader.load(descriptor); assertEquals("3.0.0", info.getArchVersion() ); assertEquals("Test Plugin", info.getName() ); assertEquals("Redshape Ltd.", info.getPublisher().getCompany() ); assertEquals("http://redshape.ru", info.getPublisher().getURI().toString() ); assertNotNull(info.getStarterInfo()); assertEquals(EngineType.Java, info.getStarterInfo().getEngineType()); assertEquals("1.6", info.getStarterInfo().getVersion()); IStarterEngine engine = this.getStartersRegistry().selectEngine( info.getStarterInfo().getEngineType() ); assertNotNull(engine); // IPlugin plugin = engine.resolve(info); // IPluginsRegistry registry = this.getPluginsRegistry(); // registry.registerPlugin( info, plugin ); // engine.start(plugin); // engine.stop(plugin); }
diff --git a/modules/compute4/org/molgenis/compute/test/reader/WorkflowReaderDBJDBC.java b/modules/compute4/org/molgenis/compute/test/reader/WorkflowReaderDBJDBC.java index 0919a84e1..7f8df5d56 100644 --- a/modules/compute4/org/molgenis/compute/test/reader/WorkflowReaderDBJDBC.java +++ b/modules/compute4/org/molgenis/compute/test/reader/WorkflowReaderDBJDBC.java @@ -1,62 +1,62 @@ package org.molgenis.compute.test.reader; import app.DatabaseFactory; import org.molgenis.compute.design.ComputeParameter; import org.molgenis.compute.design.ComputeProtocol; import org.molgenis.compute.design.Workflow; import org.molgenis.compute.design.WorkflowElement; import org.molgenis.framework.db.Database; import org.molgenis.framework.db.DatabaseException; import org.molgenis.framework.db.QueryRule; import java.util.List; /** * Created with IntelliJ IDEA. User: georgebyelas Date: 24/08/2012 Time: 11:17 * To change this template use File | Settings | File Templates. */ public class WorkflowReaderDBJDBC implements WorkflowReader { - public Workflow getWorkflow(String name) + public Workflow getWorkflow(String name) throws IOException { Database db = null; try { db = DatabaseFactory.create(); db.beginTx(); Workflow w = db.find(Workflow.class, new QueryRule(Workflow.NAME, QueryRule.Operator.EQUALS, name)).get(0); List<WorkflowElement> workflowElements = db.find(WorkflowElement.class, new QueryRule(WorkflowElement.WORKFLOW_NAME, QueryRule.Operator.EQUALS, w.getName())); for(WorkflowElement we : workflowElements) { String protocol_name = we.getProtocol_Name(); ComputeProtocol protocol = db.find(ComputeProtocol.class, new QueryRule(ComputeProtocol.NAME, QueryRule.Operator.EQUALS, protocol_name)).get(0); we.setProtocol(protocol); // we.getPreviousSteps_Id(); // List<WorkflowElement> prev = db.find(WorkflowElement.class, // new QueryRule(WorkflowElement_PreviousSteps., QueryRule.Operator.EQUALS, we.getName())); int i = 0; } db.close(); return w; } catch (DatabaseException e) { e.printStackTrace(); } return null; } public List<ComputeParameter> getParameters() { //TODO: we do not use JDBC workflow reader - otherwise it should be implemented return null; } }
true
true
public Workflow getWorkflow(String name) { Database db = null; try { db = DatabaseFactory.create(); db.beginTx(); Workflow w = db.find(Workflow.class, new QueryRule(Workflow.NAME, QueryRule.Operator.EQUALS, name)).get(0); List<WorkflowElement> workflowElements = db.find(WorkflowElement.class, new QueryRule(WorkflowElement.WORKFLOW_NAME, QueryRule.Operator.EQUALS, w.getName())); for(WorkflowElement we : workflowElements) { String protocol_name = we.getProtocol_Name(); ComputeProtocol protocol = db.find(ComputeProtocol.class, new QueryRule(ComputeProtocol.NAME, QueryRule.Operator.EQUALS, protocol_name)).get(0); we.setProtocol(protocol); // we.getPreviousSteps_Id(); // List<WorkflowElement> prev = db.find(WorkflowElement.class, // new QueryRule(WorkflowElement_PreviousSteps., QueryRule.Operator.EQUALS, we.getName())); int i = 0; } db.close(); return w; } catch (DatabaseException e) { e.printStackTrace(); } return null; }
public Workflow getWorkflow(String name) throws IOException { Database db = null; try { db = DatabaseFactory.create(); db.beginTx(); Workflow w = db.find(Workflow.class, new QueryRule(Workflow.NAME, QueryRule.Operator.EQUALS, name)).get(0); List<WorkflowElement> workflowElements = db.find(WorkflowElement.class, new QueryRule(WorkflowElement.WORKFLOW_NAME, QueryRule.Operator.EQUALS, w.getName())); for(WorkflowElement we : workflowElements) { String protocol_name = we.getProtocol_Name(); ComputeProtocol protocol = db.find(ComputeProtocol.class, new QueryRule(ComputeProtocol.NAME, QueryRule.Operator.EQUALS, protocol_name)).get(0); we.setProtocol(protocol); // we.getPreviousSteps_Id(); // List<WorkflowElement> prev = db.find(WorkflowElement.class, // new QueryRule(WorkflowElement_PreviousSteps., QueryRule.Operator.EQUALS, we.getName())); int i = 0; } db.close(); return w; } catch (DatabaseException e) { e.printStackTrace(); } return null; }
diff --git a/src/mula/console/TestConsole.java b/src/mula/console/TestConsole.java index 68c03df..ca3c649 100644 --- a/src/mula/console/TestConsole.java +++ b/src/mula/console/TestConsole.java @@ -1,56 +1,59 @@ package mula.console; import java.io.Console; import java.io.StringReader; import java.util.List; import java.util.Map; import mula.parser.MulaParser; import mula.parser.ParseException; import mula.parser.TokenMgrError; import mula.structure.*; public class TestConsole { /** * @param args * @throws ParseException */ public static void main(String[] args) throws ParseException { Console console = System.console(); console.printf("Mula Preview on Java, (version 0.1)\n\n"); while(true) { try { console.printf("mula-preview >>> "); String text = System.console().readLine(); MulaParser parser = new MulaParser(new StringReader(text)); MulaSubstance[] substances = parser.article(); if(!(substances.length == 1 && substances[0] instanceof MulaList && ((MulaList)substances[0]).get(0).equals(MulaAtom.get("match")) && ((MulaList)substances[0]).get(1) instanceof MulaList && ((MulaList)substances[0]).get(2) instanceof MulaList)) { throw new Exception("Unexpected list, using \"(match [scheme] [source])\" to test MulaScheme."); } - MulaList scheme = (MulaList)substances[1]; - MulaList source = (MulaList)substances[2]; + MulaList scheme = (MulaList)((MulaList)substances[0]).get(1); + MulaList source = (MulaList)((MulaList)substances[0]).get(2); MulaScheme mulaScheme = new MulaScheme(scheme); Map<MulaAtom, List<MulaSubstance>> variables = mulaScheme.match(source); if(variables == null) { throw new Exception("Source doesn't match scheme."); } console.printf("Variables: \n"); for(MulaAtom name: variables.keySet()) { for(MulaSubstance substance: variables.get(name)) { console.printf(name.toString() + " -> " + substance.toString()); } } + console.printf("\n"); } catch(Exception e) { - console.printf(e.toString()); + console.printf(e.getMessage()); + e.printStackTrace(); + console.printf("\n"); } } } }
false
true
public static void main(String[] args) throws ParseException { Console console = System.console(); console.printf("Mula Preview on Java, (version 0.1)\n\n"); while(true) { try { console.printf("mula-preview >>> "); String text = System.console().readLine(); MulaParser parser = new MulaParser(new StringReader(text)); MulaSubstance[] substances = parser.article(); if(!(substances.length == 1 && substances[0] instanceof MulaList && ((MulaList)substances[0]).get(0).equals(MulaAtom.get("match")) && ((MulaList)substances[0]).get(1) instanceof MulaList && ((MulaList)substances[0]).get(2) instanceof MulaList)) { throw new Exception("Unexpected list, using \"(match [scheme] [source])\" to test MulaScheme."); } MulaList scheme = (MulaList)substances[1]; MulaList source = (MulaList)substances[2]; MulaScheme mulaScheme = new MulaScheme(scheme); Map<MulaAtom, List<MulaSubstance>> variables = mulaScheme.match(source); if(variables == null) { throw new Exception("Source doesn't match scheme."); } console.printf("Variables: \n"); for(MulaAtom name: variables.keySet()) { for(MulaSubstance substance: variables.get(name)) { console.printf(name.toString() + " -> " + substance.toString()); } } } catch(Exception e) { console.printf(e.toString()); } } }
public static void main(String[] args) throws ParseException { Console console = System.console(); console.printf("Mula Preview on Java, (version 0.1)\n\n"); while(true) { try { console.printf("mula-preview >>> "); String text = System.console().readLine(); MulaParser parser = new MulaParser(new StringReader(text)); MulaSubstance[] substances = parser.article(); if(!(substances.length == 1 && substances[0] instanceof MulaList && ((MulaList)substances[0]).get(0).equals(MulaAtom.get("match")) && ((MulaList)substances[0]).get(1) instanceof MulaList && ((MulaList)substances[0]).get(2) instanceof MulaList)) { throw new Exception("Unexpected list, using \"(match [scheme] [source])\" to test MulaScheme."); } MulaList scheme = (MulaList)((MulaList)substances[0]).get(1); MulaList source = (MulaList)((MulaList)substances[0]).get(2); MulaScheme mulaScheme = new MulaScheme(scheme); Map<MulaAtom, List<MulaSubstance>> variables = mulaScheme.match(source); if(variables == null) { throw new Exception("Source doesn't match scheme."); } console.printf("Variables: \n"); for(MulaAtom name: variables.keySet()) { for(MulaSubstance substance: variables.get(name)) { console.printf(name.toString() + " -> " + substance.toString()); } } console.printf("\n"); } catch(Exception e) { console.printf(e.getMessage()); e.printStackTrace(); console.printf("\n"); } } }
diff --git a/src/main/java/com/socrata/datasync/job/IntegrationJob.java b/src/main/java/com/socrata/datasync/job/IntegrationJob.java index b2242e0..9b0864a 100644 --- a/src/main/java/com/socrata/datasync/job/IntegrationJob.java +++ b/src/main/java/com/socrata/datasync/job/IntegrationJob.java @@ -1,325 +1,329 @@ package com.socrata.datasync.job; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.Serializable; import com.socrata.api.Soda2Producer; import com.socrata.api.SodaImporter; import com.socrata.datasync.*; import com.socrata.exceptions.SodaError; import com.socrata.model.UpsertError; import com.socrata.model.UpsertResult; import org.codehaus.jackson.annotate.JsonIgnoreProperties; import org.codehaus.jackson.annotate.JsonProperty; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.annotate.JsonSerialize; @JsonIgnoreProperties(ignoreUnknown=true) @JsonSerialize(include= JsonSerialize.Inclusion.NON_NULL) public class IntegrationJob implements Job { //, Serializable { /** * @author Adrian Laurenzi * * Stores a single integration job that can be opened/run in the GUI * or in command-line mode. */ private static final String DELETE_ZERO_ROWS = ""; // When a file to be published is larger than this value (in bytes), file is chunked private static final int FILESIZE_CHUNK_CUTOFF_BYTES = 78643200; // = 75 MB // During chunking files are uploaded NUM_ROWS_PER_CHUNK rows per chunk private static final int NUM_ROWS_PER_CHUNK = 10000; // TODO move this somewhere else (or remove it) private static final int DATASET_ID_LENGTH = 9; // Anytime a @JsonProperty is added/removed/updated in this class add 1 to this value private static final long fileVersionUID = 1L; private String datasetID; private String fileToPublish; private PublishMethod publishMethod; private String fileRowsToDelete; private String pathToSavedJobFile; private static final String DEFAULT_JOB_NAME = "Untitled Standard Job"; public IntegrationJob() { pathToSavedJobFile = ""; datasetID = ""; fileToPublish = ""; publishMethod = PublishMethod.upsert; fileRowsToDelete = DELETE_ZERO_ROWS; } /** * Loads integration job data from a file and * uses the saved data to populate the fields * of this object */ public IntegrationJob(String pathToFile) throws IOException { // first try reading the 'current' format ObjectMapper mapper = new ObjectMapper(); try { IntegrationJob loadedJob = mapper.readValue(new File(pathToFile), IntegrationJob.class); setPathToSavedFile(loadedJob.getPathToSavedFile()); setDatasetID(loadedJob.getDatasetID()); setFileToPublish(loadedJob.getFileToPublish()); setPublishMethod(loadedJob.getPublishMethod()); setFileRowsToDelete(loadedJob.getFileRowsToDelete()); } catch (IOException e) { // if reading new format fails...try reading old format into this object try { InputStream file = new FileInputStream(pathToFile); InputStream buffer = new BufferedInputStream(file); ObjectInput input = new ObjectInputStream (buffer); try{ com.socrata.datasync.IntegrationJob loadedJobOld = (com.socrata.datasync.IntegrationJob) input.readObject(); // Load data into this object setPathToSavedFile(loadedJobOld.getPathToSavedFile()); setDatasetID(loadedJobOld.getDatasetID()); setFileToPublish(loadedJobOld.getFileToPublish()); setPublishMethod(loadedJobOld.getPublishMethod()); setFileRowsToDelete(loadedJobOld.getFileRowsToDelete()); } finally{ input.close(); } } catch(Exception e2){ throw new IOException(e.toString()); } } } /** * * @return an error JobStatus if any input is invalid, otherwise JobStatus.VALID */ public JobStatus validate(SocrataConnectionInfo connectionInfo) { if(connectionInfo.getUrl().equals("") || connectionInfo.getUrl().equals("https://")) { return JobStatus.INVALID_DOMAIN; } if(datasetID.length() != DATASET_ID_LENGTH) { return JobStatus.INVALID_DATASET_ID; } if(fileToPublish.equals("")) { return JobStatus.MISSING_FILE_TO_PUBLISH; } else { File checkFileToPublish = new File(fileToPublish); if(!checkFileToPublish.exists()) { JobStatus errorStatus = JobStatus.FILE_TO_PUBLISH_DOESNT_EXIST; errorStatus.setMessage(fileToPublish + ": File to publish does not exist"); return errorStatus; } } if(!publishMethod.equals(PublishMethod.upsert) && !publishMethod.equals(PublishMethod.replace) && !publishMethod.equals(PublishMethod.append)) { return JobStatus.INVALID_PUBLISH_METHOD; } // TODO add more validation return JobStatus.VALID; } public JobStatus run() { UserPreferences userPrefs = new UserPreferences(); SocrataConnectionInfo connectionInfo = userPrefs.getConnectionInfo(); UpsertResult result = null; JobStatus runStatus = JobStatus.SUCCESS; JobStatus validationStatus = validate(connectionInfo); if(validationStatus.isError()) { runStatus = validationStatus; } else { final Soda2Producer producer = Soda2Producer.newProducer(connectionInfo.getUrl(), connectionInfo.getUser(), connectionInfo.getPassword(), connectionInfo.getToken()); final SodaImporter importer = SodaImporter.newImporter(connectionInfo.getUrl(), connectionInfo.getUser(), connectionInfo.getPassword(), connectionInfo.getToken()); File fileToPublishFile = new File(fileToPublish); File deleteRowsFile = null; if(!fileRowsToDelete.equals(DELETE_ZERO_ROWS)) { deleteRowsFile = new File(fileRowsToDelete); } String errorMessage = ""; boolean noPublishExceptions = false; try { if(publishMethod.equals(PublishMethod.upsert)) { if(fileToPublishFile.length() > FILESIZE_CHUNK_CUTOFF_BYTES) { result = IntegrationUtility.upsertInChunks( NUM_ROWS_PER_CHUNK, producer, importer, datasetID, deleteRowsFile, fileToPublishFile); } else { result = IntegrationUtility.upsert(producer, importer, datasetID, deleteRowsFile, fileToPublishFile); } noPublishExceptions = true; } else if(publishMethod.equals(PublishMethod.append)) { if(fileToPublishFile.length() > FILESIZE_CHUNK_CUTOFF_BYTES) { result = IntegrationUtility.appendInChunks( NUM_ROWS_PER_CHUNK, producer, datasetID, fileToPublishFile); } else { result = IntegrationUtility.append(producer, datasetID, fileToPublishFile); } noPublishExceptions = true; } else if(publishMethod.equals(PublishMethod.replace)) { result = IntegrationUtility.replaceNew(producer, datasetID, fileToPublishFile); noPublishExceptions = true; } else { errorMessage = JobStatus.INVALID_PUBLISH_METHOD.toString(); } } catch (IOException ioException) { errorMessage = ioException.getMessage(); } catch (SodaError sodaError) { - errorMessage = sodaError.getMessage(); + errorMessage = sodaError.getMessage(); } catch (InterruptedException intrruptException) { errorMessage = intrruptException.getMessage(); } catch (Exception other) { errorMessage = other.toString() + ": " + other.getMessage(); } finally { if(noPublishExceptions) { - // Check for upsert errors (only for upsert and append publish methods) + // Check for upsert errors (only for upsert and append publish methods) if(result != null) { - if(result.errorCount() > 0) { + if(result.errorCount() > 0) { for (UpsertError upsertErr : result.getErrors()) { errorMessage += upsertErr.getError() + " (line " + (upsertErr.getIndex() + 1) + " of file) \n"; } runStatus = JobStatus.PUBLISH_ERROR; runStatus.setMessage(errorMessage); - } + } else { + //if(sodaError.getMessage().equals("Not found")) + //runStatus = JobStatus.PUBLISH_ERROR; + //runStatus.setMessage("Dataset with that ID does not exist or you do not have permission to publish to it"); + } } else { runStatus = JobStatus.SUCCESS; } } else { runStatus = JobStatus.PUBLISH_ERROR; runStatus.setMessage(errorMessage); } } } String adminEmail = userPrefs.getAdminEmail(); String logDatasetID = userPrefs.getLogDatasetID(); JobStatus logStatus = JobStatus.SUCCESS; if(!logDatasetID.equals("")) { logStatus = IntegrationUtility.addLogEntry(logDatasetID, connectionInfo, this, runStatus, result); } // Send email if there was an error updating log or target dataset if(userPrefs.emailUponError() && !adminEmail.equals("")) { String errorEmailMessage = ""; String urlToLogDataset = connectionInfo.getUrl() + "/d/" + logDatasetID; if(runStatus.isError()) { errorEmailMessage += "There was an error updating a dataset.\n" + "\nDataset: " + connectionInfo.getUrl() + "/d/" + getDatasetID() + "\nFile to be published: " + fileToPublish + "\nPublish method: " + publishMethod // TODO + "\nFile with rows to delete: " + fileRowsToDelete + "\nJob File: " + pathToSavedJobFile + "\nError message: " + runStatus.getMessage() + "\nLog dataset: " + urlToLogDataset + "\n\n"; } if(logStatus.isError()) { errorEmailMessage += "There was an error updating the log dataset: " + urlToLogDataset + "\n" + "Error message: " + logStatus.getMessage() + "\n\n"; } if(runStatus.isError() || logStatus.isError()) { try { SMTPMailer.send(adminEmail, "Socrata DataSync Error", errorEmailMessage); } catch (Exception e) { System.out.println("Error sending email to: " + adminEmail + "\n" + e.getMessage()); } } } return runStatus; } /** * Saves this object as a file at given filepath */ public void writeToFile(String filepath) throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.writeValue(new File(filepath), this); } @JsonProperty("fileVersionUID") public long getFileVersionUID() { return fileVersionUID; } @JsonProperty("pathToSavedJobFile") public void setPathToSavedFile(String newPath) { pathToSavedJobFile = newPath; } @JsonProperty("pathToSavedJobFile") public String getPathToSavedFile() { return pathToSavedJobFile; } @JsonProperty("datasetID") public void setDatasetID(String newDatasetID) { datasetID = newDatasetID; } @JsonProperty("datasetID") public String getDatasetID() { return datasetID; } @JsonProperty("fileToPublish") public void setFileToPublish(String newFileToPublish) { fileToPublish = newFileToPublish; } @JsonProperty("fileToPublish") public String getFileToPublish() { return fileToPublish; } @JsonProperty("publishMethod") public void setPublishMethod(PublishMethod newPublishMethod) { publishMethod = newPublishMethod; } @JsonProperty("publishMethod") public PublishMethod getPublishMethod() { return publishMethod; } @JsonProperty("fileRowsToDelete") public void setFileRowsToDelete(String newFileRowsToDelete) { fileRowsToDelete = newFileRowsToDelete; } @JsonProperty("fileRowsToDelete") public String getFileRowsToDelete() { return fileRowsToDelete; } public String getJobFilename() { if(pathToSavedJobFile.equals("")) { return DEFAULT_JOB_NAME; } return new File(pathToSavedJobFile).getName(); } }
false
true
public JobStatus run() { UserPreferences userPrefs = new UserPreferences(); SocrataConnectionInfo connectionInfo = userPrefs.getConnectionInfo(); UpsertResult result = null; JobStatus runStatus = JobStatus.SUCCESS; JobStatus validationStatus = validate(connectionInfo); if(validationStatus.isError()) { runStatus = validationStatus; } else { final Soda2Producer producer = Soda2Producer.newProducer(connectionInfo.getUrl(), connectionInfo.getUser(), connectionInfo.getPassword(), connectionInfo.getToken()); final SodaImporter importer = SodaImporter.newImporter(connectionInfo.getUrl(), connectionInfo.getUser(), connectionInfo.getPassword(), connectionInfo.getToken()); File fileToPublishFile = new File(fileToPublish); File deleteRowsFile = null; if(!fileRowsToDelete.equals(DELETE_ZERO_ROWS)) { deleteRowsFile = new File(fileRowsToDelete); } String errorMessage = ""; boolean noPublishExceptions = false; try { if(publishMethod.equals(PublishMethod.upsert)) { if(fileToPublishFile.length() > FILESIZE_CHUNK_CUTOFF_BYTES) { result = IntegrationUtility.upsertInChunks( NUM_ROWS_PER_CHUNK, producer, importer, datasetID, deleteRowsFile, fileToPublishFile); } else { result = IntegrationUtility.upsert(producer, importer, datasetID, deleteRowsFile, fileToPublishFile); } noPublishExceptions = true; } else if(publishMethod.equals(PublishMethod.append)) { if(fileToPublishFile.length() > FILESIZE_CHUNK_CUTOFF_BYTES) { result = IntegrationUtility.appendInChunks( NUM_ROWS_PER_CHUNK, producer, datasetID, fileToPublishFile); } else { result = IntegrationUtility.append(producer, datasetID, fileToPublishFile); } noPublishExceptions = true; } else if(publishMethod.equals(PublishMethod.replace)) { result = IntegrationUtility.replaceNew(producer, datasetID, fileToPublishFile); noPublishExceptions = true; } else { errorMessage = JobStatus.INVALID_PUBLISH_METHOD.toString(); } } catch (IOException ioException) { errorMessage = ioException.getMessage(); } catch (SodaError sodaError) { errorMessage = sodaError.getMessage(); } catch (InterruptedException intrruptException) { errorMessage = intrruptException.getMessage(); } catch (Exception other) { errorMessage = other.toString() + ": " + other.getMessage(); } finally { if(noPublishExceptions) { // Check for upsert errors (only for upsert and append publish methods) if(result != null) { if(result.errorCount() > 0) { for (UpsertError upsertErr : result.getErrors()) { errorMessage += upsertErr.getError() + " (line " + (upsertErr.getIndex() + 1) + " of file) \n"; } runStatus = JobStatus.PUBLISH_ERROR; runStatus.setMessage(errorMessage); } } else { runStatus = JobStatus.SUCCESS; } } else { runStatus = JobStatus.PUBLISH_ERROR; runStatus.setMessage(errorMessage); } } } String adminEmail = userPrefs.getAdminEmail(); String logDatasetID = userPrefs.getLogDatasetID(); JobStatus logStatus = JobStatus.SUCCESS; if(!logDatasetID.equals("")) { logStatus = IntegrationUtility.addLogEntry(logDatasetID, connectionInfo, this, runStatus, result); } // Send email if there was an error updating log or target dataset if(userPrefs.emailUponError() && !adminEmail.equals("")) { String errorEmailMessage = ""; String urlToLogDataset = connectionInfo.getUrl() + "/d/" + logDatasetID; if(runStatus.isError()) { errorEmailMessage += "There was an error updating a dataset.\n" + "\nDataset: " + connectionInfo.getUrl() + "/d/" + getDatasetID() + "\nFile to be published: " + fileToPublish + "\nPublish method: " + publishMethod // TODO + "\nFile with rows to delete: " + fileRowsToDelete + "\nJob File: " + pathToSavedJobFile + "\nError message: " + runStatus.getMessage() + "\nLog dataset: " + urlToLogDataset + "\n\n"; } if(logStatus.isError()) { errorEmailMessage += "There was an error updating the log dataset: " + urlToLogDataset + "\n" + "Error message: " + logStatus.getMessage() + "\n\n"; } if(runStatus.isError() || logStatus.isError()) { try { SMTPMailer.send(adminEmail, "Socrata DataSync Error", errorEmailMessage); } catch (Exception e) { System.out.println("Error sending email to: " + adminEmail + "\n" + e.getMessage()); } } } return runStatus; }
public JobStatus run() { UserPreferences userPrefs = new UserPreferences(); SocrataConnectionInfo connectionInfo = userPrefs.getConnectionInfo(); UpsertResult result = null; JobStatus runStatus = JobStatus.SUCCESS; JobStatus validationStatus = validate(connectionInfo); if(validationStatus.isError()) { runStatus = validationStatus; } else { final Soda2Producer producer = Soda2Producer.newProducer(connectionInfo.getUrl(), connectionInfo.getUser(), connectionInfo.getPassword(), connectionInfo.getToken()); final SodaImporter importer = SodaImporter.newImporter(connectionInfo.getUrl(), connectionInfo.getUser(), connectionInfo.getPassword(), connectionInfo.getToken()); File fileToPublishFile = new File(fileToPublish); File deleteRowsFile = null; if(!fileRowsToDelete.equals(DELETE_ZERO_ROWS)) { deleteRowsFile = new File(fileRowsToDelete); } String errorMessage = ""; boolean noPublishExceptions = false; try { if(publishMethod.equals(PublishMethod.upsert)) { if(fileToPublishFile.length() > FILESIZE_CHUNK_CUTOFF_BYTES) { result = IntegrationUtility.upsertInChunks( NUM_ROWS_PER_CHUNK, producer, importer, datasetID, deleteRowsFile, fileToPublishFile); } else { result = IntegrationUtility.upsert(producer, importer, datasetID, deleteRowsFile, fileToPublishFile); } noPublishExceptions = true; } else if(publishMethod.equals(PublishMethod.append)) { if(fileToPublishFile.length() > FILESIZE_CHUNK_CUTOFF_BYTES) { result = IntegrationUtility.appendInChunks( NUM_ROWS_PER_CHUNK, producer, datasetID, fileToPublishFile); } else { result = IntegrationUtility.append(producer, datasetID, fileToPublishFile); } noPublishExceptions = true; } else if(publishMethod.equals(PublishMethod.replace)) { result = IntegrationUtility.replaceNew(producer, datasetID, fileToPublishFile); noPublishExceptions = true; } else { errorMessage = JobStatus.INVALID_PUBLISH_METHOD.toString(); } } catch (IOException ioException) { errorMessage = ioException.getMessage(); } catch (SodaError sodaError) { errorMessage = sodaError.getMessage(); } catch (InterruptedException intrruptException) { errorMessage = intrruptException.getMessage(); } catch (Exception other) { errorMessage = other.toString() + ": " + other.getMessage(); } finally { if(noPublishExceptions) { // Check for upsert errors (only for upsert and append publish methods) if(result != null) { if(result.errorCount() > 0) { for (UpsertError upsertErr : result.getErrors()) { errorMessage += upsertErr.getError() + " (line " + (upsertErr.getIndex() + 1) + " of file) \n"; } runStatus = JobStatus.PUBLISH_ERROR; runStatus.setMessage(errorMessage); } else { //if(sodaError.getMessage().equals("Not found")) //runStatus = JobStatus.PUBLISH_ERROR; //runStatus.setMessage("Dataset with that ID does not exist or you do not have permission to publish to it"); } } else { runStatus = JobStatus.SUCCESS; } } else { runStatus = JobStatus.PUBLISH_ERROR; runStatus.setMessage(errorMessage); } } } String adminEmail = userPrefs.getAdminEmail(); String logDatasetID = userPrefs.getLogDatasetID(); JobStatus logStatus = JobStatus.SUCCESS; if(!logDatasetID.equals("")) { logStatus = IntegrationUtility.addLogEntry(logDatasetID, connectionInfo, this, runStatus, result); } // Send email if there was an error updating log or target dataset if(userPrefs.emailUponError() && !adminEmail.equals("")) { String errorEmailMessage = ""; String urlToLogDataset = connectionInfo.getUrl() + "/d/" + logDatasetID; if(runStatus.isError()) { errorEmailMessage += "There was an error updating a dataset.\n" + "\nDataset: " + connectionInfo.getUrl() + "/d/" + getDatasetID() + "\nFile to be published: " + fileToPublish + "\nPublish method: " + publishMethod // TODO + "\nFile with rows to delete: " + fileRowsToDelete + "\nJob File: " + pathToSavedJobFile + "\nError message: " + runStatus.getMessage() + "\nLog dataset: " + urlToLogDataset + "\n\n"; } if(logStatus.isError()) { errorEmailMessage += "There was an error updating the log dataset: " + urlToLogDataset + "\n" + "Error message: " + logStatus.getMessage() + "\n\n"; } if(runStatus.isError() || logStatus.isError()) { try { SMTPMailer.send(adminEmail, "Socrata DataSync Error", errorEmailMessage); } catch (Exception e) { System.out.println("Error sending email to: " + adminEmail + "\n" + e.getMessage()); } } } return runStatus; }
diff --git a/src/radlab/rain/workload/olio/AddEventOperation.java b/src/radlab/rain/workload/olio/AddEventOperation.java index 02ef4c2..7b2ea0b 100644 --- a/src/radlab/rain/workload/olio/AddEventOperation.java +++ b/src/radlab/rain/workload/olio/AddEventOperation.java @@ -1,275 +1,286 @@ /* * Copyright (c) 2010, Regents of the University of California * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of California, Berkeley * nor the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * * Author Original authors * Author: Marco Guazzone ([email protected]), 2013 */ package radlab.rain.workload.olio; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Calendar; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.HttpStatus; import radlab.rain.IScoreboard; import radlab.rain.workload.olio.model.OlioPerson; import radlab.rain.workload.olio.model.OlioSocialEvent; import radlab.rain.workload.olio.model.OlioTag; /** * The AddEventOperation is an operation that creates a new event. The user * must be logged on. The creation of the POST involves populating the request * with event details, an image, a document, and address data.<br /> * <br /> * The requests made include loading the event form, loading the static URLs * (CSS/JS), and sending the POST data to the application. * <br/> * NOTE: Code based on {@code org.apache.olio.workload.driver.UIDriver} class * and adapted for RAIN. * * @author Original authors * @author <a href="mailto:[email protected]">Marco Guazzone</a> */ public class AddEventOperation extends OlioOperation { public AddEventOperation(boolean interactive, IScoreboard scoreboard) { super(interactive, scoreboard); this._operationName = OlioGenerator.ADD_EVENT_OP_NAME; this._operationIndex = OlioGenerator.ADD_EVENT_OP; } @Override public void execute() throws Throwable { // Need a logged person OlioPerson loggedPerson = this.getUtility().getPerson(this.getSessionState().getLoggedPersonId()); if (!this.getUtility().isRegisteredPerson(loggedPerson)) { this.getLogger().severe("Login required for adding an event"); //throw new Exception("Login required for adding an event"); this.setFailed(true); return; } StringBuilder response = null; // Fetch the add event form. response = this.getHttpTransport().fetchUrl(this.getGenerator().getAddEventURL()); this.trace(this.getGenerator().getAddEventURL()); // Verify that the request succeeded. if (!this.getGenerator().checkHttpResponse(response.toString())) { this.getLogger().severe("Problems in performing request to URL: " + this.getGenerator().getAddEventURL() + " (HTTP status code: " + this.getHttpTransport().getStatusCode() + "). Server response: " + response); throw new IOException("Problems in performing request to URL: " + this.getGenerator().getAddEventURL() + " (HTTP status code: " + this.getHttpTransport().getStatusCode() + ")"); } // Load the static files associated with the add event form. this.loadStatics(this.getGenerator().getAddEventStatics()); this.trace(this.getGenerator().getAddEventStatics()); // Get the authentication token needed to create the POST request. String token = null; switch (this.getConfiguration().getIncarnation()) { case OlioConfiguration.JAVA_INCARNATION: // No token to parse break; case OlioConfiguration.PHP_INCARNATION: // No token to parse break; case OlioConfiguration.RAILS_INCARNATION: token = this.parseAuthToken(response.toString()); if ( token == null ) { throw new Exception( "Authentication token could not be parsed" ); } break; } // Generate a new Olio social event OlioSocialEvent event = this.getUtility().newSocialEvent(); event.submitterUserName = loggedPerson.userName; // Submit the add event form to create the event. HttpPost reqPost = new HttpPost(this.getGenerator().getAddEventResultURL()); MultipartEntity entity = new MultipartEntity(); this.populateEntity(entity, event); switch (this.getConfiguration().getIncarnation()) { case OlioConfiguration.JAVA_INCARNATION: // No token to set break; case OlioConfiguration.PHP_INCARNATION: // No token to set break; case OlioConfiguration.RAILS_INCARNATION: entity.addPart("authenticity_token", new StringBody(token)); break; } reqPost.setEntity(entity); response = this.getHttpTransport().fetch(reqPost); this.trace(this.getGenerator().getAddEventResultURL()); //FIXME: In Apache Olio there is also a check for redirection. Do we need it? // Probably no, since HttpTransport#fecth already take care of it //String[] locationHeader = this.getHttpTransport().getHeadersMap().get("location"); //if (redirectionLocation != null) //{ // String redirectUrl = null; // switch (this.getConfiguration().getIncarnation()) // { // case OlioConfiguration.JAVA_INCARNATION: // redirectUrl = this.getGenerator().getBaseURL() + '/' + locationHeader[0]; // break; // case OlioConfiguration.PHP_INCARNATION: // redirectUrl = this.getGenerator().getBaseURL() + '/' + locationHeader[0]; // break; // case OlioConfiguration.RAILS_INCARNATION: // redirectUrl = locationHeader[0]; // break; // } // response = this.getHttpTransport().fetchURL(redirectUrl); //} // Verify that the request succeeded. if (!this.getGenerator().checkHttpResponse(response.toString())) { this.getLogger().severe("Problems in performing request to URL: " + reqPost.getURI() + " (HTTP status code: " + this.getHttpTransport().getStatusCode() + "). Server response: " + response); throw new IOException("Problems in performing request to URL: " + reqPost.getURI() + " (HTTP status code: " + this.getHttpTransport().getStatusCode() + ")"); } // Verify that the operation succeeded. - int index = response.toString().toLowerCase().indexOf("success"); - if (index == -1) + switch (this.getConfiguration().getIncarnation()) { - this.getLogger().severe("Problems in performing request to URL: " + reqPost.getURI() + " (HTTP status code: " + this.getHttpTransport().getStatusCode() + "): Could not find success message in result body. Server response: " + response); - throw new IOException("Problems in performing request to URL: " + reqPost.getURI() + " (HTTP status code: " + this.getHttpTransport().getStatusCode() + "): Could not find success message in result body"); + case OlioConfiguration.JAVA_INCARNATION: + // No check to do + break; + case OlioConfiguration.PHP_INCARNATION: + // No check to do + break; + case OlioConfiguration.RAILS_INCARNATION: + int index = response.toString().toLowerCase().indexOf("event was successfully created."); + if (index == -1) + { + this.getLogger().severe("Problems in performing request to URL: " + reqPost.getURI() + " (HTTP status code: " + this.getHttpTransport().getStatusCode() + "): Could not find success message in result body. Server response: " + response); + throw new IOException("Problems in performing request to URL: " + reqPost.getURI() + " (HTTP status code: " + this.getHttpTransport().getStatusCode() + "): Could not find success message in result body"); + } + break; } // Save session data this.getSessionState().setLastResponse(response.toString()); this.setFailed(false); } /** * Adds the details and files needed to create a new event in Olio. * * @param entity The request entity in which to add event details. */ protected void populateEntity(MultipartEntity entity, OlioSocialEvent evt) throws Throwable { Calendar cal = Calendar.getInstance(); cal.setTime(evt.eventTimestamp); StringBuilder tags = new StringBuilder(); for (OlioTag tag : evt.tags) { tags.append(tag.name).append(' '); } tags.setLength(tags.length()-1); // Trim trailing space switch (this.getConfiguration().getIncarnation()) { case OlioConfiguration.JAVA_INCARNATION: entity.addPart("title", new StringBody(evt.title)); entity.addPart("summary", new StringBody(evt.summary)); entity.addPart("description", new StringBody(evt.description)); entity.addPart("submitter_user_name", new StringBody(evt.submitterUserName)); entity.addPart("telephone", new StringBody(evt.telephone)); entity.addPart("timezone", new StringBody(evt.timezone)); entity.addPart("year", new StringBody(Integer.toString(cal.get(Calendar.YEAR)))); entity.addPart("month", new StringBody(Integer.toString(cal.get(Calendar.MONTH)))); entity.addPart("day", new StringBody(Integer.toString(cal.get(Calendar.DAY_OF_MONTH)))); entity.addPart("hour", new StringBody(Integer.toString(cal.get(Calendar.HOUR_OF_DAY)))); entity.addPart("minute", new StringBody(Integer.toString(cal.get(Calendar.MINUTE)))); entity.addPart("tags", new StringBody(tags.toString())); entity.addPart("street1", new StringBody(evt.address[0])); entity.addPart("street2", new StringBody(evt.address[1])); entity.addPart("city", new StringBody(evt.address[2])); entity.addPart("state", new StringBody(evt.address[3])); entity.addPart("zip", new StringBody(evt.address[4])); entity.addPart("country", new StringBody(evt.address[5])); entity.addPart("upload_event_image", new FileBody(this.getGenerator().getEventImgFile())); entity.addPart("upload_event_literature", new FileBody(this.getGenerator().getEventPdfFile())); entity.addPart("submit", new StringBody("Create")); break; case OlioConfiguration.PHP_INCARNATION: entity.addPart("title", new StringBody(evt.title)); //entity.addPart("summary", new StringBody(evt.summary)); entity.addPart("description", new StringBody(evt.description)); entity.addPart("submitter_user_name", new StringBody(evt.submitterUserName)); entity.addPart("telephone", new StringBody(evt.telephone)); entity.addPart("timezone", new StringBody(evt.timezone)); entity.addPart("year", new StringBody(Integer.toString(cal.get(Calendar.YEAR)))); entity.addPart("month", new StringBody(Integer.toString(cal.get(Calendar.MONTH)))); entity.addPart("day", new StringBody(Integer.toString(cal.get(Calendar.DAY_OF_MONTH)))); entity.addPart("hour", new StringBody(Integer.toString(cal.get(Calendar.HOUR_OF_DAY)))); entity.addPart("minute", new StringBody(Integer.toString(cal.get(Calendar.MINUTE)))); entity.addPart("tags", new StringBody(tags.toString())); entity.addPart("street1", new StringBody(evt.address[0])); entity.addPart("street2", new StringBody(evt.address[1])); entity.addPart("city", new StringBody(evt.address[2])); entity.addPart("state", new StringBody(evt.address[3])); entity.addPart("zip", new StringBody(evt.address[4])); entity.addPart("country", new StringBody(evt.address[5])); entity.addPart("upload_event_image", new FileBody(this.getGenerator().getEventImgFile())); entity.addPart("upload_event_literature", new FileBody(this.getGenerator().getEventPdfFile())); entity.addPart("addeventsubmit", new StringBody("Create")); break; case OlioConfiguration.RAILS_INCARNATION: entity.addPart("event[title]", new StringBody(evt.title)); entity.addPart("event[summary]", new StringBody(evt.summary)); entity.addPart("event[description]", new StringBody(evt.description)); //FIXME: Submitter user name? entity.addPart("event[telephone]", new StringBody(evt.telephone)); //FIXME: Timezone? entity.addPart("event[event_timestamp(1i)]", new StringBody(Integer.toString(cal.get(Calendar.YEAR)))); entity.addPart("event[event_timestamp(2i)]", new StringBody(Integer.toString(cal.get(Calendar.MONTH)))); entity.addPart("event[event_timestamp(3i)]", new StringBody(Integer.toString(cal.get(Calendar.DAY_OF_MONTH)))); entity.addPart("event[event_timestamp(4i)]", new StringBody(Integer.toString(cal.get(Calendar.HOUR_OF_DAY)))); entity.addPart("event[event_timestamp(5i)]", new StringBody(Integer.toString(cal.get(Calendar.MINUTE)))); entity.addPart("tag_list", new StringBody(tags.toString())); entity.addPart("event_image", new FileBody(this.getGenerator().getEventImgFile())); entity.addPart("event_document", new FileBody(this.getGenerator().getEventPdfFile())); entity.addPart("address[street1]", new StringBody(evt.address[0])); entity.addPart("address[street2]", new StringBody(evt.address[1])); entity.addPart("address[city]", new StringBody(evt.address[2])); entity.addPart("address[state]", new StringBody(evt.address[3])); entity.addPart("address[zip]", new StringBody(evt.address[4])); entity.addPart("address[country]", new StringBody(evt.address[5])); entity.addPart("commit", new StringBody("Create")); break; } } }
false
true
public void execute() throws Throwable { // Need a logged person OlioPerson loggedPerson = this.getUtility().getPerson(this.getSessionState().getLoggedPersonId()); if (!this.getUtility().isRegisteredPerson(loggedPerson)) { this.getLogger().severe("Login required for adding an event"); //throw new Exception("Login required for adding an event"); this.setFailed(true); return; } StringBuilder response = null; // Fetch the add event form. response = this.getHttpTransport().fetchUrl(this.getGenerator().getAddEventURL()); this.trace(this.getGenerator().getAddEventURL()); // Verify that the request succeeded. if (!this.getGenerator().checkHttpResponse(response.toString())) { this.getLogger().severe("Problems in performing request to URL: " + this.getGenerator().getAddEventURL() + " (HTTP status code: " + this.getHttpTransport().getStatusCode() + "). Server response: " + response); throw new IOException("Problems in performing request to URL: " + this.getGenerator().getAddEventURL() + " (HTTP status code: " + this.getHttpTransport().getStatusCode() + ")"); } // Load the static files associated with the add event form. this.loadStatics(this.getGenerator().getAddEventStatics()); this.trace(this.getGenerator().getAddEventStatics()); // Get the authentication token needed to create the POST request. String token = null; switch (this.getConfiguration().getIncarnation()) { case OlioConfiguration.JAVA_INCARNATION: // No token to parse break; case OlioConfiguration.PHP_INCARNATION: // No token to parse break; case OlioConfiguration.RAILS_INCARNATION: token = this.parseAuthToken(response.toString()); if ( token == null ) { throw new Exception( "Authentication token could not be parsed" ); } break; } // Generate a new Olio social event OlioSocialEvent event = this.getUtility().newSocialEvent(); event.submitterUserName = loggedPerson.userName; // Submit the add event form to create the event. HttpPost reqPost = new HttpPost(this.getGenerator().getAddEventResultURL()); MultipartEntity entity = new MultipartEntity(); this.populateEntity(entity, event); switch (this.getConfiguration().getIncarnation()) { case OlioConfiguration.JAVA_INCARNATION: // No token to set break; case OlioConfiguration.PHP_INCARNATION: // No token to set break; case OlioConfiguration.RAILS_INCARNATION: entity.addPart("authenticity_token", new StringBody(token)); break; } reqPost.setEntity(entity); response = this.getHttpTransport().fetch(reqPost); this.trace(this.getGenerator().getAddEventResultURL()); //FIXME: In Apache Olio there is also a check for redirection. Do we need it? // Probably no, since HttpTransport#fecth already take care of it //String[] locationHeader = this.getHttpTransport().getHeadersMap().get("location"); //if (redirectionLocation != null) //{ // String redirectUrl = null; // switch (this.getConfiguration().getIncarnation()) // { // case OlioConfiguration.JAVA_INCARNATION: // redirectUrl = this.getGenerator().getBaseURL() + '/' + locationHeader[0]; // break; // case OlioConfiguration.PHP_INCARNATION: // redirectUrl = this.getGenerator().getBaseURL() + '/' + locationHeader[0]; // break; // case OlioConfiguration.RAILS_INCARNATION: // redirectUrl = locationHeader[0]; // break; // } // response = this.getHttpTransport().fetchURL(redirectUrl); //} // Verify that the request succeeded. if (!this.getGenerator().checkHttpResponse(response.toString())) { this.getLogger().severe("Problems in performing request to URL: " + reqPost.getURI() + " (HTTP status code: " + this.getHttpTransport().getStatusCode() + "). Server response: " + response); throw new IOException("Problems in performing request to URL: " + reqPost.getURI() + " (HTTP status code: " + this.getHttpTransport().getStatusCode() + ")"); } // Verify that the operation succeeded. int index = response.toString().toLowerCase().indexOf("success"); if (index == -1) { this.getLogger().severe("Problems in performing request to URL: " + reqPost.getURI() + " (HTTP status code: " + this.getHttpTransport().getStatusCode() + "): Could not find success message in result body. Server response: " + response); throw new IOException("Problems in performing request to URL: " + reqPost.getURI() + " (HTTP status code: " + this.getHttpTransport().getStatusCode() + "): Could not find success message in result body"); } // Save session data this.getSessionState().setLastResponse(response.toString()); this.setFailed(false); }
public void execute() throws Throwable { // Need a logged person OlioPerson loggedPerson = this.getUtility().getPerson(this.getSessionState().getLoggedPersonId()); if (!this.getUtility().isRegisteredPerson(loggedPerson)) { this.getLogger().severe("Login required for adding an event"); //throw new Exception("Login required for adding an event"); this.setFailed(true); return; } StringBuilder response = null; // Fetch the add event form. response = this.getHttpTransport().fetchUrl(this.getGenerator().getAddEventURL()); this.trace(this.getGenerator().getAddEventURL()); // Verify that the request succeeded. if (!this.getGenerator().checkHttpResponse(response.toString())) { this.getLogger().severe("Problems in performing request to URL: " + this.getGenerator().getAddEventURL() + " (HTTP status code: " + this.getHttpTransport().getStatusCode() + "). Server response: " + response); throw new IOException("Problems in performing request to URL: " + this.getGenerator().getAddEventURL() + " (HTTP status code: " + this.getHttpTransport().getStatusCode() + ")"); } // Load the static files associated with the add event form. this.loadStatics(this.getGenerator().getAddEventStatics()); this.trace(this.getGenerator().getAddEventStatics()); // Get the authentication token needed to create the POST request. String token = null; switch (this.getConfiguration().getIncarnation()) { case OlioConfiguration.JAVA_INCARNATION: // No token to parse break; case OlioConfiguration.PHP_INCARNATION: // No token to parse break; case OlioConfiguration.RAILS_INCARNATION: token = this.parseAuthToken(response.toString()); if ( token == null ) { throw new Exception( "Authentication token could not be parsed" ); } break; } // Generate a new Olio social event OlioSocialEvent event = this.getUtility().newSocialEvent(); event.submitterUserName = loggedPerson.userName; // Submit the add event form to create the event. HttpPost reqPost = new HttpPost(this.getGenerator().getAddEventResultURL()); MultipartEntity entity = new MultipartEntity(); this.populateEntity(entity, event); switch (this.getConfiguration().getIncarnation()) { case OlioConfiguration.JAVA_INCARNATION: // No token to set break; case OlioConfiguration.PHP_INCARNATION: // No token to set break; case OlioConfiguration.RAILS_INCARNATION: entity.addPart("authenticity_token", new StringBody(token)); break; } reqPost.setEntity(entity); response = this.getHttpTransport().fetch(reqPost); this.trace(this.getGenerator().getAddEventResultURL()); //FIXME: In Apache Olio there is also a check for redirection. Do we need it? // Probably no, since HttpTransport#fecth already take care of it //String[] locationHeader = this.getHttpTransport().getHeadersMap().get("location"); //if (redirectionLocation != null) //{ // String redirectUrl = null; // switch (this.getConfiguration().getIncarnation()) // { // case OlioConfiguration.JAVA_INCARNATION: // redirectUrl = this.getGenerator().getBaseURL() + '/' + locationHeader[0]; // break; // case OlioConfiguration.PHP_INCARNATION: // redirectUrl = this.getGenerator().getBaseURL() + '/' + locationHeader[0]; // break; // case OlioConfiguration.RAILS_INCARNATION: // redirectUrl = locationHeader[0]; // break; // } // response = this.getHttpTransport().fetchURL(redirectUrl); //} // Verify that the request succeeded. if (!this.getGenerator().checkHttpResponse(response.toString())) { this.getLogger().severe("Problems in performing request to URL: " + reqPost.getURI() + " (HTTP status code: " + this.getHttpTransport().getStatusCode() + "). Server response: " + response); throw new IOException("Problems in performing request to URL: " + reqPost.getURI() + " (HTTP status code: " + this.getHttpTransport().getStatusCode() + ")"); } // Verify that the operation succeeded. switch (this.getConfiguration().getIncarnation()) { case OlioConfiguration.JAVA_INCARNATION: // No check to do break; case OlioConfiguration.PHP_INCARNATION: // No check to do break; case OlioConfiguration.RAILS_INCARNATION: int index = response.toString().toLowerCase().indexOf("event was successfully created."); if (index == -1) { this.getLogger().severe("Problems in performing request to URL: " + reqPost.getURI() + " (HTTP status code: " + this.getHttpTransport().getStatusCode() + "): Could not find success message in result body. Server response: " + response); throw new IOException("Problems in performing request to URL: " + reqPost.getURI() + " (HTTP status code: " + this.getHttpTransport().getStatusCode() + "): Could not find success message in result body"); } break; } // Save session data this.getSessionState().setLastResponse(response.toString()); this.setFailed(false); }
diff --git a/src/test/java/com/manmoe/example/test/FirespottingITTest.java b/src/test/java/com/manmoe/example/test/FirespottingITTest.java index 0d9bb55..2010375 100644 --- a/src/test/java/com/manmoe/example/test/FirespottingITTest.java +++ b/src/test/java/com/manmoe/example/test/FirespottingITTest.java @@ -1,96 +1,98 @@ package com.manmoe.example.test; import bsh.util.Sessiond; import com.manmoe.example.model.PopupPage; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.remote.SessionId; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import us.monoid.web.AbstractContent; import us.monoid.web.Resty; import java.io.IOException; import static org.mockito.Mockito.*; import static org.testng.Assert.*; /** * Tests our Firespotting test example. * * @author Manuel Möhlmann <[email protected]> */ public class FirespottingITTest { /** * Our test object. */ private FirespottingIT firespottingIT; private PopupPage popupPage = mock(PopupPage.class); /** * Method for setting up the test environment. */ @BeforeMethod public void setUp() { this.firespottingIT = spy(new FirespottingIT()); } /** * Let's check, if we set up our test environment properly. */ @Test public void testSetUp() { RemoteWebDriver remoteWebDriver = mock(RemoteWebDriver.class); doReturn(remoteWebDriver).when(firespottingIT).getWebDriver(); // run test firespottingIT.setUp(); // check, if all went well assertNotNull(firespottingIT.popupPage); } /** * Check the tear down. */ @Test public void testTearDown() throws IOException { // insert mock to test object firespottingIT.popupPage = this.popupPage; // mock rest client firespottingIT.restClient = mock(Resty.class); // mock some objects for session key RemoteWebDriver remoteWebDriver = mock(RemoteWebDriver.class); SessionId sessionId = mock(SessionId.class); when(popupPage.getDriver()).thenReturn(remoteWebDriver); when(remoteWebDriver.getSessionId()).thenReturn(sessionId); when(sessionId.toString()).thenReturn("72345863"); // run test method firespottingIT.tearDown(); // is the method called to tear down correctly? verify(popupPage, atLeastOnce()).tearDown(); - // verify rest client actions - // @TODO: add better verification! (no more anyStrings; check the values!) - verify(firespottingIT.restClient, atLeastOnce()).authenticate(anyString(), anyString(), anyString().toCharArray()); - verify(firespottingIT.restClient, atLeastOnce()).withHeader("Content-Type", "application/json"); - verify(firespottingIT.restClient, atLeastOnce()).json(anyString(), any(AbstractContent.class)); + if (System.getenv("SAUCE_USERNAME") != null && System.getenv("SAUCE_ACCESS_KEY") != null && System.getenv("PLATFORM") != null) { + // verify rest client actions if environment variables are set + // @TODO: add better verification! (no more anyStrings; check the values!) + verify(firespottingIT.restClient, atLeastOnce()).authenticate(anyString(), anyString(), anyString().toCharArray()); + verify(firespottingIT.restClient, atLeastOnce()).withHeader("Content-Type", "application/json"); + verify(firespottingIT.restClient, atLeastOnce()).json(anyString(), any(AbstractContent.class)); + } } /** * We check the isInstalled method. */ @Test public void testIsInstalled() { firespottingIT.popupPage = this.popupPage; when(popupPage.getId()).thenReturn("testId"); firespottingIT.isInstalled(); } }
true
true
public void testTearDown() throws IOException { // insert mock to test object firespottingIT.popupPage = this.popupPage; // mock rest client firespottingIT.restClient = mock(Resty.class); // mock some objects for session key RemoteWebDriver remoteWebDriver = mock(RemoteWebDriver.class); SessionId sessionId = mock(SessionId.class); when(popupPage.getDriver()).thenReturn(remoteWebDriver); when(remoteWebDriver.getSessionId()).thenReturn(sessionId); when(sessionId.toString()).thenReturn("72345863"); // run test method firespottingIT.tearDown(); // is the method called to tear down correctly? verify(popupPage, atLeastOnce()).tearDown(); // verify rest client actions // @TODO: add better verification! (no more anyStrings; check the values!) verify(firespottingIT.restClient, atLeastOnce()).authenticate(anyString(), anyString(), anyString().toCharArray()); verify(firespottingIT.restClient, atLeastOnce()).withHeader("Content-Type", "application/json"); verify(firespottingIT.restClient, atLeastOnce()).json(anyString(), any(AbstractContent.class)); }
public void testTearDown() throws IOException { // insert mock to test object firespottingIT.popupPage = this.popupPage; // mock rest client firespottingIT.restClient = mock(Resty.class); // mock some objects for session key RemoteWebDriver remoteWebDriver = mock(RemoteWebDriver.class); SessionId sessionId = mock(SessionId.class); when(popupPage.getDriver()).thenReturn(remoteWebDriver); when(remoteWebDriver.getSessionId()).thenReturn(sessionId); when(sessionId.toString()).thenReturn("72345863"); // run test method firespottingIT.tearDown(); // is the method called to tear down correctly? verify(popupPage, atLeastOnce()).tearDown(); if (System.getenv("SAUCE_USERNAME") != null && System.getenv("SAUCE_ACCESS_KEY") != null && System.getenv("PLATFORM") != null) { // verify rest client actions if environment variables are set // @TODO: add better verification! (no more anyStrings; check the values!) verify(firespottingIT.restClient, atLeastOnce()).authenticate(anyString(), anyString(), anyString().toCharArray()); verify(firespottingIT.restClient, atLeastOnce()).withHeader("Content-Type", "application/json"); verify(firespottingIT.restClient, atLeastOnce()).json(anyString(), any(AbstractContent.class)); } }
diff --git a/analytics/src/main/java/com/ning/billing/analytics/BusinessAccountRecorder.java b/analytics/src/main/java/com/ning/billing/analytics/BusinessAccountRecorder.java index 2c774e8fa..2da59227a 100644 --- a/analytics/src/main/java/com/ning/billing/analytics/BusinessAccountRecorder.java +++ b/analytics/src/main/java/com/ning/billing/analytics/BusinessAccountRecorder.java @@ -1,226 +1,226 @@ /* * Copyright 2010-2011 Ning, Inc. * * Ning licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.ning.billing.analytics; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.UUID; import com.ning.billing.util.api.TagUserApi; import com.ning.billing.util.dao.ObjectType; import org.joda.time.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Inject; import com.ning.billing.account.api.Account; import com.ning.billing.account.api.AccountApiException; import com.ning.billing.account.api.AccountData; import com.ning.billing.account.api.AccountUserApi; import com.ning.billing.account.api.ChangedField; import com.ning.billing.analytics.dao.BusinessAccountDao; import com.ning.billing.invoice.api.Invoice; import com.ning.billing.invoice.api.InvoiceUserApi; import com.ning.billing.payment.api.PaymentApi; import com.ning.billing.payment.api.PaymentApiException; import com.ning.billing.payment.api.PaymentAttempt; import com.ning.billing.payment.api.PaymentInfoEvent; import com.ning.billing.util.tag.Tag; public class BusinessAccountRecorder { private static final Logger log = LoggerFactory.getLogger(BusinessAccountRecorder.class); private final BusinessAccountDao dao; private final AccountUserApi accountApi; private final InvoiceUserApi invoiceUserApi; private final PaymentApi paymentApi; private final TagUserApi tagUserApi; @Inject public BusinessAccountRecorder(final BusinessAccountDao dao, final AccountUserApi accountApi, final InvoiceUserApi invoiceUserApi, final PaymentApi paymentApi, final TagUserApi tagUserApi) { this.dao = dao; this.accountApi = accountApi; this.invoiceUserApi = invoiceUserApi; this.paymentApi = paymentApi; this.tagUserApi = tagUserApi; } public void accountCreated(final AccountData data) { Account account; try { account = accountApi.getAccountByKey(data.getExternalKey()); Map<String, Tag> tags = tagUserApi.getTags(account.getId(), ObjectType.ACCOUNT); final BusinessAccount bac = createBusinessAccountFromAccount(account, new ArrayList<Tag>(tags.values())); log.info("ACCOUNT CREATION " + bac); dao.createAccount(bac); } catch (AccountApiException e) { log.warn("Error encountered creating BusinessAccount",e); } } /** * Notification handler for Account changes * * @param accountId account id changed * @param changedFields list of changed fields */ public void accountUpdated(final UUID accountId, final List<ChangedField> changedFields) { // None of the fields updated interest us so far - see DefaultAccountChangeNotification // TODO We'll need notifications for tags changes eventually } /** * Notification handler for Payment creations * * @param paymentInfo payment object (from the payment plugin) */ public void accountUpdated(final PaymentInfoEvent paymentInfo) { try { final PaymentAttempt paymentAttempt = paymentApi.getPaymentAttemptForPaymentId(paymentInfo.getId()); if (paymentAttempt == null) { return; } final Account account = accountApi.getAccountById(paymentAttempt.getAccountId()); accountUpdated(account.getId()); } catch (AccountApiException e) { log.warn("Error encountered creating BusinessAccount",e); } catch (PaymentApiException e) { log.warn("Error encountered creating BusinessAccount",e); } } /** * Notification handler for Invoice creations * * @param accountId account id associated with the created invoice */ public void accountUpdated(final UUID accountId) { try { final Account account = accountApi.getAccountById(accountId); final Map<String, Tag> tags = tagUserApi.getTags(accountId, ObjectType.ACCOUNT); if (account == null) { log.warn("Couldn't find account {}", accountId); return; } BusinessAccount bac = dao.getAccount(account.getExternalKey()); if (bac == null) { bac = createBusinessAccountFromAccount(account, new ArrayList<Tag>(tags.values())); log.info("ACCOUNT CREATION " + bac); dao.createAccount(bac); } else { updateBusinessAccountFromAccount(account, bac); log.info("ACCOUNT UPDATE " + bac); dao.saveAccount(bac); } } catch (AccountApiException e) { log.warn("Error encountered creating BusinessAccount",e); } } private BusinessAccount createBusinessAccountFromAccount(final Account account, final List<Tag> tags) { final BusinessAccount bac = new BusinessAccount( account.getExternalKey(), invoiceUserApi.getAccountBalance(account.getId()), tags, // These fields will be updated below null, null, null, null, null, null ); updateBusinessAccountFromAccount(account, bac); return bac; } private void updateBusinessAccountFromAccount(final Account account, final BusinessAccount bac) { final List<UUID> invoiceIds = new ArrayList<UUID>(); try { DateTime lastInvoiceDate = null; BigDecimal totalInvoiceBalance = BigDecimal.ZERO; String lastPaymentStatus = null; String paymentMethod = null; String creditCardType = null; String billingAddressCountry = null; // Retrieve invoices information final List<Invoice> invoices = invoiceUserApi.getInvoicesByAccount(account.getId()); if (invoices != null && invoices.size() > 0) { for (final Invoice invoice : invoices) { invoiceIds.add(invoice.getId()); totalInvoiceBalance = totalInvoiceBalance.add(invoice.getBalance()); if (lastInvoiceDate == null || invoice.getInvoiceDate().isAfter(lastInvoiceDate)) { lastInvoiceDate = invoice.getInvoiceDate(); } } // Retrieve payments information for these invoices DateTime lastPaymentDate = null; final List<PaymentInfoEvent> payments = paymentApi.getPaymentInfo(invoiceIds); if (payments != null) { for (final PaymentInfoEvent payment : payments) { // Use the last payment method/type/country as the default one for the account if (lastPaymentDate == null || payment.getCreatedDate().isAfter(lastPaymentDate)) { lastPaymentDate = payment.getCreatedDate(); lastPaymentStatus = payment.getStatus(); paymentMethod = payment.getPaymentMethod(); creditCardType = payment.getCardType(); billingAddressCountry = payment.getCardCountry(); } } } } // Retrieve payments information for these invoices final PaymentInfoEvent payment = paymentApi.getLastPaymentInfo(invoiceIds); if (payment != null) { lastPaymentStatus = payment.getStatus(); paymentMethod = payment.getPaymentMethod(); creditCardType = payment.getCardType(); + billingAddressCountry = payment.getCardCountry(); } - billingAddressCountry = payment.getCardCountry(); bac.setLastPaymentStatus(lastPaymentStatus); bac.setPaymentMethod(paymentMethod); bac.setCreditCardType(creditCardType); bac.setBillingAddressCountry(billingAddressCountry); bac.setLastInvoiceDate(lastInvoiceDate); bac.setTotalInvoiceBalance(totalInvoiceBalance); bac.setBalance(invoiceUserApi.getAccountBalance(account.getId())); } catch (PaymentApiException ex) { log.error(String.format("Failed to handle acount update for account %s", account.getId()), ex); } } }
false
true
private void updateBusinessAccountFromAccount(final Account account, final BusinessAccount bac) { final List<UUID> invoiceIds = new ArrayList<UUID>(); try { DateTime lastInvoiceDate = null; BigDecimal totalInvoiceBalance = BigDecimal.ZERO; String lastPaymentStatus = null; String paymentMethod = null; String creditCardType = null; String billingAddressCountry = null; // Retrieve invoices information final List<Invoice> invoices = invoiceUserApi.getInvoicesByAccount(account.getId()); if (invoices != null && invoices.size() > 0) { for (final Invoice invoice : invoices) { invoiceIds.add(invoice.getId()); totalInvoiceBalance = totalInvoiceBalance.add(invoice.getBalance()); if (lastInvoiceDate == null || invoice.getInvoiceDate().isAfter(lastInvoiceDate)) { lastInvoiceDate = invoice.getInvoiceDate(); } } // Retrieve payments information for these invoices DateTime lastPaymentDate = null; final List<PaymentInfoEvent> payments = paymentApi.getPaymentInfo(invoiceIds); if (payments != null) { for (final PaymentInfoEvent payment : payments) { // Use the last payment method/type/country as the default one for the account if (lastPaymentDate == null || payment.getCreatedDate().isAfter(lastPaymentDate)) { lastPaymentDate = payment.getCreatedDate(); lastPaymentStatus = payment.getStatus(); paymentMethod = payment.getPaymentMethod(); creditCardType = payment.getCardType(); billingAddressCountry = payment.getCardCountry(); } } } } // Retrieve payments information for these invoices final PaymentInfoEvent payment = paymentApi.getLastPaymentInfo(invoiceIds); if (payment != null) { lastPaymentStatus = payment.getStatus(); paymentMethod = payment.getPaymentMethod(); creditCardType = payment.getCardType(); } billingAddressCountry = payment.getCardCountry(); bac.setLastPaymentStatus(lastPaymentStatus); bac.setPaymentMethod(paymentMethod); bac.setCreditCardType(creditCardType); bac.setBillingAddressCountry(billingAddressCountry); bac.setLastInvoiceDate(lastInvoiceDate); bac.setTotalInvoiceBalance(totalInvoiceBalance); bac.setBalance(invoiceUserApi.getAccountBalance(account.getId())); } catch (PaymentApiException ex) { log.error(String.format("Failed to handle acount update for account %s", account.getId()), ex); } }
private void updateBusinessAccountFromAccount(final Account account, final BusinessAccount bac) { final List<UUID> invoiceIds = new ArrayList<UUID>(); try { DateTime lastInvoiceDate = null; BigDecimal totalInvoiceBalance = BigDecimal.ZERO; String lastPaymentStatus = null; String paymentMethod = null; String creditCardType = null; String billingAddressCountry = null; // Retrieve invoices information final List<Invoice> invoices = invoiceUserApi.getInvoicesByAccount(account.getId()); if (invoices != null && invoices.size() > 0) { for (final Invoice invoice : invoices) { invoiceIds.add(invoice.getId()); totalInvoiceBalance = totalInvoiceBalance.add(invoice.getBalance()); if (lastInvoiceDate == null || invoice.getInvoiceDate().isAfter(lastInvoiceDate)) { lastInvoiceDate = invoice.getInvoiceDate(); } } // Retrieve payments information for these invoices DateTime lastPaymentDate = null; final List<PaymentInfoEvent> payments = paymentApi.getPaymentInfo(invoiceIds); if (payments != null) { for (final PaymentInfoEvent payment : payments) { // Use the last payment method/type/country as the default one for the account if (lastPaymentDate == null || payment.getCreatedDate().isAfter(lastPaymentDate)) { lastPaymentDate = payment.getCreatedDate(); lastPaymentStatus = payment.getStatus(); paymentMethod = payment.getPaymentMethod(); creditCardType = payment.getCardType(); billingAddressCountry = payment.getCardCountry(); } } } } // Retrieve payments information for these invoices final PaymentInfoEvent payment = paymentApi.getLastPaymentInfo(invoiceIds); if (payment != null) { lastPaymentStatus = payment.getStatus(); paymentMethod = payment.getPaymentMethod(); creditCardType = payment.getCardType(); billingAddressCountry = payment.getCardCountry(); } bac.setLastPaymentStatus(lastPaymentStatus); bac.setPaymentMethod(paymentMethod); bac.setCreditCardType(creditCardType); bac.setBillingAddressCountry(billingAddressCountry); bac.setLastInvoiceDate(lastInvoiceDate); bac.setTotalInvoiceBalance(totalInvoiceBalance); bac.setBalance(invoiceUserApi.getAccountBalance(account.getId())); } catch (PaymentApiException ex) { log.error(String.format("Failed to handle acount update for account %s", account.getId()), ex); } }
diff --git a/modules/cpr/src/main/java/org/atmosphere/cpr/SessionSupport.java b/modules/cpr/src/main/java/org/atmosphere/cpr/SessionSupport.java index 15da0b8c2..232f20b2d 100644 --- a/modules/cpr/src/main/java/org/atmosphere/cpr/SessionSupport.java +++ b/modules/cpr/src/main/java/org/atmosphere/cpr/SessionSupport.java @@ -1,53 +1,56 @@ /* * Copyright 2013 Jeanfrancois Arcand * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.atmosphere.cpr; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; public class SessionSupport implements HttpSessionListener { private final Logger logger = LoggerFactory.getLogger(SessionSupport.class); public SessionSupport() { } @Override public void sessionCreated(HttpSessionEvent se) { logger.trace("Session created"); } @Override public void sessionDestroyed(HttpSessionEvent se) { logger.trace("Session destroyed"); try { HttpSession s = se.getSession(); - for (Broadcaster b : BroadcasterFactory.getDefault().lookupAll()) { - for (AtmosphereResource r : b.getAtmosphereResources()) { - if (r.session() != null && r.session().getId().equals(s.getId())) { - AtmosphereResourceImpl.class.cast(r).session(null); + BroadcasterFactory factory = BroadcasterFactory.getDefault(); + if (factory != null) { + for (Broadcaster b : factory.lookupAll()) { + for (AtmosphereResource r : b.getAtmosphereResources()) { + if (r.session() != null && r.session().getId().equals(s.getId())) { + AtmosphereResourceImpl.class.cast(r).session(null); + } } - } + } } } catch (Throwable t) { logger.warn("", t); } } }
false
true
public void sessionDestroyed(HttpSessionEvent se) { logger.trace("Session destroyed"); try { HttpSession s = se.getSession(); for (Broadcaster b : BroadcasterFactory.getDefault().lookupAll()) { for (AtmosphereResource r : b.getAtmosphereResources()) { if (r.session() != null && r.session().getId().equals(s.getId())) { AtmosphereResourceImpl.class.cast(r).session(null); } } } } catch (Throwable t) { logger.warn("", t); } }
public void sessionDestroyed(HttpSessionEvent se) { logger.trace("Session destroyed"); try { HttpSession s = se.getSession(); BroadcasterFactory factory = BroadcasterFactory.getDefault(); if (factory != null) { for (Broadcaster b : factory.lookupAll()) { for (AtmosphereResource r : b.getAtmosphereResources()) { if (r.session() != null && r.session().getId().equals(s.getId())) { AtmosphereResourceImpl.class.cast(r).session(null); } } } } } catch (Throwable t) { logger.warn("", t); } }