answer
stringlengths
17
10.2M
package cn.com.lemon.base.xml; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import static cn.com.lemon.base.Preasserts.checkArgument; import static cn.com.lemon.base.Strings.isNullOrEmpty; import com.thoughtworks.xstream.XStream; /** * Static utility methods pertaining to {@code Xmls} primitives. * <p> * The base utility contain basic operate. * <p> * Create XML data from Java Object and Parser XML data to Java Object * * @author shellpo shih * @version 1.0 */ public final class Xmls { private static final Map<String, XStream> XSTREAMS = new ConcurrentHashMap<String, XStream>(); private static final String DEFAULT_NAME = "FALSE"; private static final String DEFAULT_XML_HEADER = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"; private Xmls() { } static { XSTREAMS.put("TRUE", new XStream(new XmlsDriver(true))); XSTREAMS.put("FALSE", new XStream(new XmlsDriver(false))); } public static XStream newInstance() { return newInstance(DEFAULT_NAME); } public static XStream newInstance(String name) { XStream stream = XSTREAMS.get(name); checkArgument(stream != null); return stream; } /** * Create XML data from Java Object * * @param data * {@code Object} the data * @param isUseCDATA * is use CDATA * @param isContainHeader * is contail xml header * @param clazz * @return {@link String} the xml data */ public static String generator(Object data, boolean isUseCDATA, boolean isContainHeader, Class<?> clazz) { if (null == data) return null; XStream xstream = isUseCDATA ? newInstance("TRUE") : newInstance(); xstream.processAnnotations(clazz); xstream.autodetectAnnotations(true); return isContainHeader ? DEFAULT_XML_HEADER + xstream.toXML(data) : xstream.toXML(data); } /** * Create XML data from Java Object and write the XML data to files * * @param data * {@code Object} the data * @param xmlFilePath * write date to xml file * @param isUseCDATA * is use CDATA * @param isContainHeader * is contail xml header * @param clazz * @return {@link String} the xml data */ public static boolean generator(Object data, String xmlFilePath, boolean isUseCDATA, boolean isContainHeader, Class<?> clazz) { if (null == data || isNullOrEmpty(xmlFilePath)) return false; File file = new File(xmlFilePath); FileOutputStream out = null; BufferedWriter writer = null; try { if (!file.exists() && !file.isFile()) file.createNewFile(); out = new FileOutputStream(file); writer = new BufferedWriter(new OutputStreamWriter(out)); writer.write(generator(data, isUseCDATA, isContainHeader, clazz)); return true; } catch (FileNotFoundException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } finally { if (writer != null) { try { writer.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * Parser XML data to Java Object * * @param data * {@code Object} the data * @param isUseCDATA * is use CDATA * @param clazz * @return {@link String} the xml data */ @SuppressWarnings("unchecked") public static <T> T parser(String data, boolean isUseCDATA, Class<?> clazz) { if (isNullOrEmpty(data)) { return null; } XStream xstream = isUseCDATA ? newInstance("TRUE") : newInstance(); if (clazz != null) { xstream.processAnnotations(clazz); } return (T) xstream.fromXML(data); } }
package com.xamoom.android.mapping; import com.xamoom.android.request.Location; /** * Used for mapping spot form the xamoom-cloud-api. * Spot will have a displayName, a description (optional), a location and a image (optional). * * @author Raphael Seher * * @see SpotMap */ public class Spot { private String displayName; private String description; private Location location; private String image; @Override public String toString() { return String.format("\ndisplayName: %s, \ndescription: %s, \nlocation: %f, %f, \nimage: %s", displayName, description, location.getLat(), location.getLon(), image); } public String getDisplayName() { return displayName; } public String getDescription() { return description; } public Location getLocation() { return location; } public String getImage() { return image; } }
package com.conveyal.disser; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.io.Serializable; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Random; import java.util.Map.Entry; import org.geotools.data.DataStore; import org.geotools.data.DataStoreFinder; import org.geotools.data.DefaultTransaction; import org.geotools.data.FeatureSource; import org.geotools.data.Transaction; import org.geotools.data.shapefile.ShapefileDataStore; import org.geotools.data.shapefile.ShapefileDataStoreFactory; import org.geotools.data.simple.SimpleFeatureSource; import org.geotools.data.simple.SimpleFeatureStore; import org.geotools.factory.CommonFactoryFinder; import org.geotools.feature.DefaultFeatureCollection; import org.geotools.feature.FeatureCollection; import org.geotools.feature.FeatureIterator; import org.geotools.feature.simple.SimpleFeatureBuilder; import org.geotools.feature.simple.SimpleFeatureTypeBuilder; import org.geotools.geometry.jts.ReferencedEnvelope; import org.geotools.referencing.crs.DefaultGeographicCRS; import org.opengis.feature.Feature; import org.opengis.feature.GeometryAttribute; import org.opengis.feature.Property; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; import org.opengis.feature.type.FeatureType; import org.opengis.filter.FilterFactory2; import org.opengis.filter.spatial.BBOX; import org.opengis.geometry.BoundingBox; import org.opengis.referencing.crs.CoordinateReferenceSystem; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.GeometryFactory; import com.vividsolutions.jts.geom.MultiPolygon; import com.vividsolutions.jts.geom.Point; import com.vividsolutions.jts.geom.TopologyException; public class Disser { static boolean GEOM_TOLERANT = false; public static void main(String[] args) throws Exception { if( args.length < 5 ) { System.out.println( "usage: cmd [--(discrete|shapefile)] indicator_shp indicator_fld diss_shp diss_fld output_fn" ); return; } int argOfs = 0; boolean discrete = args[0].equals("--discrete"); boolean shapefile = args[0].equals("--shapefile"); if(discrete || shapefile){ argOfs=1; } String indicator_shp = args[argOfs+0]; String indFldExpression = args[argOfs+1]; String diss_shp = args[argOfs+2]; String dissFldExpression = args[argOfs+3]; String output_fn = args[argOfs+4]; FeatureSource<?, ?> indicatorSource = getFeatureSource(indicator_shp); FeatureSource<?, ?> dissSource = getFeatureSource(diss_shp); CoordinateReferenceSystem crs1 = indicatorSource.getSchema().getCoordinateReferenceSystem(); CoordinateReferenceSystem crs2 = dissSource.getSchema().getCoordinateReferenceSystem(); if( !crs1.equals(crs2) ){ throw new Exception( "Coordinate systems don't match. "+crs1+"\n\n"+crs2 ); } HashMap<Feature, ArrayList<Feature>> dissToInd = collectIndByDiss( indicatorSource, dissSource); if(dissToInd.size()==0){ System.out.println( "no overlaps found." ); return; } // register each diss with the inds, along with the ind's share of the diss's magnitude HashMap<Feature, ArrayList<DissShare>> indDissShares = collectDissSharesByInd( dissFldExpression, dissToInd); // dole out the ind's magnitude in proportion to the diss's mag share, accumulating under the diss HashMap<Feature, Double> dissMags = distributeIndToDisses( indFldExpression, indDissShares); // go through the dissMag list and emit points at centroids if(shapefile){ writeToShapefile(output_fn, dissMags); } else { writeToCSV(discrete, output_fn, dissMags); } System.out.print("done.\n"); } private static void writeToCSV(boolean discrete, String output_fn, HashMap<Feature, Double> dissMags) throws FileNotFoundException, UnsupportedEncodingException { System.out.print( "printing to file..." ); PrintWriter writer = new PrintWriter(output_fn, "UTF-8"); writer.println("lon,lat,mag"); Random rand = new Random(); //could come in handy if we're doing a discrete output for( Entry<Feature, Double> entry : dissMags.entrySet() ) { Feature diss = entry.getKey(); Geometry dissGeom = (Geometry)diss.getDefaultGeometryProperty().getValue(); double mag = entry.getValue(); if(discrete){ // probabilistically round magnitude to an integer. This way if there's 5 disses with mag 0.2, on average // one will be 1 and the others 0, instead of rounding all down to 0. int discreteMag; double remainder = mag-Math.floor(mag); //number between 0 and 1 if(remainder<rand.nextDouble()){ //remainder is smaller than random integer; relatively likely for small remainders //so when this happens we'll round down discreteMag = (int)Math.floor(mag); } else { discreteMag = (int)Math.ceil(mag); } BoundingBox bb = diss.getBounds(); for(int j=0; j<discreteMag; j++){ Point pt = getRandomPoint( bb, dissGeom ); if(pt==null){ continue; //something went wrong; act cool } writer.println( pt.getX()+","+pt.getY()+",1"); } } else { Point centroid = dissGeom.getCentroid(); if(mag>0){ writer.println( centroid.getX()+","+centroid.getY()+","+mag); } } } writer.flush(); writer.close(); } private static void writeToShapefile(String output_fn, HashMap<Feature, Double> dissMags) throws MalformedURLException, IOException { System.out.println( "printing to shapefile..." ); ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory(); Map<String, Serializable> params = new HashMap<String, Serializable>(); params.put("url", new File(output_fn).toURI().toURL()); params.put("create spatial index", Boolean.TRUE); ShapefileDataStore outputStore = (ShapefileDataStore)dataStoreFactory.createNewDataStore(params); outputStore.forceSchemaCRS(DefaultGeographicCRS.WGS84); // build the type SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder(); builder.setName("diss"); builder.setCRS(DefaultGeographicCRS.WGS84); builder.add("the_geom", MultiPolygon.class); builder.length(16).add("mag", Float.class); final SimpleFeatureType dissType = builder.buildFeatureType(); outputStore.createSchema(dissType); DefaultFeatureCollection featureCollection = new DefaultFeatureCollection(); SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(dissType); int j=0; for(Entry<Feature, Double> entry : dissMags.entrySet()) { if(j%1000==0){ System.out.println("writing feature "+j); } Feature diss = entry.getKey(); Geometry dissGeom = (Geometry)diss.getDefaultGeometryProperty().getValue(); double mag = entry.getValue(); featureBuilder.add(dissGeom); featureBuilder.add(mag); SimpleFeature feature = featureBuilder.buildFeature(null); featureCollection.add(feature); j++; } Transaction transaction = new DefaultTransaction("create"); String outputTypeName = outputStore.getTypeNames()[0]; SimpleFeatureSource featureSource = outputStore.getFeatureSource(outputTypeName); if (featureSource instanceof SimpleFeatureStore) { System.out.println("committing"); SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource; featureStore.setTransaction(transaction); featureStore.addFeatures(featureCollection); transaction.commit(); transaction.close(); } } private static HashMap<Feature, Double> distributeIndToDisses( String indicator_fld, HashMap<Feature, ArrayList<DissShare>> indDissShares) throws Exception { System.out.println( "doling out ind magnitudes to disses" ); HashMap<Feature,Double> dissMags = new HashMap<Feature,Double>(); for( Entry<Feature, ArrayList<DissShare>> entry : indDissShares.entrySet() ){ Feature ind = entry.getKey(); ArrayList<DissShare> dissShares = entry.getValue(); // count up total shares int totalDissMag = 0; int totalDiss = 0; for(DissShare dissShare : dissShares){ totalDissMag += dissShare.mag; totalDiss += 1; } // get magnitude of ind double indMag = getFieldsByExpression( indicator_fld, ind ); if(indMag==0.0){ continue; } // for every diss associated with ind for( DissShare dissShare : dissShares ){ // find fraction of ind doleable to diss double fraction; if(totalDissMag>0){ fraction = dissShare.mag/totalDissMag; } else { // if all disses under ind have 0 magnitude, but the // ind still has magnitude to dole out, dole out equally // to all disses. fraction = 1.0/totalDiss; } double doleable = indMag*fraction; if(doleable==0.0){ continue; } // accumulate values doled out to disses Double dissMag = dissMags.get(dissShare.diss); if(dissMag==null){ dissMag = new Double(0); } dissMag += doleable; dissMags.put(dissShare.diss,dissMag); } } return dissMags; } private static HashMap<Feature, ArrayList<DissShare>> collectDissSharesByInd( String dissFldExpression, HashMap<Feature, ArrayList<Feature>> dissToInd) throws Exception { System.out.println( "accumulating diss shares under inds" ); HashMap<Feature,ArrayList<DissShare>> indDissShares = new HashMap<Feature,ArrayList<DissShare>>(); for( Entry<Feature, ArrayList<Feature>> entry : dissToInd.entrySet() ){ Feature diss = entry.getKey(); ArrayList<Feature> inds = entry.getValue(); // determine diss's magnitude double mag = getFieldsByExpression(dissFldExpression, diss); Geometry dissGeo = (Geometry)diss.getDefaultGeometryProperty().getValue(); double dissGeoArea = dissGeo.getArea(); for(Feature ind : inds){ // find the fraction of diss overlapping each ind shape Geometry indGeo = (Geometry)ind.getDefaultGeometryProperty().getValue(); Geometry overlap; try{ overlap = dissGeo.intersection(indGeo); } catch (TopologyException e){ if(GEOM_TOLERANT){ // something strange happened; carry on continue; } else{ throw e; } } double overlapArea = overlap.getArea(); double fraction = overlapArea/dissGeoArea; // assign the magnitude proportionately double share = fraction*mag; if(share==0.0){ continue; } // then register the diss feature's share with the ind feature ArrayList<DissShare> shares = indDissShares.get(ind); if(shares==null){ shares = new ArrayList<DissShare>(); indDissShares.put(ind, shares); } shares.add(new DissShare(diss,share)); } } return indDissShares; } private static HashMap<Feature, ArrayList<Feature>> collectIndByDiss( FeatureSource<?, ?> indicatorSource, FeatureSource<?, ?> dissSource) throws IOException { HashMap<Feature,ArrayList<Feature>> dissToInd = new HashMap<Feature,ArrayList<Feature>>(); FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2(); FeatureType schema = dissSource.getSchema(); String geometryPropertyName = schema.getGeometryDescriptor().getLocalName(); CoordinateReferenceSystem dissCRS = schema.getGeometryDescriptor().getCoordinateReferenceSystem(); // get the part of the indicator file where diss items will be found ReferencedEnvelope dissBBox = dissSource.getBounds(); String indicatorPropertyName = indicatorSource.getSchema().getGeometryDescriptor().getLocalName(); BBOX dissFilter = ff.bbox(ff.property(indicatorPropertyName), dissBBox); FeatureCollection<?, ?> indCollection = indicatorSource.getFeatures(dissFilter); FeatureIterator<?> indIterator = indCollection.features(); int n = indCollection.size(); System.out.println( "accumulating ind geoms under disses" ); int i=0; while( indIterator.hasNext() ){ if(i%100==0){ System.out.print( "\r"+i+"/"+n+" ("+(100*(float)i)/n+"%)" ); } Feature ind = (Feature) indIterator.next(); GeometryAttribute indGeoAttr = ind.getDefaultGeometryProperty(); Geometry indGeo = (Geometry)indGeoAttr.getValue(); // Get every diss geometry that intersects with the indicator geometry ReferencedEnvelope bbox = new ReferencedEnvelope(dissCRS); bbox.setBounds(indGeoAttr.getBounds()); BBOX filter = ff.bbox(ff.property(geometryPropertyName), bbox); FeatureCollection<?, ?> dissCollection = dissSource.getFeatures(filter); FeatureIterator<?> dissIterator = dissCollection.features(); // register the ind feature with the diss while(dissIterator.hasNext()){ Feature diss = (Feature)dissIterator.next(); GeometryAttribute dissGeoAttr = diss.getDefaultGeometryProperty(); Geometry dissGeo = (Geometry)dissGeoAttr.getValue(); if(dissGeo.crosses(indGeo) || dissGeo.equals(indGeo)){ ArrayList<Feature> inds = dissToInd.get(diss); if(inds==null){ inds = new ArrayList<Feature>(); dissToInd.put(diss, inds); } inds.add(ind); } } dissIterator.close(); i++; } System.out.println(""); //print newline after the progress meter return dissToInd; } private static FeatureSource<?, ?> getFeatureSource(String shp_filename) throws MalformedURLException, IOException { // construct shapefile factory File file = new File( shp_filename ); Map<String,URL> map = new HashMap<String,URL>(); map.put( "url", file.toURI().toURL() ); DataStore dataStore = DataStoreFinder.getDataStore( map ); // get shapefile as generic 'feature source' String typeName = dataStore.getTypeNames()[0]; FeatureSource<?, ?> source = dataStore.getFeatureSource( typeName ); return source; } private static double getFieldsByExpression(String fieldExpression, Feature feature) throws Exception { double mag=0; String[] dissFlds = fieldExpression.split("\\+"); for(String dissFld : dissFlds ){ mag += parseField(dissFld.trim(), feature); } return mag; } private static double parseField(String diss_fld, Feature diss) throws Exception { double mag; if(diss_fld.equals("::area::")){ mag = ((Geometry)diss.getDefaultGeometryProperty().getValue()).getArea(); } else { Property magProp = diss.getProperty(diss_fld); if(magProp==null){ String propStrings = ""; Collection<Property> props = diss.getProperties(); for( Property prop : props ){ propStrings += " "+prop.getName(); } throw new Exception("Property '"+diss_fld+"' not found. Options are:"+propStrings+"." ); } Class<?> cls = magProp.getType().getBinding(); Object propVal = diss.getProperty( diss_fld ).getValue(); if(propVal==null){ return 0; } if(cls.equals(Long.class)){ mag = (Long)propVal; } else if(cls.equals(Integer.class)){ mag = (Integer)propVal; } else if(cls.equals(Double.class)){ mag = (Double)propVal; } else if(cls.equals(Float.class)){ mag = (Float)propVal; } else { throw new Exception( "Diss property has unkown type "+cls ); } } return mag; } private static Point getRandomPoint(BoundingBox bb, Geometry geom) { Random rand = new Random(); GeometryFactory gf = new GeometryFactory(); Point pt = null; for(int i=0; i<1000; i++){ double x = randdouble(rand, bb.getMinX(),bb.getMaxX()); double y = randdouble(rand, bb.getMinY(),bb.getMaxY()); pt = gf.createPoint( new Coordinate(x,y) ); if(geom.contains(pt)){ return pt; } } return null; } private static double randdouble(Random rand, double minX, double maxX) { return minX + rand.nextDouble()*(maxX-minX); } }
package pl.edu.icm.yadda.analysis.bibref; import pl.edu.icm.yadda.analysis.AnalysisException; import pl.edu.icm.yadda.analysis.textr.model.BxDocument; /** * Bibliographic reference extractor interface. * * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public interface BibReferenceExtractor { public String[] extractBibReferences(BxDocument document) throws AnalysisException; }
package com.conveyal.gtfs; import com.conveyal.gtfs.error.GTFSError; import com.conveyal.gtfs.loader.FeedLoadResult; import com.conveyal.gtfs.loader.JdbcGTFSFeedConverter; import com.conveyal.gtfs.model.*; import com.conveyal.gtfs.model.Calendar; import com.conveyal.gtfs.validator.Validator; import com.conveyal.gtfs.validator.service.GeoUtils; import com.google.common.collect.*; import com.google.common.eventbus.EventBus; import com.google.common.util.concurrent.ExecutionError; import com.vividsolutions.jts.algorithm.ConvexHull; import com.vividsolutions.jts.geom.*; import com.vividsolutions.jts.index.strtree.STRtree; import org.geotools.referencing.GeodeticCalculator; import org.mapdb.BTreeMap; import org.mapdb.DB; import org.mapdb.DBMaker; import org.mapdb.Fun; import org.mapdb.Fun.Tuple2; import org.mapdb.Serializer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.sql.DataSource; import java.io.Closeable; import java.io.File; import java.io.FileOutputStream; import java.io.IOError; import java.io.IOException; import java.io.OutputStream; import java.time.format.DateTimeFormatter; import java.util.*; import java.util.concurrent.ConcurrentNavigableMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipOutputStream; /** * All entities must be from a single feed namespace. * Composed of several GTFSTables. */ public class GTFSFeed implements Cloneable, Closeable { private static final Logger LOG = LoggerFactory.getLogger(GTFSFeed.class); private static final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyyMMdd"); private DB db; public String feedId = null; // TODO make all of these Maps MapDBs so the entire GTFSFeed is persistent and uses constant memory /* Some of these should be multimaps since they don't have an obvious unique key. */ public final Map<String, Agency> agency; public final Map<String, FeedInfo> feedInfo; public final NavigableSet<Tuple2<String, Frequency>> frequencies; public final Map<String, Route> routes; public final Map<String, Stop> stops; public final Map<String, Transfer> transfers; public final BTreeMap<String, Trip> trips; public final Set<String> transitIds = new HashSet<>(); /** CRC32 of the GTFS file this was loaded from */ public long checksum; /* Map from 2-tuples of (shape_id, shape_pt_sequence) to shape points */ public final ConcurrentNavigableMap<Tuple2<String, Integer>, ShapePoint> shape_points; /* Map from 2-tuples of (trip_id, stop_sequence) to stoptimes. */ public final BTreeMap<Tuple2, StopTime> stop_times; // public final ConcurrentMap<String, Long> stopCountByStopTime; // TODO: Remove these indexes from GTFSFeed. // /* Map from stop (stop_id) to stopTimes tuples (trip_id, stop_sequence) */ // public final NavigableSet<Tuple2<String, Tuple2>> stopStopTimeSet; // public final ConcurrentMap<String, Long> stopCountByStopTime; // public final NavigableSet<Tuple2<String, String>> tripsPerService; // public final NavigableSet<Tuple2<String, String>> servicesPerDate; /* A fare is a fare_attribute and all fare_rules that reference that fare_attribute. */ public final Map<String, Fare> fares; /* A service is a calendar entry and all calendar_dates that modify that calendar entry. */ public final BTreeMap<String, Service> services; /* A place to accumulate errors while the feed is loaded. Tolerate as many errors as possible and keep on loading. */ public final NavigableSet<GTFSError> errors; /* Stops spatial index which gets built lazily by getSpatialIndex() */ private transient STRtree spatialIndex; /* Convex hull of feed (based on stops) built lazily by getConvexHull() */ private transient Polygon convexHull; /* Merged stop buffers polygon built lazily by getMergedBuffers() */ private transient Geometry mergedBuffers; /* Create geometry factory to produce LineString geometries. */ GeometryFactory gf = new GeometryFactory(); /* Map routes to associated trip patterns. */ // TODO: Hash Multimapping in guava (might need dependency). public final Map<String, Pattern> patterns; // TODO bind this to map above so that it is kept up to date automatically public final Map<String, String> tripPatternMap; private boolean loaded = false; /* A place to store an event bus that is passed through constructor. */ public transient EventBus eventBus; /** * The order in which we load the tables is important for two reasons. * 1. We must load feed_info first so we know the feed ID before loading any other entities. This could be relaxed * by having entities point to the feed object rather than its ID String. * 2. Referenced entities must be loaded before any entities that reference them. This is because we check * referential integrity while the files are being loaded. This is done on the fly during loading because it allows * us to associate a line number with errors in objects that don't have any other clear identifier. * * Interestingly, all references are resolvable when tables are loaded in alphabetical order. */ public void loadFromFile(ZipFile zip, String fid) throws Exception { if (this.loaded) throw new UnsupportedOperationException("Attempt to load GTFS into existing database"); // NB we don't have a single CRC for the file, so we combine all the CRCs of the component files. NB we are not // simply summing the CRCs because CRCs are (I assume) uniformly randomly distributed throughout the width of a // long, so summing them is a convolution which moves towards a Gaussian with mean 0 (i.e. more concentrated // probability in the center), degrading the quality of the hash. Instead we XOR. Assuming each bit is independent, // this will yield a nice uniformly distributed result, because when combining two bits there is an equal // probability of any input, which means an equal probability of any output. At least I think that's all correct. // Repeated XOR is not commutative but zip.stream returns files in the order they are in the central directory // of the zip file, so that's not a problem. checksum = zip.stream().mapToLong(ZipEntry::getCrc).reduce((l1, l2) -> l1 ^ l2).getAsLong(); db.getAtomicLong("checksum").set(checksum); new FeedInfo.Loader(this).loadTable(zip); // maybe we should just point to the feed object itself instead of its ID, and null out its stoptimes map after loading if (fid != null) { feedId = fid; LOG.info("Feed ID is undefined, pester maintainers to include a feed ID. Using file name {}.", feedId); // TODO log an error, ideally feeds should include a feedID } else if (feedId == null || feedId.isEmpty()) { feedId = new File(zip.getName()).getName().replaceAll("\\.zip$", ""); LOG.info("Feed ID is undefined, pester maintainers to include a feed ID. Using file name {}.", feedId); // TODO log an error, ideally feeds should include a feedID } else { LOG.info("Feed ID is '{}'.", feedId); } db.getAtomicString("feed_id").set(feedId); new Agency.Loader(this).loadTable(zip); // calendars and calendar dates are joined into services. This means a lot of manipulating service objects as // they are loaded; since mapdb keys/values are immutable, load them in memory then copy them to MapDB once // we're done loading them Map<String, Service> serviceTable = new HashMap<>(); new Calendar.Loader(this, serviceTable).loadTable(zip); new CalendarDate.Loader(this, serviceTable).loadTable(zip); this.services.putAll(serviceTable); serviceTable = null; // free memory // Same deal Map<String, Fare> fares = new HashMap<>(); new FareAttribute.Loader(this, fares).loadTable(zip); new FareRule.Loader(this, fares).loadTable(zip); this.fares.putAll(fares); fares = null; // free memory new Route.Loader(this).loadTable(zip); new ShapePoint.Loader(this).loadTable(zip); new Stop.Loader(this).loadTable(zip); new Transfer.Loader(this).loadTable(zip); new Trip.Loader(this).loadTable(zip); new Frequency.Loader(this).loadTable(zip); new StopTime.Loader(this).loadTable(zip); // comment out this line for quick testing using NL feed LOG.info("{} errors", errors.size()); for (GTFSError error : errors) { LOG.info("{}", error); } loaded = true; } public void loadFromFile(ZipFile zip) throws Exception { loadFromFile(zip, null); } public FeedLoadResult toSQL (DataSource dataSource) { JdbcGTFSFeedConverter converter = new JdbcGTFSFeedConverter(this, dataSource); return converter.loadTables(); } public void toFile (String file) { try { File out = new File(file); OutputStream os = new FileOutputStream(out); ZipOutputStream zip = new ZipOutputStream(os); // write everything // TODO: shapes // don't write empty feed_info.txt if (!this.feedInfo.isEmpty()) new FeedInfo.Writer(this).writeTable(zip); new Agency.Writer(this).writeTable(zip); new Calendar.Writer(this).writeTable(zip); new CalendarDate.Writer(this).writeTable(zip); new FareAttribute.Writer(this).writeTable(zip); new FareRule.Writer(this).writeTable(zip); new Frequency.Writer(this).writeTable(zip); new Route.Writer(this).writeTable(zip); new Stop.Writer(this).writeTable(zip); new ShapePoint.Writer(this).writeTable(zip); new Transfer.Writer(this).writeTable(zip); new Trip.Writer(this).writeTable(zip); new StopTime.Writer(this).writeTable(zip); zip.close(); LOG.info("GTFS file written"); } catch (Exception e) { LOG.error("Error saving GTFS: {}", e.getMessage()); throw new RuntimeException(e); } } public void validate (boolean repair, Validator... validators) { long startValidation = System.currentTimeMillis(); for (Validator validator : validators) { try { long startValidator = System.currentTimeMillis(); // validator.validate(this, repair); long endValidator = System.currentTimeMillis(); long diff = endValidator - startValidator; LOG.info("{} finished in {} milliseconds.", validator.getClass().getSimpleName(), TimeUnit.NANOSECONDS.toMillis(diff)); } catch (Exception e) { LOG.error("Could not run {} validator.", validator.getClass().getSimpleName()); // LOG.error(e.toString()); e.printStackTrace(); } } long endValidation = System.nanoTime(); long total = endValidation - startValidation; LOG.info("{} validators completed in {} milliseconds.", validators.length, TimeUnit.NANOSECONDS.toMillis(total)); } // validate function call that should explicitly list each validator to run on GTFSFeed public void validate () { } /** * Static factory method returning a new instance of GTFSFeed containing the contents of * the GTFS file at the supplied filesystem path. */ public static GTFSFeed fromFile(String file) { return fromFile(file, null); } /** * Static factory method returning a new instance of GTFSFeed containing the contents of * the GTFS file at the supplied filesystem path. Forces the feedId to the * supplied value if the parameter is non-null. */ public static GTFSFeed fromFile(String file, String feedId) { GTFSFeed feed = new GTFSFeed(); ZipFile zip; try { zip = new ZipFile(file); if (feedId == null) { feed.loadFromFile(zip); } else { feed.loadFromFile(zip, feedId); } zip.close(); return feed; } catch (Exception e) { LOG.error("Error loading GTFS: {}", e.getMessage()); throw new RuntimeException(e); } } public boolean hasFeedInfo () { return !this.feedInfo.isEmpty(); } public FeedInfo getFeedInfo () { return this.hasFeedInfo() ? this.feedInfo.values().iterator().next() : null; } /** * For the given trip ID, fetch all the stop times in order of increasing stop_sequence. * This is an efficient iteration over a tree map. */ public Iterable<StopTime> getOrderedStopTimesForTrip (String trip_id) { Map<Fun.Tuple2, StopTime> tripStopTimes = stop_times.subMap( Fun.t2(trip_id, null), Fun.t2(trip_id, Fun.HI) ); return tripStopTimes.values(); } /** * TODO rename getStopSpatialIndex to make it clear what the index contains. */ public STRtree getSpatialIndex () { if (this.spatialIndex == null) { synchronized (this) { if (this.spatialIndex == null) { // build spatial index STRtree stopIndex = new STRtree(); for(Stop stop : this.stops.values()) { try { if (Double.isNaN(stop.stop_lat) || Double.isNaN(stop.stop_lon)) { continue; } Coordinate stopCoord = new Coordinate(stop.stop_lat, stop.stop_lon); stopIndex.insert(new Envelope(stopCoord), stop); } catch (Exception e) { e.printStackTrace(); } } try { stopIndex.build(); this.spatialIndex = stopIndex; } catch (Exception e) { e.printStackTrace(); } } } } return this.spatialIndex; } /** Get the shape for the given shape ID */ public Shape getShape (String shape_id) { Shape shape = new Shape(this, shape_id); return shape.shape_dist_traveled.length > 0 ? shape : null; } /** * MapDB-based implementation to find patterns. * * FIXME: Remove and make pattern finding happen during validation? We want to share the pattern finder between the * two implementations (MapDB and RDBMS), apply the same validation process to both kinds of storage, and produce * Patterns in the same way in both cases, during validation. This prevents us from iterating over every stopTime * twice, since we're already iterating over all of them in validation. However, in this case it might not be costly * to simply retrieve the stop times from the stop_times map. */ public void findPatterns () { PatternFinder patternFinder = new PatternFinder(); // Iterate over trips and process each trip and its stop times. for (Trip trip : this.trips.values()) { Iterable<StopTime> orderedStopTimesForTrip = this.getOrderedStopTimesForTrip(trip.trip_id); patternFinder.processTrip(trip, orderedStopTimesForTrip); } Map<TripPatternKey, Pattern> patternObjects = patternFinder.createPatternObjects(this.stops, null); this.patterns.putAll(patternObjects.values().stream() .collect(Collectors.toMap(Pattern::getId, pattern -> pattern))); } /** * For the given trip ID, fetch all the stop times in order, and interpolate stop-to-stop travel times. */ public Iterable<StopTime> getInterpolatedStopTimesForTrip (String trip_id) throws FirstAndLastStopsDoNotHaveTimes { // clone stop times so as not to modify base GTFS structures StopTime[] stopTimes = StreamSupport.stream(getOrderedStopTimesForTrip(trip_id).spliterator(), false) .map(st -> st.clone()) .toArray(i -> new StopTime[i]); // avoid having to make sure that the array has length below. if (stopTimes.length == 0) return Collections.emptyList(); // first pass: set all partially filled stop times for (StopTime st : stopTimes) { if (st.arrival_time != Entity.INT_MISSING && st.departure_time == Entity.INT_MISSING) { st.departure_time = st.arrival_time; } if (st.arrival_time == Entity.INT_MISSING && st.departure_time != Entity.INT_MISSING) { st.arrival_time = st.departure_time; } } // quick check: ensure that first and last stops have times. // technically GTFS requires that both arrival_time and departure_time be filled at both the first and last stop, // but we are slightly more lenient and only insist that one of them be filled at both the first and last stop. // The meaning of the first stop's arrival time is unclear, and same for the last stop's departure time (except // in the case of interlining). // it's fine to just check departure time, as the above pass ensures that all stop times have either both // arrival and departure times, or neither if (stopTimes[0].departure_time == Entity.INT_MISSING || stopTimes[stopTimes.length - 1].departure_time == Entity.INT_MISSING) { throw new FirstAndLastStopsDoNotHaveTimes(); } // second pass: fill complete stop times int startOfInterpolatedBlock = -1; for (int stopTime = 0; stopTime < stopTimes.length; stopTime++) { if (stopTimes[stopTime].departure_time == Entity.INT_MISSING && startOfInterpolatedBlock == -1) { startOfInterpolatedBlock = stopTime; } else if (stopTimes[stopTime].departure_time != Entity.INT_MISSING && startOfInterpolatedBlock != -1) { // we have found the end of the interpolated section int nInterpolatedStops = stopTime - startOfInterpolatedBlock; double totalLengthOfInterpolatedSection = 0; double[] lengthOfInterpolatedSections = new double[nInterpolatedStops]; GeodeticCalculator calc = new GeodeticCalculator(); for (int stopTimeToInterpolate = startOfInterpolatedBlock, i = 0; stopTimeToInterpolate < stopTime; stopTimeToInterpolate++, i++) { Stop start = stops.get(stopTimes[stopTimeToInterpolate - 1].stop_id); Stop end = stops.get(stopTimes[stopTimeToInterpolate].stop_id); calc.setStartingGeographicPoint(start.stop_lon, start.stop_lat); calc.setDestinationGeographicPoint(end.stop_lon, end.stop_lat); double segLen = calc.getOrthodromicDistance(); totalLengthOfInterpolatedSection += segLen; lengthOfInterpolatedSections[i] = segLen; } // add the segment post-last-interpolated-stop Stop start = stops.get(stopTimes[stopTime - 1].stop_id); Stop end = stops.get(stopTimes[stopTime].stop_id); calc.setStartingGeographicPoint(start.stop_lon, start.stop_lat); calc.setDestinationGeographicPoint(end.stop_lon, end.stop_lat); totalLengthOfInterpolatedSection += calc.getOrthodromicDistance(); int departureBeforeInterpolation = stopTimes[startOfInterpolatedBlock - 1].departure_time; int arrivalAfterInterpolation = stopTimes[stopTime].arrival_time; int totalTime = arrivalAfterInterpolation - departureBeforeInterpolation; double lengthSoFar = 0; for (int stopTimeToInterpolate = startOfInterpolatedBlock, i = 0; stopTimeToInterpolate < stopTime; stopTimeToInterpolate++, i++) { lengthSoFar += lengthOfInterpolatedSections[i]; int time = (int) (departureBeforeInterpolation + totalTime * (lengthSoFar / totalLengthOfInterpolatedSection)); stopTimes[stopTimeToInterpolate].arrival_time = stopTimes[stopTimeToInterpolate].departure_time = time; } // we're done with this block startOfInterpolatedBlock = -1; } } return Arrays.asList(stopTimes); } public Collection<Frequency> getFrequencies (String trip_id) { // IntelliJ tells me all these casts are unnecessary, and that's also my feeling, but the code won't compile // without them return (List<Frequency>) frequencies.subSet(new Fun.Tuple2(trip_id, null), new Fun.Tuple2(trip_id, Fun.HI)).stream() .map(t2 -> ((Tuple2<String, Frequency>) t2).b) .collect(Collectors.toList()); } public List<String> getOrderedStopListForTrip (String trip_id) { Iterable<StopTime> orderedStopTimes = getOrderedStopTimesForTrip(trip_id); List<String> stops = Lists.newArrayList(); // In-order traversal of StopTimes within this trip. The 2-tuple keys determine ordering. for (StopTime stopTime : orderedStopTimes) { stops.add(stopTime.stop_id); } return stops; } public LineString getStraightLineForStops(String trip_id) { CoordinateList coordinates = new CoordinateList(); LineString ls = null; Trip trip = trips.get(trip_id); Iterable<StopTime> stopTimes; stopTimes = getOrderedStopTimesForTrip(trip.trip_id); if (Iterables.size(stopTimes) > 1) { for (StopTime stopTime : stopTimes) { Stop stop = stops.get(stopTime.stop_id); Double lat = stop.stop_lat; Double lon = stop.stop_lon; coordinates.add(new Coordinate(lon, lat)); } ls = gf.createLineString(coordinates.toCoordinateArray()); } // set ls equal to null if there is only one stopTime to avoid an exception when creating linestring else{ ls = null; } return ls; } /** * Returns a trip geometry object (LineString) for a given trip id. * If the trip has a shape reference, this will be used for the geometry. * Otherwise, the ordered stoptimes will be used. * * @param trip_id trip id of desired trip geometry * @return the LineString representing the trip geometry. * @see LineString */ public LineString getTripGeometry(String trip_id){ CoordinateList coordinates = new CoordinateList(); LineString ls = null; Trip trip = trips.get(trip_id); // If trip has shape_id, use it to generate geometry. if (trip.shape_id != null) { Shape shape = getShape(trip.shape_id); if (shape != null) ls = shape.geometry; } // Use the ordered stoptimes. if (ls == null) { ls = getStraightLineForStops(trip_id); } return ls; } /** Get the length of a trip in meters. */ public double getTripDistance (String trip_id, boolean straightLine) { return straightLine ? GeoUtils.getDistance(this.getStraightLineForStops(trip_id)) : GeoUtils.getDistance(this.getTripGeometry(trip_id)); } /** Get trip speed (using trip shape if available) in meters per second. */ public double getTripSpeed (String trip_id) { return getTripSpeed(trip_id, false); } /** Get trip speed in meters per second. */ public double getTripSpeed (String trip_id, boolean straightLine) { StopTime firstStopTime = this.stop_times.ceilingEntry(Fun.t2(trip_id, null)).getValue(); StopTime lastStopTime = this.stop_times.floorEntry(Fun.t2(trip_id, Fun.HI)).getValue(); // ensure that stopTime returned matches trip id (i.e., that the trip has stoptimes) if (!firstStopTime.trip_id.equals(trip_id) || !lastStopTime.trip_id.equals(trip_id)) { return Double.NaN; } double distance = getTripDistance(trip_id, straightLine); // trip time (in seconds) int time = lastStopTime.arrival_time - firstStopTime.departure_time; return distance / time; // meters per second } public Polygon getConvexHull() { if (this.convexHull == null) { synchronized (this) { List<Coordinate> coordinates = this.stops.values().stream().map( stop -> new Coordinate(stop.stop_lon, stop.stop_lat) ).collect(Collectors.toList()); Coordinate[] coords = coordinates.toArray(new Coordinate[coordinates.size()]); ConvexHull convexHull = new ConvexHull(coords, gf); this.convexHull = (Polygon) convexHull.getConvexHull(); } } return this.convexHull; } /** * Cloning can be useful when you want to make only a few modifications to an existing feed. * Keep in mind that this is a shallow copy, so you'll have to create new maps in the clone for tables you want * to modify. */ @Override public GTFSFeed clone() { try { return (GTFSFeed) super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } protected void finalize() throws IOException { close(); } public void close () { db.close(); } /** Thrown when we cannot interpolate stop times because the first or last stops do not have times */ public class FirstAndLastStopsDoNotHaveTimes extends Exception { /** do nothing */ } /** Create a GTFS feed in a temp file */ public GTFSFeed () { // calls to this must be first operation in constructor - why, Java? this(DBMaker.newTempFileDB() .transactionDisable() .mmapFileEnable() .asyncWriteEnable() .deleteFilesAfterClose() .compressionEnable() // .cacheSize(1024 * 1024) this bloats memory consumption .make()); // TODO db.close(); } /** Create a GTFS feed connected to a particular DB, which will be created if it does not exist. */ public GTFSFeed (String dbFile) throws IOException, ExecutionException { this(constructDB(dbFile)); // TODO db.close(); } private static DB constructDB(String dbFile) { DB db; try{ DBMaker dbMaker = DBMaker.newFileDB(new File(dbFile)); db = dbMaker .transactionDisable() .mmapFileEnable() .asyncWriteEnable() .compressionEnable() // .cacheSize(1024 * 1024) this bloats memory consumption .make(); return db; } catch (ExecutionError | IOError | Exception e) { LOG.error("Could not construct db from file.", e); return null; } } private GTFSFeed (DB db) { this.db = db; agency = db.getTreeMap("agency"); feedInfo = db.getTreeMap("feed_info"); routes = db.getTreeMap("routes"); trips = db.getTreeMap("trips"); stop_times = db.getTreeMap("stop_times"); frequencies = db.getTreeSet("frequencies"); transfers = db.getTreeMap("transfers"); stops = db.getTreeMap("stops"); fares = db.getTreeMap("fares"); services = db.getTreeMap("services"); shape_points = db.getTreeMap("shape_points"); feedId = db.getAtomicString("feed_id").get(); checksum = db.getAtomicLong("checksum").get(); // use Java serialization because MapDB serialization is very slow with JTS as they have a lot of references. // nothing else contains JTS objects patterns = db.createTreeMap("patterns") .valueSerializer(Serializer.JAVA) .makeOrGet(); tripPatternMap = db.getTreeMap("patternForTrip"); errors = db.getTreeSet("errors"); } }
package com.crushpaper; /** * This is the full list of strings that can be returned by the HTTP server. * This serves to isolate all messages into one place where they can be reviewed * for consistency. This should also make it easier to internationalize the * application if desired. buttons, labels and links should not have periods. * sentences and errors should be full sentences with periods. fragments should * be portions of sentences and should generally not have periods. */ public class ServletText { public String buttonRestore() { return "Restore"; } public String buttonSave() { return "Save"; } public String errorEntryCouldNotBeFound() { return "Sorry, the specified note could not be found."; } public String errorNotebookCouldNotBeFound() { return "Sorry, the specified notebook could not be found."; } public String errorNotebooksCouldNotBeFound() { return "Sorry, your notebooks could not be found."; } public String errorMovedCouldNotBeFound() { return "Sorry, the specified note to move could not be found."; } public String errorNoSourceFound() { return "Sorry, no such source was found."; } public String errorParentCouldNotBeFound() { return "Sorry, the specified parent could not be found."; } public String errorChildCouldNotBeFound() { return "Sorry, the specified subnote could not be found."; } public String errorCouldNotParseQuery() { return "Sorry, your query could not be parsed."; } public String errorInternalDatabase() { return "Sorry, there was an internal database error."; } public String errorHasNoParent() { return "Sorry, this note has no parent."; } public String errorParentIdInvalidFormat() { return "Sorry, the specified parent ID was in an invalid format."; } public String errorMovedIdInvalidFormat() { return "Sorry, the ID of the note to move was in an invalid format."; } public String errorChildIdInvalidFormat() { return "Sorry, the specified subnote ID was in an invalid format."; } public String errorIdIsInvalidFormat() { return "Sorry, the specified ID was in an invalid format."; } public String errorIdsAreInvalidFormat() { return "Sorry, the specified IDs are in an invalid format."; } public String errorInvalidOperation() { return "Sorry, the operation that was specified was not understood."; } public String errorInvalidPlacementValue() { return "Sorry, the placement that was specified was not understood."; } public String errorInvalidTimestamp() { return "Sorry, the specified timestamp was in an invalid format."; } public String errorJson() { return "Sorry, the JSON could not be parsed."; } public String errorMayNotSeeSource() { return "Sorry, you are not entitled to view this source."; } public String errorMayNotSeeEntry() { return "Sorry, you are not entitled to view this note."; } public String errorMayNotSeeNotebook() { return "Sorry, you are not entitled to view this notebook."; } public String errorMayNotSeeNotebooks() { return "Sorry, you are not entitled to view these notebooks."; } public String errorMissingOperation() { return "Sorry, no operation was specified."; } public String errorNoFileUploaded() { return "Sorry, no file was uploaded so it cannot be restored."; } public String errorNoteNotCreated() { return "Sorry, your note could not be created."; } public String errorPageNotFound() { return "Sorry, the page you were looking for doesn't exist."; } public String errorRestoreFailed() { return "Sorry, the restore failed."; } public String fragmentBlankTitle() { return "Blank title"; } public String fragmentBlankNote() { return "Blank note"; } public String fragmentBlankQuotation() { return "Blank quotation"; } public String sentenceCmdForDbRestore() { return "To restore the backup first shutdown the server and then run these commands:"; } public String fragmentShowingContentsOf() { return "Showing contents of"; } public String labelApplicationName() { return "CrushPaper"; } public String pageTitleQuotation() { return "Quotation"; } public String pageTitleNotebook() { return "Notebook"; } public String pageTitleAllNotes() { return "All Notes"; } public String pageTitleOfflineBackupDb() { return "Offline Backup"; } public String pageTitleOnlineBackupDb() { return "Online Backup"; } public String pageTitleNewNotebook() { return "New Notebook"; } public String pageTitleSource() { return "Source"; } public String pageTitleSources() { return "Sources"; } public String pageTitleUserBackup() { return "Backup"; } public String pageTitleQuotations() { return "Quotations"; } public String pageTitleUserRestore() { return "Restore"; } public String pageTitleShowDbBackups() { return "Backups"; } public String pageTitleNotebooks() { return "Notebooks"; } public String pageTitleEditNote() { return "Edit Note"; } public String pageTitleEditQuotation() { return "Edit Quotation"; } public String pageTitleCheckDbForErrors() { return "Check Errors"; } public String sentenceRestored() { return "Your backup file has been successfully restored."; } public String sentenceNoSourcesExist() { return "No sources have been created yet.<br><br>A source is created when you create a quotation from a web page.<br><br>" + sentenceChromeExtension(); } public String sentenceNoQuotationsExist() { return "No quotations have been created yet.<br><br>" + sentenceChromeExtension(); } private String sentenceChromeExtension() { return "If you have the CrushPaper Chrome extension installed then create a quotation:<br><br>" + "1. Go to another web site.<br>" + "2. Select any text on that web site.<br>" + "3. Right click the text.<br>" + "4. Click \"Save selected text to CrushPaper\".<br>" + "5. Come back to this page and click the refresh icon. " + "<div title=\"Click to refresh this part of the page.\" class=\"refreshIcon\" onclick=\"refreshPane(event); return false;\"></div>"; } public String sentenceNoQuotationsForThisSourceExist() { return "No quotations have been created for this source yet."; } public String sentenceNoNotesExist() { return "No notebooks have been created yet.<br><br>You can click on \"New Notebook\" on the top of the left menu to create one."; } public String sentenceNothingHere() { return "There is nothing here. This page assists in debugging."; } public String sentencePressHForHelp() { return "Press the \"h\" key for <u>h</u>elp."; } public String sentenceTheDatabaseHasNoErrors() { return "The database has no errors."; } public String sentenceTheDatabaseHasErrors() { return "The database has errors."; } public String sentenceThereWereNoMatches() { return "There were no matches."; } public String textNoDbBackupsHaveBeenCreated() { return "No backups have been created."; } public String labelApplicationNameTooltip() { return "Go to the CrushPaper welcome page."; } public String labelCrushPaperComTooltip() { return "Go to crushpaper.com."; } public String labelTwitterTooltip() { return "Go to CrushPaper's Twitter account."; } public String labelGithubTooltip() { return "Go to CrushPaper's GitHub repo."; } public String labelGoogleGroupTooltip() { return "Go to CrushPaper's Google Group."; } public String pageTitleCreateNoteTooltip() { return "Create a new notebook."; } public String pageTitleNotebooksTooltip() { return "View all your notebooks."; } public String pageTitleAllNotesTooltip() { return "View all your notes."; } public String pageTitleQuotationsTooltip() { return "View all your quotations."; } public String pageTitleSourcesTooltip() { return "View all your sources."; } public String pageTitleUserBackupTooltip() { return "Backup all your notebooks as a JSON file."; } public String pageTitleUserRestoreTooltip() { return "Restore notebooks from a JSON file."; } public String pageTitleOfflineBackupDbTooltip() { return "Create an offline backup of the database on the server. Changes made during this process will corrupt the backup."; } public String pageTitleOnlineBackupDbTooltip() { return "Create an online backup of the database on the server. Changes made during this process will NOT corrupt the backup."; } public String pageTitleCheckDbForErrorsTooltip() { return "Check the database for integrity errors."; } public String pageTitleShowDbBackupsTooltip() { return "Show all available backup copies."; } public String printLinkTooltip() { return "View a more printable version of the current page."; } public String clickToEditAlt() { return "Click to edit"; } public String clickToEditTheQuotationTooltip() { return "Click to edit the quotation."; } public String clickToEditTheNoteTooltip() { return "Click to edit the note."; } public String clickToEditTheSourceTooltip() { return "Click to edit the source."; } public String showExternalSourceLinkTooltip() { return "View the external web page for the source."; } public String dragEntryAlt() { return "Drag"; } public String dragEntryTooltip() { return "Drag this note into or next to another note by dragging this image."; } public String quotationInListTooltip() { return "This is the text of the quotation. Click to edit."; } public String noteInListTooltip(String type) { return "This is the text of the " + type + (type.equals("notebook") ? " title" : "") + ". Click to edit."; } public String modTimeInListTooltip(String type) { return "This is the time the " + type + " was last modified. Click to edit."; } public String showDomainTooltip() { return "This is the domain of the source."; } public String errorPageNotAllowed() { return "Sorry, you are not allowed to view this page."; } public String notAllowedTitle() { return "Not Viewable"; } public String pageTitleClearDbTooltip() { return "Clear the entire database."; } public String pageTitleClearDb() { return "Clear DB"; } public String sentenceCleared() { return "The database was cleared of all data."; } public String welcome() { return "Welcome"; } public String fragmentFrom() { return "From"; } public String moreFromThisSourceTooltip() { return "Show more quotations from this source."; } public String buttonMoreQuotations() { return "More quotations from this source"; } public String fragmentLastModified() { return "Last modified"; } public String offlineBackupDbAreYouSure() { return "Backing up the database is time consuming.<br>There is almost never a reason to do an offline backup instead of an online backup."; } public String onlineBackupDbAreYouSure() { return "Backing up the database is time consuming."; } public String clearAreYouSure() { return "Clearing removes all data from the database, not just your own."; } public String checkDbForErrorsAreYouSure() { return "Checking the database for errors is time consuming.<br><br>It may lock the database for a long time."; } public String userBackupAreYouSure() { return "This creates a JSON text file that is a backup of all of your notebooks, sources and quotations.<br><br>You can save it to your computer and restore it later to CrushPaper.<br><br>This can be time consuming.<br><br>It may lock the database for a long time."; } public String sentenceOfflineDbBackupWasSuccessful() { return "The offline backup was successful."; } public String sentenceOfflineDbBackupWasNotSuccessful() { return "<span class=\"errorMessage\">The offline backup was not successful.</span>"; } public String sentenceOnlineDbBackupWasSuccessful(int numRowsExtracted) { return "The online backup was successful.<br><br>" + numRowsExtracted + " rows were backed up."; } public String sentenceOnlineDbBackupWasNotSuccessful() { return "<span class=\"errorMessage\">The online backup was not successful.</span>"; } public String linkShowRestoreDbBackupCmdTooltip() { return "Click to show the command that will restore this backup."; } public String errorNoNameSpecifiedForRestoration() { return "The backup that you would like to restore was not specified."; } public String pageTitleRestoreBackupCommandDb() { return "Command to Restore a Backup"; } public String sentenceToRestoreDbCommand() { return "Click one of the links below to view the command that will restore that backup."; } public String pageTitleClearedDb() { return "Entire Database Cleared"; } public String pageTitleRestored() { return "Notes Restored"; } public String linkNext() { return "Next Page"; } public String linkPrevious() { return "Previous Page"; } public String sentenceNoMoreResults() { return "Sorry, there were no more results."; } public String fragmentCreated() { return "Created"; } public String linkSignIn() { return "Sign In"; } public String linkAccount() { return "Account"; } public String linkCreateAccount() { return "Create Account"; } public String tooltipSignIn() { return "Click here to sign into your account."; } public String tooltipCreateAccount() { return "Click here to create an account."; } public String tooltipEditAccount() { return "Click here to edit your account details."; } public String linkSignOut() { return "Sign Out"; } public String tooltipSignOut() { return "Click here to sign out of your account."; } public String errorUsernameMustNotBeBlank() { return "Sorry, the username must not be blank."; } public String errorPasswordMustNotBeBlank() { return "Sorry, the password must not be blank."; } public String errorPasswordsMustMatch() { return "Sorry, the passwords must match."; } public String errorUserNameIsNotValid() { return "Sorry, the username is not valid. It must be between 3 and 20 letters long and only contain the characters a-z and 0-9."; } public String errorPasswordIsNotValid() { return "Sorry, the password is not valid. It must be between 8 and 20 letters long."; } public String errorUserNameIsAlreadyTaken() { return "Sorry, the username is already taken."; } public String errorCouldNotCreateAccount() { return "Sorry, the account could not be created."; } public String errorPasswordIsIncorrect() { return "Sorry, the password is incorrect."; } public String errorRequiresSignIn(boolean allowSaveIfNotSignedIn) { String result = "Sorry, you must be signed in for this."; if (allowSaveIfNotSignedIn) result += "<br><br>However, if you create a new notebook then an account will automatically be created for you.<br><br>" + "You can change your username and password later."; return result; } public String pageTitleAccounts() { return "Accounts"; } public String pageTitleAccountsTooltip() { return "View all accounts."; } public String clickToEditTheAccountTooltip() { return "Click to edit the account."; } public String errorNoAccountFound() { return "Sorry, the specified account could not be found."; } public String pageTitleAccount() { return "Account"; } public String errorEmailIsNotValid() { return "Sorry, the email address is not valid. Remember, it is optional."; } public String sentenceNoAccountsExist() { return "No accounts have been created yet."; } public String tooltipSearch() { return "Go to 'Help / Search' for information on query syntax."; } public String errorQueryIsRequired() { return "Sorry, you must specify a search query."; } public String sentenceChooseAUserName() { return "Choose a username (at least 3 characters from a-z and 0-9)"; } public String sentenceNewPassword() { return "Choose a new password (at least 8 characters)"; } public String sentenceUserMayBeContacted() { return "The user may be contacted with information about this web site."; } public String sentenceIMayBeContacted() { return "I may be contacted with information about this web site."; } public String sentenceUserIsAnAdmin() { return "The user is an admin."; } public String sentenceIsAccountClosed() { return "The account is closed."; } public String sentenceVerifyNewPassword() { return "Verify the new password"; } public String sentenceEmailOptional() { return "Email address (optional)"; } public String errorAccountIsClosed() { return "Sorry, your account is closed."; } public String errorCurrentPasswordIsNotValid() { return "Sorry, the current password is not valid. It must be between 8 and 20 letters long."; } public String errorCurrentPasswordIsIncorrect() { return "Sorry, the current password is incorrect."; } public String pageTitleChangeAccount() { return "Change Account Details"; } public String sentenceChangesWereSaved() { return "Your changes were saved."; } public String errorNoChangesToSave() { return "Sorry, there were no changes to save."; } public String errorChangesWereNotSaved() { return "Your changes were not saved because of this."; } public String errorSelfSignUpNotAllowed() { return "Sorry, creating your own account is not allowed on this server."; } public String errorOnlyAnAdminCanChangeIsAdmin() { return "Sorry, only an admin can change whether a user is an admin."; } public String errorSingleUserMustStayAnAdmin() { return "Sorry, single users must be admins."; } public String sentenceAllowSaveIfNotSignedIn() { return "Creating this notebook will automatically create an account for you and sign you in.<br><br>You can change your username and password later.<br><br>"; } public String sentenceYouHaveBeenSignedOut() { return "You have been signed out."; } public String sentenceYouHaveNotBeenSignedOut() { return "Sorry, it seems like you tried to sign out but it didn't work."; } public String pageTitleSignedOut() { return "Signed Out"; } public String errorWrongCsrft() { return "Sorry, the wrong csrft was supplied."; } public String pageTitleWelcome() { return "Welcome to CrushPaper"; } public String pageTitleWelcomeExtra() { return " where you can create notes and save quotations from sources"; } public String sentenceReuseIds() { return "Reuse note IDs if possible."; } public String shutdownAreYouSure() { return "This kills the CrushPaper server process. <br><br>It will not handle HTTP requests until restarted from the command line."; } public String sentenceShuttingdown() { return "The CrushPaper server process is shutting down. <br><br>It will not handle HTTP requests until restarted from the command line."; } public String pageTitleShutdown() { return "Shutdown"; } public String pageTitleShutdownTooltip() { return "This kills the process. It will not handle HTTP requests until restarted from the command line."; } public String pageTitleHelp() { return "Help"; } public String pageTitleHelpTooltip() { return "View the list of help pages for this site."; } public String pageTitleUiHelp() { return "UI Help"; } public String pageTitleUiHelpTooltip() { return "View the list keyboard shortcuts and mouse actions for this page."; } public String callToAction(boolean allowSaveIfNotSignedIn) { if (allowSaveIfNotSignedIn) return "<br><br><div style=\"text-align: center\"><div style=\"display: inline-block;\">" + "<b>Try CrushPaper for free without creating an account!</b><br><br>" + "<form action=\"/newNotebook/\" method=\"GET\">" + "<button onclick=\"showPopupForCreateNotebook(); return false;\" id=\"save\" class=\"specialbutton\" style=\"float: none;\" title=\"Create a notebook where you can put notes and quotations\">" + "Create a New Notebook" + "</button></form></div></div>"; return ""; } public String viewYourNotebooks() { return "<br><br><div style=\"text-align: center\"><div style=\"display: inline-block;\">" + "<form action=\"/notebooks/\" method=\"GET\">" + "<button onclick=\"newPaneForForm(event, '" + pageTitleNotebooks() + "', 'notebooks'); return false;\" id=\"save\" class=\"specialbutton\" style=\"float: none;\" title=\"View all of the notebooks you have created\">" + "Go to your notebooks" + "</button></form></div></div>"; } public String errorNoteIsInvalid() { return "Sorry, the note is too long."; } public String errorQuotationIsInvalid() { return "Sorry, the quotation is too long."; } public String errorUrlIsInvalid() { return "Sorry, the web address is too long."; } public String errorTitleIsInvalid() { return "Sorry, the title is too long."; } public String pageTitleUsersNotebooksTooltip() { return "View all the user's notebooks."; } public String pageTitleUsersAllNotesTooltip() { return "View all the user's notes."; } public String pageTitleUsersQuotationsTooltip() { return "View all the user's quotations."; } public String pageTitleUsersSourcesTooltip() { return "View all the user's sources."; } public String pageTitleUsersSearchTooltip() { return "Search as the user."; } public String sentenceSeeWhatTheUserSees() { return "See what the user sees:"; } public String errorParentMustBeMovedBeforeChild() { return "Sorry, parents must be moved before subnotes are moved. This is a bug in the user interface."; } public String errorTargetIdInvalidFormat() { return "Sorry, the specified target ID was in an invalid format."; } public String errorTargetNoteCouldNotBeFound() { return "Sorry, the target note could not be found."; } public String errorTargetParentCouldNotBeFound() { return "Sorry, the target parent could not be found."; } public String errorDuplicateEntry() { return "Sorry, there was a duplicate note in the list. This is a bug in the user interface."; } public String errorTargetAndObjectCanNotBeTheSame() { return "Sorry, the target and object cannot be the same. This is a bug in the user interface."; } public String errorLevelsIsInvalid() { return "Sorry, the levels parameter is invalid. This is a bug in the user interface."; } public String errorMayNotSeeList() { return "Sorry, you are not entitled to view this list."; } public String pageTitleAdvancedHelp() { return "Advanced Help"; } public String introTextShowNotebook(boolean forTouch) { String result = "&bull; This is a notebook. It is a hierarchy of your notes.<br>&bull; "; if(forTouch) { result += "Press a note to edit it."; } else { result += "Mouse over, right click or press h to see all of the available commands."; } return result; } public String introTextShowSources(boolean forTouch) { return "&bull; This is the list of all the sources from which you have saved quotations.<br>" + sentenceWhatIsAQuotation() + sentenceQuotationClickDesc(forTouch, false); } private String sentenceWhatIsAQuotation() { return "&bull; A quotation is a snippet of text from another web site that you selected and saved to CrushPaper."; } public String introTextShowNotebooks(boolean forTouch) { return "&bull; This is the hierarchy of all the notebooks you have created.<br>&bull; Each notebook contains a hierarchy of notes and quotations.<br>" + sentenceWhatIsAQuotation() + "<br>&bull; " + clickOrTouchCapFirst(forTouch) + " a notebook to view or " + clickOrTouch(forTouch) + " the pencil icon above to edit this hierarchy."; } public String introTextSearchQuotations(boolean forTouch) { return "&bull; You have just searched the quotations you have saved.<br>" + sentenceWhatIsAQuotation() + sentenceQuotationClickDesc(forTouch, false) + sentenceNotebookIconClickDesc(forTouch); } public String introTextSearchNotes(boolean forTouch) { return "You have just searched all of your notes and your quotations that have notes.<br>" + sentenceWhatIsAQuotation() + "<br>" + clickOrTouchCapFirst(forTouch) + " a note to view or edit it." + sentenceNotebookIconClickDesc(forTouch); } public String introTextSearchNotebooks(boolean forTouch) { return "&bull; You have just searched the titles of all your notebooks.<br>" + clickOrTouchCapFirst(forTouch) + " the book icon to view a notebook."; } public String introTextSearchSources(boolean forTouch) { return "&bull; You have just searched the titles and web addresses of all the sources from which you have saved quotations.<br>" + sentenceWhatIsAQuotation() + sentenceQuotationClickDesc(forTouch, false); } private String clickOrTouch(boolean forTouch) { return forTouch ? "touch" : "click"; } private String clickOrTouchCapFirst(boolean forTouch) { return forTouch ? "Touch" : "Click"; } private String sentenceQuotationClickDesc(boolean forTouch, boolean forShowSource) { String result = "<br>&bull; Hold down the quotation's drag icon to move it into one of your notebooks."; if (forShowSource) { return result; } result += "<br>&bull; "; if (forTouch) { result += "Press "; } else { result += "Click "; } result += "\"More quotations from this source\" to view them."; return result; } private String sentenceNotebookIconClickDesc(boolean forTouch) { return "<br>&bull; " + clickOrTouchCapFirst(forTouch) + " the book icon to view it in the context of its notebook if it is in one."; } public String introTextSearchUsers() { return "&bull; You have just searched the usernames of all accounts on this server."; } public String introTextShowQuotations(boolean forTouch) { return "&bull; This is the list of all the quotations you have saved.<br>" + sentenceWhatIsAQuotation() + sentenceQuotationClickDesc(forTouch, false); } public String introTextShowSource(boolean forTouch) { return "&bull; This is a source from which you have saved quotations.<br>&bull; " + clickOrTouchCapFirst(forTouch) + " the title of the source to go that web site." + sentenceQuotationClickDesc(forTouch, true); } public String introTextSearchAccounts() { return "&bull; You have just searched the usernames of all the accounts on this server."; } public String introTextShowAccounts(boolean forTouch) { return "&bull; This is the list of all the accounts on this server.<br>&bull; " + clickOrTouchCapFirst(forTouch) + " to view or edit.<br>"; } public String introTextShowNotes() { return "&bull; This is the list of all the notes you have you have created that do not contain quotations.<br>" + sentenceWhatIsAQuotation(); } public String labelAnyoneCanReadThis() { return "Anyone can read this notebook"; } public String labelYourNotebookTitle() { return "Your notebook title"; } public String buttonChangePassword() { return "Change Password"; } public String buttonChangeAccountDetails() { return "Change Account Details"; } public String prefix(boolean currentIsEditedUser) { return (currentIsEditedUser ? "You " : "The user "); } public String prefixWithIsOrAre(boolean currentIsEditedUser) { return (currentIsEditedUser ? "You are " : "The user is "); } public String prefixPossesive(boolean currentIsEditedUser) { return (currentIsEditedUser ? "Your " : "The user's "); } public String sentenceIsAnAdmin(boolean currentIsEditedUser) { return prefixWithIsOrAre(currentIsEditedUser) + " an admin."; } public String sentenceAccountIsClosed(boolean currentIsEditedUser) { return prefixPossesive(currentIsEditedUser) + "account is closed."; } public String sentenceMayBeContacted(boolean currentIsEditedUser, boolean mayBeContacted) { return prefix(currentIsEditedUser) + "may " + (mayBeContacted ? "" : "not ") + "be contacted with information about this web site."; } public String sentenceEmailIs(boolean currentIsEditedUser, String email) { if (email == null || email.isEmpty()) return prefixPossesive(currentIsEditedUser) + "email address is not set."; return prefixPossesive(currentIsEditedUser) + "email address is " + email + "."; } public String sentenceUsernameIs(boolean currentIsEditedUser, String username) { return prefixPossesive(currentIsEditedUser) + "user name is " + username + "."; } public String pageTitleViewAccount() { return "Account Details"; } public String pageTitleChangePassword() { return "Change Password"; } public String sentenceCurrentPassword(boolean currentIsEditedUser) { return prefixPossesive(currentIsEditedUser) + "current password"; } public String pageTitleCloseAccount() { return "Close Account"; } public String sentenceSureYouWantToCloseAccount( boolean currentIsEditedUser, String username) { return "Are you sure you want to close " + (currentIsEditedUser ? "your" : username + "'s") + " account?"; } public String buttonCloseAccount() { return "Close Account"; } public String sentenceEnterNewAccountDetailsHere( boolean currentIsEditedUser, String username) { return "Enter " + (currentIsEditedUser ? "your" : username + "'s") + " new account details here:"; } public String sentenceEnterNewPasswordHereTwice( boolean currentIsEditedUser, String username) { return "Enter " + (currentIsEditedUser ? "your" : username + "'s") + " new password here twice:"; } public String sentenceEnterYourCurrentPasswordHere() { return "Enter your current password here:"; } public String errorUsernameMayNotBeChanged() { return "Username may not be changed"; } public String sentencePleaseChangeNameFromGenerated( boolean currentIsEditedUser, String username) { return "Please change " + (currentIsEditedUser ? "your" : username + "'s") + " user name:"; } public String errorFirstPasswordMustBeSet(boolean currentIsEditedUser, String username) { return "The first password field must contain " + (currentIsEditedUser ? "your" : username + "'s") + " new password"; } public String errorSecondPasswordMustBeSet(boolean currentIsEditedUser, String username) { return "The second password field must also contain " + (currentIsEditedUser ? "your" : username + "'s") + " new password"; } public String errorNewPasswordIsTheSameAsTheCurrent() { return "The new password is the same as the current password."; } public String plusTooltip() { return "Click to show one more level."; } public String minusTooltip() { return "Click to show one less level."; } public String introTextRestore() { return "You can restore backups of notes, quotations and sources by uploading a JSON file to the server using this page.<br><br>" + "Restoring a backup does not delete any notes, quotations and sources that you currently have.<br><br>" + "If you select \"Reuse note IDs if possible\" then the CrushPaper server will try to recreate your notes, quotations and sources with the same IDs as in the file. This is useful if you want to be able to retain the same URLs. If another item already has the ID then the CrushPaper server will assign a new ID.<br><br>" + "If you select \"The file is in MS Word List Format\" then the CrushPaper server will treat the file as if it contains a single notebook in this format:" + "<pre>" + "*\tNote at level 1<br>" + "O\tNote at level 2<br>" + "?\tNote at level x<br>" + "</pre>" + "CrushPaper assumes that if the bullet character that appears at the beginning of the line has not been seen before then the line should be at a level below any other levels."; } public String tooltipOptions() { return "Change the options for this site."; } public String linkOptions() { return "Options"; } public String pageTitleSearchTooltip() { return "Search your notes, quotations and sources."; } public String pageTitleSearch() { return "Search"; } public String placeholderSearch() { return ""; } public String buttonSearch() { return "Search"; } public String labelSearchSources() { return "Sources"; } public String labelSearchQuotations() { return "Quotations"; } public String labelSearchNotes() { return "Notes"; } public String errorSearchDataSetIsRequired() { return "Sorry, you must specify a data set to search."; } public String errorJavaScriptNeeded() { return "Sorry, JavaScript is required for most features of this site."; } public String pageTitleGetNextPage() { return "Get Next Page"; } public String pageTitleGetPreviousPage() { return "Get Previous Page"; } public String errorInvalidUrl() { return "Sorry, the web address was invalid."; } public String labelSearchAccounts() { return "Accounts"; } public String tooltipRefreshPane() { return "Click to refresh this part of the page."; } public String tooltipClosePane() { return "Click to close this part of the page."; } public String pageTitleCloseAllTooltip() { return "Close all open subpages."; } public String pageTitleCloseAll() { return "Close All"; } public String buttonNewNote() { return "New Note"; } public String buttonNewNotebook() { return "New Notebook"; } public String tooltipNewNote() { return "Click to add a new note to this notebook."; } public String tooltipNewNotebook() { return "Click to create a new notebook."; } public String pageTitleNote() { return "Note"; } public String errorEntryCanNotBeDeleted() { return "Sorry, this the entry cannot be deleted this way. This is a bug in the user interface."; } public String fragmentVisitExternalSource() { return "View the external web page at"; } public String labelSearchNotebooks() { return "Notebooks"; } public String linkMenu() { return "Menu"; } public String tooltipMenu() { return "Click to show or hide the menu."; } public String errorNeedLongerQuery() { return "Sorry, please try a longer query."; } public String sentenceMsWordListFormat() { return "The file is in MS Word List Format."; } }
package com.filestack.model; import java.util.ArrayList; import java.util.Date; public class Policy { public static final String CALL_PICK = "pick"; public static final String CALL_READ = "read"; public static final String CALL_STAT = "stat"; public static final String CALL_WRITE = "write"; public static final String CALL_WRITE_URL = "writeUrl"; public static final String CALL_STORE = "store"; public static final String CALL_CONVERT = "convert"; public static final String CALL_REMOVE = "remove"; public static final String CALL_EXIF = "exif"; private Long expiry; private String[] call; private String handle; private String url; private Integer maxSize; private Integer minSize; private String path; private String container; private Policy() { } public static class Builder { private Long expiry; private ArrayList<String> calls; private String handle; private String url; private Integer maxSize; private Integer minSize; private String path; private String container; public Builder expiry(Long expiry) { this.expiry = expiry; return this; } public Builder addCall(String call) { if (calls == null) { calls = new ArrayList<>(); } calls.add(call); return this; } public Builder handle(String handle) { this.handle = handle; return this; } public Builder url(String url) { this.url = url; return this; } public Builder maxSize(Integer maxSize) { this.maxSize = maxSize; return this; } public Builder minSize(Integer minSize) { this.minSize = minSize; return this; } public Builder path(String path) { this.path = path; return this; } public Builder container(String container) { this.container = container; return this; } /** * Convenience method to create a policy with full access and one year expiry. */ public Builder giveFullAccess() { // Set expiry to one year from now Date date = new Date(); expiry = date.getTime() / 1000 + 60 * 60 * 24 * 365; // Add all calls calls = new ArrayList<>(); calls.add(CALL_PICK); calls.add(CALL_READ); calls.add(CALL_STAT); calls.add(CALL_WRITE); calls.add(CALL_WRITE_URL); calls.add(CALL_STORE); calls.add(CALL_CONVERT); calls.add(CALL_REMOVE); calls.add(CALL_EXIF); return this; } /** Construct and return the policy. */ public Policy build() { Policy policy = new Policy(); policy.expiry = expiry; if (calls != null) { policy.call = calls.toArray(new String[0]); } policy.handle = handle; policy.url = url; policy.maxSize = maxSize; policy.minSize = minSize; policy.path = path; policy.container = container; return policy; } } }
package com.kodedu.boot; import com.install4j.api.launcher.StartupNotification; import com.kodedu.config.ConfigurationService; import com.kodedu.config.EditorConfigBean; import com.kodedu.controller.ApplicationController; import com.kodedu.service.FileOpenListener; import com.kodedu.service.ThreadService; import com.kodedu.service.ui.TabService; import de.tototec.cmdoption.CmdlineParser; import de.tototec.cmdoption.CmdlineParserException; import javafx.application.Application; import javafx.application.Platform; import javafx.fxml.FXMLLoader; import javafx.geometry.Rectangle2D; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyCodeCombination; import javafx.scene.layout.AnchorPane; import javafx.scene.text.Font; import javafx.stage.Modality; import javafx.stage.Screen; import javafx.stage.Stage; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.context.ConfigurableApplicationContext; import java.io.File; import java.io.InputStream; import static javafx.scene.input.KeyCombination.SHORTCUT_DOWN; public class AppStarter extends Application { private static Logger logger = LoggerFactory.getLogger(AppStarter.class); private static ApplicationController controller; private static ConfigurableApplicationContext context; private EditorConfigBean editorConfigBean; private Stage stage; private ThreadService threadService; private ConfigurationService configurationService; @Override public void start(final Stage stage) { Thread.setDefaultUncaughtExceptionHandler((t, e) -> logger.error(e.getMessage(), e)); Font.loadFont(AppStarter.class.getResourceAsStream("/font/NotoSerif-Regular.ttf"), -1); // System.setProperty("nashorn.typeInfo.maxFiles", "5"); System.setProperty("jsse.enableSNIExtension", "false"); // System.setProperty("https.protocols", "SSLv3"); System.setProperty("sun.net.http.allowRestrictedHeaders", "true"); final CmdlineConfig config = new CmdlineConfig(); final CmdlineParser cp = new CmdlineParser(config); try { cp.parse(getParameters().getRaw().toArray(new String[0])); } catch (final CmdlineParserException e) { System.err.println("Invalid commandline given: " + e.getMessage()); System.exit(1); } if (config.help) { cp.usage(); System.exit(0); } new Thread(() -> { try { startApp(stage, config); } catch (final Throwable e) { logger.error("Problem occured while starting AsciidocFX", e); } }).start(); } private void startApp(final Stage stage, final CmdlineConfig config) throws Throwable { this.stage = stage; context = SpringApplication.run(SpringAppConfig.class); editorConfigBean = context.getBean(EditorConfigBean.class); controller = context.getBean(ApplicationController.class); threadService = context.getBean(ThreadService.class); configurationService = context.getBean(ConfigurationService.class); final FXMLLoader parentLoader = new FXMLLoader(); parentLoader.setControllerFactory(context::getBean); InputStream sceneStream = AppStarter.class.getResourceAsStream("/fxml/AsciidocFX_Scene.fxml"); Parent root = parentLoader.load(sceneStream); Scene scene = new Scene(root); stage.setTitle("AsciidocFX"); InputStream logoStream = AppStarter.class.getResourceAsStream("/logo.png"); stage.getIcons().add(new Image(logoStream)); threadService.runActionLater(stage::setScene, scene); controller.initializeApp(); stage.setOnShowing(e -> { controller.setStage(stage); controller.setScene(scene); controller.setHostServices(getHostServices()); configurationService.loadConfigurations(); controller.applyInitialConfigurations(); controller.checkStageInsideScreens(); }); stage.setOnShown(e -> { controller.bindConfigurations(); controller.showConfigLoaderOnNewInstall(); }); threadService.runActionLater(() -> { setMaximized(); if (controller.getTabPane().getTabs().isEmpty()) { controller.newDoc(); } stage.show(); }); IOUtils.closeQuietly(sceneStream); IOUtils.closeQuietly(logoStream); final FXMLLoader asciidocTableLoader = new FXMLLoader(); final FXMLLoader markdownTableLoader = new FXMLLoader(); asciidocTableLoader.setControllerFactory(context::getBean); markdownTableLoader.setControllerFactory(context::getBean); InputStream asciidocTableStream = AppStarter.class.getResourceAsStream("/fxml/AsciidocTablePopup.fxml"); AnchorPane asciidocTableAnchor = asciidocTableLoader.load(asciidocTableStream); InputStream markdownTableStream = AppStarter.class.getResourceAsStream("/fxml/MarkdownTablePopup.fxml"); AnchorPane markdownTableAnchor = markdownTableLoader.load(markdownTableStream); Stage asciidocTableStage = threadService.supply(Stage::new); threadService.runActionLater(asciidocTableStage::setScene, new Scene(asciidocTableAnchor)); asciidocTableStage.setTitle("Table Generator"); asciidocTableStage.initModality(Modality.WINDOW_MODAL); asciidocTableStage.initOwner(scene.getWindow()); asciidocTableStage.getIcons().add(new Image(logoStream)); Stage markdownTableStage = threadService.supply(Stage::new); threadService.runActionLater(markdownTableStage::setScene, new Scene(markdownTableAnchor)); markdownTableStage.setTitle("Table Generator"); markdownTableStage.initModality(Modality.WINDOW_MODAL); markdownTableStage.initOwner(scene.getWindow()); markdownTableStage.getIcons().add(new Image(logoStream)); IOUtils.closeQuietly(asciidocTableStream); IOUtils.closeQuietly(markdownTableStream); controller.setAsciidocTableAnchor(asciidocTableAnchor); controller.setMarkdownTableAnchor(markdownTableAnchor); controller.setAsciidocTableStage(asciidocTableStage); controller.setAsciidocTableScene(asciidocTableStage.getScene()); controller.setMarkdownTableStage(markdownTableStage); controller.setMarkdownTableScene(markdownTableStage.getScene()); controller.applyCurrentTheme(asciidocTableStage, markdownTableStage); controller.initializeSaveOnBlur(); scene.getAccelerators().put(new KeyCodeCombination(KeyCode.S, SHORTCUT_DOWN), controller::saveDoc); scene.getAccelerators().put(new KeyCodeCombination(KeyCode.M, SHORTCUT_DOWN), controller::adjustSplitPane); scene.getAccelerators().put(new KeyCodeCombination(KeyCode.N, SHORTCUT_DOWN), controller::newDoc); scene.getAccelerators().put(new KeyCodeCombination(KeyCode.T, SHORTCUT_DOWN), controller::newDoc); scene.getAccelerators().put(new KeyCodeCombination(KeyCode.O, SHORTCUT_DOWN), controller::openDoc); scene.getAccelerators().put(new KeyCodeCombination(KeyCode.W, SHORTCUT_DOWN), controller::saveAndCloseCurrentTab); final ThreadService threadService = context.getBean(ThreadService.class); controller.initializeTabWatchListener(); threadService.start(() -> { try { registerStartupListener(config); } catch (Exception e) { logger.error("Problem occured in startup listener", e); } }); scene.getWindow().setOnCloseRequest(controller::closeAllTabs); stage.widthProperty().addListener(controller::stageWidthChanged); stage.heightProperty().addListener(controller::stageWidthChanged); } private void setMaximized() { Rectangle2D bounds = Screen.getPrimary().getVisualBounds(); stage.setX(bounds.getMinX()); stage.setY(bounds.getMinY()); stage.setWidth(bounds.getWidth()); stage.setHeight(bounds.getHeight()); } private void registerStartupListener(CmdlineConfig config) { final ThreadService threadService = context.getBean(ThreadService.class); final TabService tabService = context.getBean(TabService.class); final FileOpenListener fileOpenListener = context.getBean(FileOpenListener.class); StartupNotification.registerStartupListener(fileOpenListener); if (!config.files.isEmpty()) { threadService.runActionLater(() -> { config.files.stream().forEach(f -> { File file = new File(f).getAbsoluteFile(); if (file.exists()) { logger.info("Opening file as requsted from cmdline: {}", file); tabService.addTab(file.toPath()); } else { // TODO: do we want to create such a file on demand? logger.error("Cannot open non-existent file: {}", file); } }); }); } } @Override public void stop() throws Exception { controller.closeApp(null); context.registerShutdownHook(); Platform.exit(); System.exit(0); } /** * The main() method is ignored in correctly deployed JavaFX application. * main() serves only as fallback in case the application can not be * launched through deployment artifacts, e.g., in IDEs with limited FX * support. NetBeans ignores main(). * * @param args the command line arguments */ public static void main(String[] args) { launch(args); } }
package org.eeiiaa.wifi; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.content.Context; import android.net.wifi.ScanResult; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiManager; import android.net.wifi.WifiConfiguration.AuthAlgorithm; import android.net.wifi.WifiConfiguration.GroupCipher; import android.net.wifi.WifiConfiguration.KeyMgmt; import android.net.wifi.WifiConfiguration.PairwiseCipher; import android.net.wifi.WifiConfiguration.Protocol; import android.text.TextUtils; import android.util.Log; public class Wifi { // Constants used for different security types public static final String WPA2 = "WPA2"; public static final String WPA = "WPA"; public static final String WEP = "WEP"; public static final String OPEN = "Open"; // For EAP Enterprise fields public static final String WPA_EAP = "WPA-EAP"; public static final String IEEE8021X = "IEEE8021X"; public static final String[] EAP_METHOD = { "PEAP", "TLS", "TTLS" }; public static final int WEP_PASSWORD_AUTO = 0; public static final int WEP_PASSWORD_ASCII = 1; public static final int WEP_PASSWORD_HEX = 2; private static final String TAG = "Wifiglue:Wifi"; /** * Change the password of an existing configured network and connect to it * * @param wifiMgr * @param config * @param newPassword * @return */ public static boolean changePasswordAndConnect(final Context ctx, final WifiManager wifiMgr, final WifiConfiguration config, final String newPassword, final int numOpenNetworksKept) { setupSecurity(config, getWifiConfigurationSecurity(config), newPassword); final int networkId = wifiMgr.updateNetwork(config); if (networkId == -1) { // Update failed. return false; } return connectToConfiguredNetwork(ctx, wifiMgr, config, true); } /** * Configure a network, and connect to it. * * @param wifiMgr * @param scanResult * @param password * Password for secure network or is ignored. * @return */ public static boolean connectToNewNetwork(final Context ctx, final WifiManager wifiMgr, final ScanResult scanResult, final String password, final int numOpenNetworksKept) { final String security = getScanResultSecurity(scanResult); String newpass = convertToQuotedString(password); if (security.equals(OPEN)) { checkForExcessOpenNetworkAndSave(wifiMgr, numOpenNetworksKept); } WifiConfiguration config = new WifiConfiguration(); config.SSID = convertToQuotedString(scanResult.SSID); config.BSSID = scanResult.BSSID; setupSecurity(config, security, newpass); int id = -1; try { id = wifiMgr.addNetwork(config); } catch (NullPointerException e) { Log.e(TAG, "Weird!! Really!! What's wrong??", e); // Weird!! Really!! // This exception is reported by user to Android Developer } if (id == -1) { Log.e(TAG, "unable to add configuration :" + config.toString()); return false; } boolean saved = wifiMgr.saveConfiguration(); if (!saved) { Log.e(TAG, "unable to save configuration :" + config.toString()); return false; } config = getWifiConfiguration(wifiMgr, config, security); if (config == null) { return false; } boolean connected = connectToConfiguredNetwork(ctx, wifiMgr, config, true); return connected; } /* ip_address/mask */ public static String getWifiIface() { String ifAddress = null; String command = "/system/bin/ifconfig wlan0"; try { Process process = Runtime.getRuntime().exec(command); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); int read; char[] buffer = new char[4096]; StringBuffer output = new StringBuffer(); while ((read = reader.read(buffer)) > 0) { output.append(buffer, 0, read); } reader.close(); process.waitFor(); String ifconfig = output.toString(); Log.i(TAG,"ifconfig "+ifconfig); Pattern ipPattern = Pattern.compile("(\\d+\\.\\d+\\.\\d+\\.\\d+)"); Matcher ipMatcher = ipPattern.matcher(ifconfig); String ip = null; if (ipMatcher.find()){ ip = ipMatcher.group(); } String mask= null; if(ipMatcher.find()){ mask = ipMatcher.group(); } ifAddress = ip+"/"+mask; } catch (IOException e) { throw new RuntimeException(e); } catch (InterruptedException e) { throw new RuntimeException(e); } return ifAddress; } public static String quadIntIpToString(int ipAddress){ return ((ipAddress >> 0) & 0xFF) + "." + ((ipAddress >> 8) & 0xFF) + "." + ((ipAddress >> 16) & 0xFF) + "." + ((ipAddress >> 24) & 0xFF); } /** * Connect to a configured network. * * @param wifiManager * @param config * @param numOpenNetworksKept * Settings.Secure.WIFI_NUM_OPEN_NETWORKS_KEPT * @return */ public static boolean connectToConfiguredNetwork(final Context ctx, final WifiManager wifiMgr, WifiConfiguration config, boolean reassociate) { final String security = getWifiConfigurationSecurity(config); int oldPri = config.priority; // Make it the highest priority. int newPri = getMaxPriority(wifiMgr) + 1; if (newPri > MAX_PRIORITY) { newPri = shiftPriorityAndSave(wifiMgr); config = getWifiConfiguration(wifiMgr, config, security); if (config == null) { return false; } } // Set highest priority to this configured network config.priority = newPri; int networkId = wifiMgr.updateNetwork(config); if (networkId == -1) { return false; } // Do not disable others if (!wifiMgr.enableNetwork(networkId, false)) { config.priority = oldPri; return false; } if (!wifiMgr.saveConfiguration()) { config.priority = oldPri; return false; } // We have to retrieve the WifiConfiguration after save. config = getWifiConfiguration(wifiMgr, config, security); if (config == null) { return false; } // TODO: verify if to disable others is needed if not change second param to // false if (!wifiMgr.enableNetwork(config.networkId, true)) { return false; } // final boolean connect = reassociate ? wifiMgr.reassociate() : // wifiMgr.reconnect(); final boolean connect = wifiMgr.reconnect(); if (!connect) { return false; } return true; } public static boolean disconnectFromCurrentNetwork(String ssid, WifiManager wifiMgr, boolean enableOther) { int netid = wifiMgr.getConnectionInfo().getNetworkId(); WifiConfiguration config = null; if (netid == -1) { config = getWifiConfigurationBySsid(wifiMgr, convertToQuotedString(ssid)); if (config != null){ netid = config.networkId; } } else { config = getWifiConfigurationByNetworkId(wifiMgr, netid); } // reduce priority config.priority = 0; wifiMgr.updateNetwork(config); wifiMgr.saveConfiguration(); // disable current network if (wifiMgr.disableNetwork(netid)) { Log.i(TAG, "disable current network"); } else { return false; } // remove current network if (wifiMgr.removeNetwork(netid)) { Log.i(TAG, "current network removed"); wifiMgr.saveConfiguration(); // shift priorities and save shiftPriorityAndSave(wifiMgr); } else { return false; } if (enableOther) { WifiConfiguration newnet = getHighPriorityConfiguration(wifiMgr); Log.i(TAG, "enabling network config = " + newnet); if (newnet != null) { // enable others is may be true if we want the wifi to connect ONLY to // config.networkId wifiMgr.enableNetwork(newnet.networkId, false); } } return true; } public static boolean disconnectFromConfiguredNetwork(final Context ctx, final WifiManager wifiMgr, WifiConfiguration config, boolean enableOther) { // disable wifi int netid = config.networkId; if (wifiMgr.disableNetwork(netid)) { Log.i(TAG, "disable current network"); } // remove current network if (wifiMgr.removeNetwork(netid)) { Log.i(TAG, "current network removed"); wifiMgr.saveConfiguration(); } if (enableOther) { WifiConfiguration other = getHighPriorityConfiguration(wifiMgr); if (other != null) { // enable others is may be true if we want the wifi to connect ONLY to // config.networkId wifiMgr.enableNetwork(other.networkId, false); } } return true; } private static WifiConfiguration getHighPriorityConfiguration(WifiManager wifiMgr) { WifiConfiguration config = null; List<WifiConfiguration> configs = wifiMgr.getConfiguredNetworks(); List<ScanResult> scanResults = wifiMgr.getScanResults(); for (WifiConfiguration test : configs) { if (config == null) { config = test; } else if (test.priority > config.priority) { boolean found = false; for (Iterator<ScanResult> it = scanResults.iterator(); it.hasNext() && !found;) { if (test.SSID.equals(convertToQuotedString(it.next().SSID))) { config = test; found = true; } } } } return config; } private static void sortByPriority(final List<WifiConfiguration> configurations) { java.util.Collections.sort(configurations, new Comparator<WifiConfiguration>() { @Override public int compare(WifiConfiguration object1, WifiConfiguration object2) { return object1.priority - object2.priority; } }); } /** * Ensure no more than numOpenNetworksKept open networks in configuration * list. * * @param wifiMgr * @param numOpenNetworksKept * @return Operation succeed or not. */ private static boolean checkForExcessOpenNetworkAndSave(final WifiManager wifiMgr, final int numOpenNetworksKept) { final List<WifiConfiguration> configurations = wifiMgr.getConfiguredNetworks(); sortByPriority(configurations); boolean modified = false; int tempCount = 0; for (int i = configurations.size() - 1; i >= 0; i final WifiConfiguration config = configurations.get(i); if (getWifiConfigurationSecurity(config).equals(OPEN)) { tempCount++; if (tempCount >= numOpenNetworksKept) { modified = true; wifiMgr.removeNetwork(config.networkId); } } } if (modified) { return wifiMgr.saveConfiguration(); } return true; } private static final int MAX_PRIORITY = 99999; private static int shiftPriorityAndSave(final WifiManager wifiMgr) { final List<WifiConfiguration> configurations = wifiMgr.getConfiguredNetworks(); sortByPriority(configurations); final int size = configurations.size(); for (int i = 0; i < size; i++) { final WifiConfiguration config = configurations.get(i); config.priority = i; wifiMgr.updateNetwork(config); } wifiMgr.saveConfiguration(); return size; } private static int getMaxPriority(final WifiManager wifiManager) { final List<WifiConfiguration> configurations = wifiManager.getConfiguredNetworks(); int pri = 0; for (final WifiConfiguration config : configurations) { if (config.priority > pri) { pri = config.priority; } } return pri; } public static WifiConfiguration getWifiConfigurationBySsid(final WifiManager wifiMgr, final String ssid) { WifiConfiguration config = null; boolean found = false; List<WifiConfiguration> configs = wifiMgr.getConfiguredNetworks(); for (Iterator<WifiConfiguration> it = configs.iterator(); it.hasNext() && !found;) { WifiConfiguration test = it.next(); if (test.SSID.equals(ssid)) { found = true; config = test; } } return config; } public static WifiConfiguration getWifiConfigurationByNetworkId(final WifiManager wifiMgr, final int netid) { WifiConfiguration config = null; boolean found = false; List<WifiConfiguration> configs = wifiMgr.getConfiguredNetworks(); for (Iterator<WifiConfiguration> it = configs.iterator(); it.hasNext() && !found;) { WifiConfiguration test = it.next(); if (test.networkId == netid) { found = true; config = test; } } return config; } public static WifiConfiguration getWifiConfiguration(final WifiManager wifiMgr, final ScanResult hotsopt, String hotspotSecurity) { final String ssid = convertToQuotedString(hotsopt.SSID); if (ssid.length() == 0) { return null; } final String bssid = hotsopt.BSSID; if (bssid == null) { return null; } if (hotspotSecurity == null) { hotspotSecurity = getScanResultSecurity(hotsopt); } final List<WifiConfiguration> configurations = wifiMgr.getConfiguredNetworks(); if (configurations == null) { return null; } for (final WifiConfiguration config : configurations) { if (config.SSID == null || !ssid.equals(config.SSID)) { continue; } if (config.BSSID == null || bssid.equals(config.BSSID)) { final String configSecurity = getWifiConfigurationSecurity(config); if (hotspotSecurity.equals(configSecurity)) { return config; } } } return null; } public static WifiConfiguration getWifiConfiguration(final WifiManager wifiMgr, final WifiConfiguration configToFind, String security) { final String ssid = configToFind.SSID; if (ssid.length() == 0) { return null; } final String bssid = configToFind.BSSID; if (security == null) { security = getWifiConfigurationSecurity(configToFind); } final List<WifiConfiguration> configurations = wifiMgr.getConfiguredNetworks(); for (final WifiConfiguration config : configurations) { if (config.SSID == null || !ssid.equals(config.SSID)) { continue; } if (config.BSSID == null || bssid == null || bssid.equals(config.BSSID)) { final String configSecurity = getWifiConfigurationSecurity(config); if (security.equals(configSecurity)) { return config; } } } return null; } /** * @return The security of a given {@link WifiConfiguration}. */ static public String getWifiConfigurationSecurity(WifiConfiguration wifiConfig) { if (wifiConfig.allowedKeyManagement.get(KeyMgmt.NONE)) { // If we never set group ciphers, wpa_supplicant puts all of them. // For open, we don't set group ciphers. // For WEP, we specifically only set WEP40 and WEP104, so CCMP // and TKIP should not be there. if (!wifiConfig.allowedGroupCiphers.get(GroupCipher.CCMP) && (wifiConfig.allowedGroupCiphers.get(GroupCipher.WEP40) || wifiConfig.allowedGroupCiphers.get(GroupCipher.WEP104))) { return WEP; } else { return OPEN; } } else if (wifiConfig.allowedProtocols.get(Protocol.RSN)) { return WPA2; } else if (wifiConfig.allowedKeyManagement.get(KeyMgmt.WPA_EAP)) { return WPA_EAP; } else if (wifiConfig.allowedKeyManagement.get(KeyMgmt.IEEE8021X)) { return IEEE8021X; } else if (wifiConfig.allowedProtocols.get(Protocol.WPA)) { return WPA; } else { Log.w(TAG, "Unknown security type from WifiConfiguration, falling back on open."); return OPEN; } } /** * Fill in the security fields of WifiConfiguration config. * * @param config * The object to fill. * @param security * If is OPEN, password is ignored. * @param password * Password of the network if security is not OPEN. */ static public void setupSecurity(WifiConfiguration config, String security, final String password) { config.allowedAuthAlgorithms.clear(); config.allowedGroupCiphers.clear(); config.allowedKeyManagement.clear(); config.allowedPairwiseCiphers.clear(); config.allowedProtocols.clear(); if (TextUtils.isEmpty(security) || TextUtils.isEmpty(password)) { security = OPEN; Log.w(TAG, "Empty security, assuming open"); } if (security.equals(WEP)) { int wepPasswordType = WEP_PASSWORD_AUTO; // If password is empty, it should be left untouched if (!TextUtils.isEmpty(password)) { if (wepPasswordType == WEP_PASSWORD_AUTO) { if (isHexWepKey(password)) { config.wepKeys[0] = password; } else { config.wepKeys[0] = convertToQuotedString(password); } } else { config.wepKeys[0] = wepPasswordType == WEP_PASSWORD_ASCII ? convertToQuotedString(password) : password; } } config.wepTxKeyIndex = 0; config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN); config.allowedAuthAlgorithms.set(AuthAlgorithm.SHARED); config.allowedKeyManagement.set(KeyMgmt.NONE); config.allowedGroupCiphers.set(GroupCipher.WEP40); config.allowedGroupCiphers.set(GroupCipher.WEP104); } else if (security.equals(WPA) || security.equals(WPA2)) { config.allowedGroupCiphers.set(GroupCipher.TKIP); config.allowedGroupCiphers.set(GroupCipher.CCMP); config.allowedKeyManagement.set(KeyMgmt.WPA_PSK); config.allowedPairwiseCiphers.set(PairwiseCipher.CCMP); config.allowedPairwiseCiphers.set(PairwiseCipher.TKIP); config.allowedProtocols.set(security.equals(WPA2) ? Protocol.RSN : Protocol.WPA); // If password is empty, it should be left untouched if (!TextUtils.isEmpty(password)) { if (password.length() == 64 && isHex(password)) { // Goes unquoted as hex config.preSharedKey = password; } else { // Goes quoted as ASCII // config.preSharedKey = convertToQuotedString(password); config.preSharedKey = password; } } } else if (security.equals(OPEN)) { config.allowedKeyManagement.set(KeyMgmt.NONE); } else if (security.equals(WPA_EAP) || security.equals(IEEE8021X)) { config.allowedGroupCiphers.set(GroupCipher.TKIP); config.allowedGroupCiphers.set(GroupCipher.CCMP); if (security.equals(WPA_EAP)) { config.allowedKeyManagement.set(KeyMgmt.WPA_EAP); } else { config.allowedKeyManagement.set(KeyMgmt.IEEE8021X); } if (!TextUtils.isEmpty(password)) { config.preSharedKey = convertToQuotedString(password); } } } private static boolean isHexWepKey(String wepKey) { final int len = wepKey.length(); // WEP-40, WEP-104, and some vendors using 256-bit WEP (WEP-232?) if (len != 10 && len != 26 && len != 58) { return false; } return isHex(wepKey); } private static boolean isHex(String key) { for (int i = key.length() - 1; i >= 0; i final char c = key.charAt(i); if (!(c >= '0' && c <= '9' || c >= 'A' && c <= 'F' || c >= 'a' && c <= 'f')) { return false; } } return true; } private static String convertToQuotedString(String string) { if (TextUtils.isEmpty(string)) { return ""; } final int lastPos = string.length() - 1; if (lastPos < 0 || (string.charAt(0) == '"' && string.charAt(lastPos) == '"')) { return string; } return "\"" + string + "\""; } static final String[] SECURITY_MODES = { WEP, WPA, WPA2, WPA_EAP, IEEE8021X }; /** * @return The security of a given {@link ScanResult}. */ public static String getScanResultSecurity(ScanResult scanResult) { final String cap = scanResult.capabilities; for (int i = SECURITY_MODES.length - 1; i >= 0; i if (cap.contains(SECURITY_MODES[i])) { return SECURITY_MODES[i]; } } return OPEN; } }
package com.spotify.annoy; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteOrder; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.util.*; public class ANNIndex implements AnnoyIndex { private final ArrayList<Long> roots; private MappedByteBuffer[] buffers; private final int DIMENSION, MIN_LEAF_SIZE; private final IndexType INDEX_TYPE; private final int INDEX_TYPE_OFFSET; // size of C structs in bytes (initialized in init) private final int K_NODE_HEADER_STYLE; private final long NODE_SIZE; private final int INT_SIZE = 4; private final int FLOAT_SIZE = 4; private final int MAX_NODES_IN_BUFFER; private final int BLOCK_SIZE; private RandomAccessFile memoryMappedFile; /** * Construct and load an Annoy index of a specific type (euclidean / angular). * * @param dimension dimensionality of tree, e.g. 40 * @param filename filename of tree * @param indexType type of index * @throws IOException if file can't be loaded */ public ANNIndex(final int dimension, final String filename, IndexType indexType) throws IOException { this(dimension, filename, indexType, 0); } /** * Construct and load an (Angular) Annoy index. * * @param dimension dimensionality of tree, e.g. 40 * @param filename filename of tree * @throws IOException if file can't be loaded */ public ANNIndex(final int dimension, final String filename) throws IOException { this(dimension, filename, IndexType.ANGULAR); } ANNIndex(final int dimension, final String filename, IndexType indexType, final int blockSize) throws IOException { DIMENSION = dimension; INDEX_TYPE = indexType; INDEX_TYPE_OFFSET = (INDEX_TYPE == IndexType.ANGULAR) ? 4 : 8; K_NODE_HEADER_STYLE = (INDEX_TYPE == IndexType.ANGULAR) ? 12 : 16; // we can store up to MIN_LEAF_SIZE children in leaf nodes (we put // them where the separating plane normally goes) this.MIN_LEAF_SIZE = DIMENSION + 2; this.NODE_SIZE = K_NODE_HEADER_STYLE + FLOAT_SIZE * DIMENSION; this.MAX_NODES_IN_BUFFER = (int) (blockSize == 0 ? Integer.MAX_VALUE / NODE_SIZE : blockSize * NODE_SIZE); BLOCK_SIZE = (int) (this.MAX_NODES_IN_BUFFER * NODE_SIZE); roots = new ArrayList<>(); load(filename); } private void load(final String filename) throws IOException { memoryMappedFile = new RandomAccessFile(filename, "r"); long fileSize = memoryMappedFile.length(); if (fileSize == 0L) { throw new IOException("Index is a 0-byte file?"); } int numNodes = (int) (fileSize / NODE_SIZE); int buffIndex = (numNodes - 1) / MAX_NODES_IN_BUFFER; int rest = (int) (fileSize % BLOCK_SIZE); int blockSize = (rest > 0 ? rest : BLOCK_SIZE); long position = fileSize - blockSize; buffers = new MappedByteBuffer[buffIndex + 1]; boolean process = true; int m = -1; long index = fileSize; while(position >= 0) { MappedByteBuffer annBuf = memoryMappedFile.getChannel().map( FileChannel.MapMode.READ_ONLY, position, blockSize); annBuf.order(ByteOrder.LITTLE_ENDIAN); buffers[buffIndex--] = annBuf; for (int i = blockSize - (int) NODE_SIZE; process && i >= 0; i -= NODE_SIZE) { index -= NODE_SIZE; int k = annBuf.getInt(i); // node[i].n_descendants if (m == -1 || k == m) { roots.add(index); m = k; } else { process = false; } } blockSize = BLOCK_SIZE; position -= blockSize; } } private float getFloatInAnnBuf(long pos) { int b = (int) (pos / BLOCK_SIZE); int f = (int) (pos % BLOCK_SIZE); return buffers[b].getFloat(f); } private int getIntInAnnBuf(long pos) { int b = (int) (pos / BLOCK_SIZE); int i = (int) (pos % BLOCK_SIZE); return buffers[b].getInt(i); } @Override public void getNodeVector(final long nodeOffset, float[] v) { MappedByteBuffer nodeBuf = buffers[(int) (nodeOffset / BLOCK_SIZE)]; int offset = (int) ((nodeOffset % BLOCK_SIZE) + K_NODE_HEADER_STYLE); for (int i = 0; i < DIMENSION; i++) { v[i] = nodeBuf.getFloat(offset + i * FLOAT_SIZE); } } @Override public void getItemVector(int itemIndex, float[] v) { getNodeVector(itemIndex * NODE_SIZE, v); } private float getNodeBias(final long nodeOffset) { // euclidean-only return getFloatInAnnBuf(nodeOffset + 4); } public final float[] getItemVector(final int itemIndex) { return getNodeVector(itemIndex * NODE_SIZE); } public float[] getNodeVector(final long nodeOffset) { float[] v = new float[DIMENSION]; getNodeVector(nodeOffset, v); return v; } private static float norm(final float[] u) { float n = 0; for (float x : u) n += x * x; return (float) Math.sqrt(n); } private static float euclideanDistance(final float[] u, final float[] v) { float[] diff = new float[u.length]; for (int i = 0; i < u.length; i++) diff[i] = u[i] - v[i]; return norm(diff); } public static float cosineMargin(final float[] u, final float[] v) { double d = 0; for (int i = 0; i < u.length; i++) d += u[i] * v[i]; return (float) (d / (norm(u) * norm(v))); } public static float euclideanMargin(final float[] u, final float[] v, final float bias) { float d = bias; for (int i = 0; i < u.length; i++) d += u[i] * v[i]; return d; } /** * Closes this stream and releases any system resources associated * with it. If the stream is already closed then invoking this * method has no effect. * <p/> * <p> As noted in {@link AutoCloseable#close()}, cases where the * close may fail require careful attention. It is strongly advised * to relinquish the underlying resources and to internally * <em>mark</em> the {@code Closeable} as closed, prior to throwing * the {@code IOException}. * * @throws IOException if an I/O error occurs */ @Override public void close() throws IOException { memoryMappedFile.close(); } private class PQEntry implements Comparable<PQEntry> { PQEntry(final float margin, final long nodeOffset) { this.margin = margin; this.nodeOffset = nodeOffset; } private float margin; private long nodeOffset; @Override public int compareTo(final PQEntry o) { return Float.compare(o.margin, margin); } } private static boolean isZeroVec(float[] v) { for (int i = 0; i < v.length; i++) if (v[i] != 0) return false; return true; } @Override public final List<Integer> getNearest(final float[] queryVector, final int nResults) { PriorityQueue<PQEntry> pq = new PriorityQueue<>( roots.size() * FLOAT_SIZE); final float kMaxPriority = 1e30f; for (long r : roots) { pq.add(new PQEntry(kMaxPriority, r)); } Set<Integer> nearestNeighbors = new HashSet<Integer>(); while (nearestNeighbors.size() < roots.size() * nResults && !pq.isEmpty()) { PQEntry top = pq.poll(); long topNodeOffset = top.nodeOffset; int nDescendants = getIntInAnnBuf(topNodeOffset); float[] v = getNodeVector(topNodeOffset); if (nDescendants == 1) { // n_descendants // FIXME: does this ever happen? if (isZeroVec(v)) continue; nearestNeighbors.add((int) (topNodeOffset / NODE_SIZE)); } else if (nDescendants <= MIN_LEAF_SIZE) { for (int i = 0; i < nDescendants; i++) { int j = getIntInAnnBuf(topNodeOffset + INDEX_TYPE_OFFSET + i * INT_SIZE); if (isZeroVec(getNodeVector(j * NODE_SIZE))) continue; nearestNeighbors.add(j); } } else { float margin = (INDEX_TYPE == IndexType.ANGULAR) ? cosineMargin(v, queryVector) : euclideanMargin(v, queryVector, getNodeBias(topNodeOffset)); long childrenMemOffset = topNodeOffset + INDEX_TYPE_OFFSET; long lChild = NODE_SIZE * getIntInAnnBuf(childrenMemOffset); long rChild = NODE_SIZE * getIntInAnnBuf(childrenMemOffset + 4); pq.add(new PQEntry(-margin, lChild)); pq.add(new PQEntry(margin, rChild)); } } ArrayList<PQEntry> sortedNNs = new ArrayList<PQEntry>(); int i = 0; for (int nn : nearestNeighbors) { float[] v = getItemVector(nn); if (!isZeroVec(v)) { sortedNNs.add( new PQEntry((INDEX_TYPE == IndexType.ANGULAR) ? cosineMargin(v, queryVector) : -euclideanDistance(v, queryVector), nn)); } } Collections.sort(sortedNNs); ArrayList<Integer> result = new ArrayList<>(nResults); for (i = 0; i < nResults && i < sortedNNs.size(); i++) { result.add((int) sortedNNs.get(i).nodeOffset); } return result; } /** * a test query program. * * @param args tree filename, dimension, indextype ("angular" or * "euclidean" and query item id. * @throws IOException if unable to load index */ public static void main(final String[] args) throws IOException { String indexPath = args[0]; int dimension = Integer.parseInt(args[1]); IndexType indexType = null; if (args[2].toLowerCase().equals("angular")) indexType = IndexType.ANGULAR; else if (args[2].toLowerCase().equals("euclidean")) indexType = IndexType.EUCLIDEAN; else throw new RuntimeException("wrong index type specified"); int queryItem = Integer.parseInt(args[3]); ANNIndex annIndex = new ANNIndex(dimension, indexPath, indexType); float[] u = annIndex.getItemVector(queryItem); System.out.printf("vector[%d]: ", queryItem); for (float x : u) { System.out.printf("%2.2f ", x); } System.out.printf("\n"); List<Integer> nearestNeighbors = annIndex.getNearest(u, 10); for (int nn : nearestNeighbors) { float[] v = annIndex.getItemVector(nn); System.out.printf("%d %d %f\n", queryItem, nn, (indexType == IndexType.ANGULAR) ? cosineMargin(u, v) : euclideanDistance(u, v)); } } }
package com.uchicom.rssr; import java.awt.Dimension; import java.awt.Font; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.net.URLStreamHandler; import java.time.ZoneId; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Properties; import javax.swing.DefaultListModel; import javax.swing.JEditorPane; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.ListSelectionModel; import javax.swing.SwingUtilities; import com.uchicom.wjm.WJMFrame; /** * @author uchicom: Shigeki Uchiyama * */ public class RssrFrame extends JFrame { private JList<Item> list = new JList<>(); private JEditorPane editorPane = new JEditorPane(); private File configFile = new File("conf/rssr.properties"); private Properties config = new Properties(); private List<Channel> channelList = new ArrayList<Channel>(); public RssrFrame() { super(Constants.NAME); initComponents(configFile); } public RssrFrame(File configFile) { super(Constants.NAME); initComponents(configFile); } private void initProperties(File configFile) { try (FileInputStream fis = new FileInputStream(configFile);) { config.load(fis); } catch (FileNotFoundException e) { // TODO catch e.printStackTrace(); } catch (IOException e) { // TODO catch e.printStackTrace(); } } private void initComponents(File configFile) { initProperties(configFile); editorPane.setEditable(false); editorPane.setContentType("text/html"); setDefaultCloseOperation(DISPOSE_ON_CLOSE); list.setFont(list.getFont().deriveFont(Font.PLAIN)); JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); splitPane.setLeftComponent(new JScrollPane(list)); list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // list. // list.addMouseListener(new MouseAdapter() { // @Override // public void mouseEntered(MouseEvent me) { // editorPane.setText(list.getComponentAt(list.getMousePosition()).getName()); // frame.pack(); // frame.setVisible(true); // @Override // public void mouseExited(MouseEvent me) { // frame.setVisible(false); list.addListSelectionListener((e) -> { if (!e.getValueIsAdjusting()) { Item item = list.getSelectedValue(); StringBuffer strBuff = new StringBuffer(); if (item != null) { strBuff.append("<h1>").append(item.getTitle()).append("</h1><h2>"); strBuff.append( Constants.formatter2.format(item.getPubDate().toInstant().atZone(ZoneId.systemDefault()))) .append("</h2><p>"); if (item.getDescription().contains("<br/>")) { strBuff.append(item.getDescription()); } else { strBuff.append(item.getDescription().replaceAll("\n", "<br/>")); } strBuff.append("</p>"); } editorPane.setText(strBuff.toString()); editorPane.setCaretPosition(0); } }); list.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent me) { if (me.getClickCount() > 1) { if (!list.isSelectionEmpty()) { try { URL link = list.getSelectedValue().getLink(); URL url = new URL(link.getProtocol(), link.getHost(), link.getPort(), link.getFile() , new URLStreamHandler() { @Override protected int getDefaultPort() { System.out.println("dp:" + super.getDefaultPort()); return 80; } @Override protected URLConnection openConnection(URL paramURL) throws IOException { System.out.println("openCon:" + paramURL); URLConnection con = new URL(paramURL.toString()).openConnection(); // con.setRequestProperty("Accept-Encoding", "gzip"); con.setRequestProperty("Accept-Charset", "UTF-8,*;q=0.5"); con.setRequestProperty("Accept-Language", "ja,en-US;q=0.8,en;q=0.6"); con.setRequestProperty("User-Agent", "WJM/1.0"); return con; } }); WJMFrame frame = new WJMFrame(url); frame.setPreferredSize(new Dimension(300, 300)); frame.setVisible(true); } catch (MalformedURLException e) { // TODO catch e.printStackTrace(); } } } } }); splitPane.setRightComponent(new JScrollPane(editorPane)); getContentPane().add(splitPane); config.entrySet().forEach((e) -> { String key = e.getKey().toString(); if (key.endsWith(".url")) { Thread thread = new Thread(new RssRunnable(this, key)); thread.setDaemon(true); thread.start(); } }); pack(); } public String getProperty(String key) { return config.getProperty(key); } public void setChannel(Channel channel) { synchronized (this) { Item before = list.getSelectedValue(); if (!channelList.contains(channel)) { channelList.add(channel); } List<Item> tempList = new ArrayList<>(); channelList.forEach((c)-> { c.getItemList().forEach((item) -> { tempList.add(item); }); }); SwingUtilities.invokeLater(() -> { tempList.sort(new Comparator<Item>() { @Override public int compare(Item o1, Item o2) { if (o1 == null) { if (o2 == null) { return 0; } else { return 1; } } else if (o2 == null) { return -1; } if (o1.getPubDate()==null) { return 1; } else if (o2.getPubDate()==null) { return -1; } return -o1.getPubDate().compareTo(o2.getPubDate()); } }); DefaultListModel<Item> model = new DefaultListModel<>(); tempList.forEach((i)->{ model.addElement(i); }); list.setModel(model); list.setSelectedValue(before, true); }); } } }
package crazypants.enderio; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.List; import java.util.Locale; import javax.annotation.Nonnull; import com.enderio.core.common.Lang; import com.enderio.core.common.network.MessageTileNBT; import com.enderio.core.common.util.EntityUtil; import com.google.common.collect.ImmutableList; import crazypants.enderio.api.IMC; import crazypants.enderio.block.BlockDarkSteelAnvil; import crazypants.enderio.block.BlockDarkSteelLadder; import crazypants.enderio.block.BlockDecoration; import crazypants.enderio.block.BlockDecorationFacing; import crazypants.enderio.block.BlockReinforcedObsidian; import crazypants.enderio.block.BlockSelfResettingLever; import crazypants.enderio.conduit.BlockConduitBundle; import crazypants.enderio.conduit.ConduitRecipes; import crazypants.enderio.conduit.facade.BlockConduitFacade; import crazypants.enderio.conduit.geom.ConduitGeometryUtil; import crazypants.enderio.conduit.item.ItemExtractSpeedUpgrade; import crazypants.enderio.conduit.item.ItemFunctionUpgrade; import crazypants.enderio.conduit.item.ItemItemConduit; import crazypants.enderio.conduit.item.filter.ItemBasicItemFilter; import crazypants.enderio.conduit.item.filter.ItemExistingItemFilter; import crazypants.enderio.conduit.item.filter.ItemModItemFilter; import crazypants.enderio.conduit.item.filter.ItemPowerItemFilter; import crazypants.enderio.conduit.liquid.ItemLiquidConduit; import crazypants.enderio.conduit.oc.ItemOCConduit; import crazypants.enderio.conduit.power.ItemPowerConduit; import crazypants.enderio.conduit.redstone.InsulatedRedstoneConduit; import crazypants.enderio.conduit.redstone.ItemRedstoneConduit; import crazypants.enderio.config.Config; import crazypants.enderio.enchantment.Enchantments; import crazypants.enderio.enderface.BlockEnderIO; import crazypants.enderio.enderface.ItemEnderface; import crazypants.enderio.fluid.FluidFuelRegister; import crazypants.enderio.fluid.Fluids; import crazypants.enderio.integration.buildcraft.BuildcraftIntegration; import crazypants.enderio.item.ItemConduitProbe; import crazypants.enderio.item.ItemEnderFood; import crazypants.enderio.item.ItemRecipes; import crazypants.enderio.item.ItemSoulVessel; import crazypants.enderio.item.ItemYetaWrench; import crazypants.enderio.item.darksteel.DarkSteelController; import crazypants.enderio.item.darksteel.DarkSteelItems; import crazypants.enderio.item.skull.BlockEndermanSkull; import crazypants.enderio.machine.MachineRecipes; import crazypants.enderio.machine.PacketRedstoneMode; import crazypants.enderio.machine.alloy.AlloyRecipeManager; import crazypants.enderio.machine.alloy.BlockAlloySmelter; import crazypants.enderio.machine.buffer.BlockBuffer; import crazypants.enderio.machine.capbank.BlockCapBank; import crazypants.enderio.machine.crafter.BlockCrafter; import crazypants.enderio.machine.enchanter.BlockEnchanter; import crazypants.enderio.machine.enchanter.EnchanterRecipeManager; import crazypants.enderio.machine.farm.BlockFarmStation; import crazypants.enderio.machine.farm.FarmersRegistry; import crazypants.enderio.machine.gauge.BlockGauge; import crazypants.enderio.machine.generator.combustion.BlockCombustionGenerator; import crazypants.enderio.machine.generator.stirling.BlockStirlingGenerator; import crazypants.enderio.machine.generator.zombie.BlockZombieGenerator; import crazypants.enderio.machine.invpanel.BlockInventoryPanel; import crazypants.enderio.machine.invpanel.remote.ItemRemoteInvAccess; import crazypants.enderio.machine.invpanel.sensor.BlockInventoryPanelSensor; import crazypants.enderio.machine.killera.BlockKillerJoe; import crazypants.enderio.machine.light.BlockElectricLight; import crazypants.enderio.machine.light.BlockLightNode; import crazypants.enderio.machine.monitor.BlockPowerMonitor; import crazypants.enderio.machine.obelisk.attractor.BlockAttractor; import crazypants.enderio.machine.obelisk.aversion.BlockAversionObelisk; import crazypants.enderio.machine.obelisk.inhibitor.BlockInhibitorObelisk; import crazypants.enderio.machine.obelisk.relocator.BlockRelocatorObelisk; import crazypants.enderio.machine.obelisk.weather.BlockWeatherObelisk; import crazypants.enderio.machine.obelisk.xp.BlockExperienceObelisk; import crazypants.enderio.machine.obelisk.xp.ItemXpTransfer; import crazypants.enderio.machine.painter.BlockPainter; import crazypants.enderio.machine.painter.blocks.BlockPaintedCarpet; import crazypants.enderio.machine.painter.blocks.BlockPaintedFence; import crazypants.enderio.machine.painter.blocks.BlockPaintedFenceGate; import crazypants.enderio.machine.painter.blocks.BlockPaintedGlowstone; import crazypants.enderio.machine.painter.blocks.BlockPaintedPressurePlate; import crazypants.enderio.machine.painter.blocks.BlockPaintedRedstone; import crazypants.enderio.machine.painter.blocks.BlockPaintedSlab; import crazypants.enderio.machine.painter.blocks.BlockPaintedStairs; import crazypants.enderio.machine.painter.blocks.BlockPaintedWall; import crazypants.enderio.machine.reservoir.BlockReservoir; import crazypants.enderio.machine.sagmill.BlockSagMill; import crazypants.enderio.machine.sagmill.SagMillRecipeManager; import crazypants.enderio.machine.slicensplice.BlockSliceAndSplice; import crazypants.enderio.machine.slicensplice.SliceAndSpliceRecipeManager; import crazypants.enderio.machine.solar.BlockSolarPanel; import crazypants.enderio.machine.soul.BlockSoulBinder; import crazypants.enderio.machine.soul.SoulBinderRecipeManager; import crazypants.enderio.machine.spawner.BlockPoweredSpawner; import crazypants.enderio.machine.spawner.ItemBrokenSpawner; import crazypants.enderio.machine.spawner.PoweredSpawnerConfig; import crazypants.enderio.machine.tank.BlockTank; import crazypants.enderio.machine.transceiver.BlockTransceiver; import crazypants.enderio.machine.transceiver.ServerChannelRegister; import crazypants.enderio.machine.vacuum.BlockVacuumChest; import crazypants.enderio.machine.vat.BlockVat; import crazypants.enderio.machine.vat.VatRecipeManager; import crazypants.enderio.machine.wireless.BlockWirelessCharger; import crazypants.enderio.material.BlockDarkIronBars; import crazypants.enderio.material.BlockIngotStorage; import crazypants.enderio.material.ItemAlloy; import crazypants.enderio.material.ItemCapacitor; import crazypants.enderio.material.ItemFrankenSkull; import crazypants.enderio.material.ItemMachinePart; import crazypants.enderio.material.ItemMaterial; import crazypants.enderio.material.ItemPowderIngot; import crazypants.enderio.material.MaterialRecipes; import crazypants.enderio.material.OreDictionaryPreferences; import crazypants.enderio.material.fusedQuartz.BlockColoredFusedQuartz; import crazypants.enderio.material.fusedQuartz.BlockFusedQuartz; import crazypants.enderio.material.fusedQuartz.BlockPaintedFusedQuartz; import crazypants.enderio.network.PacketHandler; import crazypants.enderio.paint.PaintSourceValidator; import crazypants.enderio.power.CapInjectHandler; import crazypants.enderio.power.PowerHandlerUtil; import crazypants.enderio.rail.BlockEnderRail; import crazypants.enderio.rail.BlockExitRail; import crazypants.enderio.render.dummy.BlockMachineBase; import crazypants.enderio.render.dummy.BlockMachineIO; import crazypants.enderio.teleport.ItemTravelStaff; import crazypants.enderio.teleport.anchor.BlockTravelAnchor; import crazypants.enderio.teleport.anchor.TileTravelAnchor; import crazypants.enderio.teleport.telepad.BlockDialingDevice; import crazypants.enderio.teleport.telepad.BlockTelePad; import crazypants.enderio.teleport.telepad.ItemCoordSelector; import crazypants.enderio.teleport.telepad.ItemLocationPrintout; import crazypants.enderio.teleport.telepad.ItemRodOfReturn; import crazypants.enderio.tool.EnderIOCrashCallable; import crazypants.util.CapturedMob; import crazypants.util.Things; import net.minecraft.block.Block; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.Mod.Instance; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLInterModComms; import net.minecraftforge.fml.common.event.FMLInterModComms.IMCEvent; import net.minecraftforge.fml.common.event.FMLInterModComms.IMCMessage; import net.minecraftforge.fml.common.event.FMLLoadCompleteEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.event.FMLServerStartedEvent; import net.minecraftforge.fml.common.event.FMLServerStoppedEvent; import net.minecraftforge.fml.common.network.NetworkRegistry; import net.minecraftforge.fml.relauncher.Side; import static crazypants.enderio.EnderIO.MODID; import static crazypants.enderio.EnderIO.MOD_NAME; import static crazypants.enderio.EnderIO.VERSION; import static crazypants.util.Things.TRAVEL_BLACKLIST; @Mod(modid = MODID, name = MOD_NAME, version = VERSION, dependencies = "after:endercore;after:Waila;after:JEI@[3.11.1,)", guiFactory = "crazypants.enderio.config.ConfigFactoryEIO") public class EnderIO { public static final @Nonnull String MODID = "EnderIO"; public static final @Nonnull String DOMAIN = MODID.toLowerCase(Locale.US); public static final String MOD_NAME = "Ender IO"; public static final String VERSION = "@VERSION@"; //Enable this to use forge buckets // static { // FluidRegistry.enableUniversalBucket(); @Instance(MODID) public static EnderIO instance; @SidedProxy(clientSide = "crazypants.enderio.ClientProxy", serverSide = "crazypants.enderio.CommonProxy") public static CommonProxy proxy; public static final PacketHandler packetPipeline = new PacketHandler(); public static GuiHandler guiHandler = new GuiHandler(); public static final Lang lang = new Lang("enderio"); // Materials public static ItemCapacitor itemBasicCapacitor; public static ItemAlloy itemAlloy; public static BlockFusedQuartz blockFusedQuartz; public static ItemMachinePart itemMachinePart; public static ItemPowderIngot itemPowderIngot; public static ItemMaterial itemMaterial; public static BlockIngotStorage blockIngotStorage; public static BlockDarkIronBars blockDarkIronBars; public static ItemEnderFood itemEnderFood; // // Enderface public static BlockEnderIO blockEnderIo; public static ItemEnderface itemEnderface; // //Teleporting public static BlockTravelAnchor<TileTravelAnchor> blockTravelPlatform; public static BlockTelePad blockTelePad; public static BlockDialingDevice blockDialingDevice; public static ItemCoordSelector itemCoordSelector; public static ItemTravelStaff itemTravelStaff; public static ItemRodOfReturn itemRodOfReturn; public static ItemLocationPrintout itemlocationPrintout; // // Painter public static BlockPainter blockPainter; public static BlockPaintedFence blockPaintedFence; public static BlockPaintedFenceGate blockPaintedFenceGate; public static BlockPaintedWall blockPaintedWall; public static BlockPaintedStairs blockPaintedStair; public static BlockPaintedSlab blockPaintedSlab; public static BlockPaintedGlowstone blockPaintedGlowstone; public static BlockPaintedCarpet blockPaintedCarpet; public static BlockPaintedPressurePlate blockPaintedPressurePlate; // // Conduits public static BlockConduitBundle blockConduitBundle; public static BlockConduitFacade blockConduitFacade; public static ItemRedstoneConduit itemRedstoneConduit; public static ItemPowerConduit itemPowerConduit; public static ItemLiquidConduit itemLiquidConduit; public static ItemItemConduit itemItemConduit; public static ItemOCConduit itemOCConduit; public static ItemBasicItemFilter itemBasicFilterUpgrade; public static ItemExistingItemFilter itemExistingItemFilter; public static ItemModItemFilter itemModItemFilter; public static ItemPowerItemFilter itemPowerItemFilter; public static ItemExtractSpeedUpgrade itemExtractSpeedUpgrade; public static ItemFunctionUpgrade itemFunctionUpgrade; // Machines public static BlockStirlingGenerator blockStirlingGenerator; public static BlockCombustionGenerator blockCombustionGenerator; public static BlockZombieGenerator blockZombieGenerator; public static BlockSolarPanel blockSolarPanel; public static BlockReservoir blockReservoir; public static BlockAlloySmelter blockAlloySmelter; public static BlockCapBank blockCapBank; public static BlockWirelessCharger blockWirelessCharger; public static BlockSagMill blockCrusher; public static Block blockPowerMonitor; public static Block blockPowerMonitorAdvanced; public static BlockVat blockVat; public static BlockFarmStation blockFarmStation; public static BlockTank blockTank; public static BlockCrafter blockCrafter; public static BlockPoweredSpawner blockPoweredSpawner; public static ItemBrokenSpawner itemBrokenSpawner; public static BlockSliceAndSplice blockSliceAndSplice; public static BlockSoulBinder blockSoulFuser; public static BlockAttractor blockAttractor; public static BlockAversionObelisk blockSpawnGuard; public static BlockRelocatorObelisk blockSpawnRelocator; public static BlockExperienceObelisk blockExperianceOblisk; public static BlockWeatherObelisk blockWeatherObelisk; public static BlockInhibitorObelisk blockInhibitorObelisk; public static BlockTransceiver blockTransceiver; public static BlockBuffer blockBuffer; public static BlockInventoryPanel blockInventoryPanel; public static BlockInventoryPanelSensor blockInventoryPanelSensor; public static BlockKillerJoe blockKillerJoe; public static BlockEnchanter blockEnchanter; public static BlockGauge blockGauge; public static BlockElectricLight blockElectricLight; public static BlockLightNode blockLightNode; // Blocks public static BlockDarkSteelAnvil blockDarkSteelAnvil; public static BlockDarkSteelLadder blockDarkSteelLadder; public static BlockEndermanSkull blockEndermanSkull; public static BlockReinforcedObsidian blockReinforcedObsidian; public static BlockEnderRail blockEnderRail; public static BlockExitRail blockExitRail; public static BlockDecoration blockDecoration1, blockDecoration2; public static Fluids fluids; // Items public static ItemYetaWrench itemYetaWench; public static ItemConduitProbe itemConduitProbe; public static ItemXpTransfer itemXpTransfer; public static ItemSoulVessel itemSoulVessel; public static ItemFrankenSkull itemFrankenSkull; public static BlockVacuumChest blockVacuumChest; public static ItemRemoteInvAccess itemRemoteInvAccess; // prePreInit static { CapInjectHandler.loadClass(); } @EventHandler public void preInit(FMLPreInitializationEvent event) { EnderIOCrashCallable.create(); PowerHandlerUtil.create(); Config.load(event); proxy.loadIcons(); // Dummy blocks that contain the models for all the other blocks BlockMachineBase.create(); BlockMachineIO.create(); // TODO: find some block that can take those models as extra ConduitGeometryUtil.setupBounds((float) Config.conduitScale); blockStirlingGenerator = BlockStirlingGenerator.create(); blockCombustionGenerator = BlockCombustionGenerator.create(); blockZombieGenerator = BlockZombieGenerator.create(); blockSolarPanel = BlockSolarPanel.create(); blockCrusher = BlockSagMill.create(); blockAlloySmelter = BlockAlloySmelter.create(); blockCapBank = BlockCapBank.create(); blockPainter = BlockPainter.create(); blockPaintedFence = BlockPaintedFence.create(); blockPaintedFenceGate = BlockPaintedFenceGate.create(); blockPaintedWall = BlockPaintedWall.create(); blockPaintedStair = BlockPaintedStairs.create(); blockPaintedSlab = BlockPaintedSlab.create(); blockPaintedGlowstone = BlockPaintedGlowstone.create(); BlockPaintedRedstone.create(); blockPaintedCarpet = BlockPaintedCarpet.create(); blockPaintedPressurePlate = BlockPaintedPressurePlate.create(); blockCrafter = BlockCrafter.create(); blockVat = BlockVat.create(); blockPowerMonitor = BlockPowerMonitor.createPowerMonitor(); blockPowerMonitorAdvanced = BlockPowerMonitor.createAdvancedPowerMonitor(); blockFarmStation = BlockFarmStation.create(); blockWirelessCharger = BlockWirelessCharger.create(); blockTank = BlockTank.create(); blockReservoir = BlockReservoir.create(); blockVacuumChest = BlockVacuumChest.create(); blockTransceiver = BlockTransceiver.create(); blockBuffer = BlockBuffer.create(); blockInventoryPanel = BlockInventoryPanel.create(); blockInventoryPanelSensor = BlockInventoryPanelSensor.create(); blockEnderIo = BlockEnderIO.create(); blockTravelPlatform = BlockTravelAnchor.create(); itemCoordSelector = ItemCoordSelector.create(); blockTelePad = BlockTelePad.createTelepad(); blockDialingDevice = BlockDialingDevice.create(); blockSliceAndSplice = BlockSliceAndSplice.create(); blockSoulFuser = BlockSoulBinder.create(); blockPoweredSpawner = BlockPoweredSpawner.create(); blockKillerJoe = BlockKillerJoe.create(); blockAttractor = BlockAttractor.create(); blockSpawnGuard = BlockAversionObelisk.create(); blockSpawnRelocator = BlockRelocatorObelisk.create(); blockExperianceOblisk = BlockExperienceObelisk.create(); blockWeatherObelisk = BlockWeatherObelisk.create(); blockInhibitorObelisk = BlockInhibitorObelisk.create(); blockEnchanter = BlockEnchanter.create(); blockDarkSteelAnvil = BlockDarkSteelAnvil.create(); blockDarkSteelLadder = BlockDarkSteelLadder.create(); BlockSelfResettingLever.create(); blockElectricLight = BlockElectricLight.create(); blockLightNode = BlockLightNode.create(); blockReinforcedObsidian = BlockReinforcedObsidian.create(); blockFusedQuartz = BlockFusedQuartz.create(); BlockColoredFusedQuartz.create(); BlockPaintedFusedQuartz.create(); // blockEnderRail = BlockEnderRail.create(); blockExitRail = BlockExitRail.create(); blockConduitBundle = BlockConduitBundle.create(); blockConduitFacade = BlockConduitFacade.create(); itemBrokenSpawner = ItemBrokenSpawner.create(); blockEndermanSkull = BlockEndermanSkull.create(); itemFrankenSkull = ItemFrankenSkull.create(); itemRedstoneConduit = ItemRedstoneConduit.create(); itemPowerConduit = ItemPowerConduit.create(); itemLiquidConduit = ItemLiquidConduit.create(); itemItemConduit = ItemItemConduit.create(); itemOCConduit = ItemOCConduit.create(); itemBasicFilterUpgrade = ItemBasicItemFilter.create(); itemExistingItemFilter = ItemExistingItemFilter.create(); itemModItemFilter = ItemModItemFilter.create(); itemPowerItemFilter = ItemPowerItemFilter.create(); itemExtractSpeedUpgrade = ItemExtractSpeedUpgrade.create(); itemFunctionUpgrade = ItemFunctionUpgrade.create(); itemBasicCapacitor = ItemCapacitor.create(); itemMachinePart = ItemMachinePart.create(); itemMaterial = ItemMaterial.create(); itemAlloy = ItemAlloy.create(); itemPowderIngot = ItemPowderIngot.create(); fluids = new Fluids(); fluids.registerFluids(); itemYetaWench = ItemYetaWrench.create(); itemEnderface = ItemEnderface.create(); itemTravelStaff = ItemTravelStaff.create(); itemRodOfReturn = ItemRodOfReturn.create(); itemlocationPrintout = ItemLocationPrintout.create(); itemConduitProbe = ItemConduitProbe.create(); itemXpTransfer = ItemXpTransfer.create(); itemSoulVessel = ItemSoulVessel.create(); blockIngotStorage = BlockIngotStorage.create(); blockDarkIronBars = BlockDarkIronBars.create(); itemEnderFood = ItemEnderFood.create(); blockGauge = BlockGauge.create(); itemRemoteInvAccess = ItemRemoteInvAccess.create(); DarkSteelItems.createDarkSteelArmorItems(); DarkSteelController.instance.register(); blockDecoration1 = BlockDecoration.create(); blockDecoration2 = BlockDecorationFacing.create(); FMLInterModComms.sendMessage("Waila", "register", "crazypants.enderio.integration.waila.WailaCompat.load"); MaterialRecipes.registerOresInDictionary(); proxy.preInit(); } @EventHandler public void load(FMLInitializationEvent event) { Things.enterInit(); Config.init(); instance = this; PacketHandler.INSTANCE.registerMessage(MessageTileNBT.class, MessageTileNBT.class, PacketHandler.nextID(), Side.SERVER); PacketHandler.INSTANCE.registerMessage(PacketRedstoneMode.class, PacketRedstoneMode.class, PacketHandler.nextID(), Side.SERVER); NetworkRegistry.INSTANCE.registerGuiHandler(this, guiHandler); MinecraftForge.EVENT_BUS.register(this); MaterialRecipes.registerDependantOresInDictionary(); if (Config.recipeLevel >= 0) { MaterialRecipes.addRecipes(); ConduitRecipes.addRecipes(); MachineRecipes.addRecipes(); ItemRecipes.addRecipes(); } proxy.init(); } @EventHandler public void postInit(FMLPostInitializationEvent event) { Config.postInit(); LootManager.register(); // Regsiter the enchants Enchantments.register(); // This must be loaded before parsing the recipes so we get the preferred // outputs OreDictionaryPreferences.loadConfig(); SagMillRecipeManager.getInstance().loadRecipesFromConfig(); AlloyRecipeManager.getInstance().loadRecipesFromConfig(); SliceAndSpliceRecipeManager.getInstance().loadRecipesFromConfig(); VatRecipeManager.getInstance().loadRecipesFromConfig(); EnchanterRecipeManager.getInstance().loadRecipesFromConfig(); FarmersRegistry.addFarmers(); SoulBinderRecipeManager.getInstance().addDefaultRecipes(); PaintSourceValidator.instance.loadConfig(); //should have been registered by open blocks if (Fluids.fluidXpJuice == null) { fluids.forgeRegisterXPJuice(); } if (Config.dumpMobNames) { dumpMobNamesToFile(); } addModIntegration(); } @EventHandler public void loadComplete(FMLLoadCompleteEvent event) { // Some mods send IMCs during PostInit, so we catch them here. processImc(FMLInterModComms.fetchRuntimeMessages(this)); } @EventHandler public void serverStarted(FMLServerStartedEvent event) { ServerChannelRegister.load(); } @EventHandler public void serverStopped(FMLServerStoppedEvent event) { ServerChannelRegister.store(); } @EventHandler public void onImc(IMCEvent evt) { processImc(evt.getMessages()); } private void addModIntegration() { // ThaumcraftCompat.load(); BuildcraftIntegration.init(); } private void processImc(ImmutableList<IMCMessage> messages) { for (IMCMessage msg : messages) { String key = msg.key; try { if (msg.isStringMessage()) { String value = msg.getStringValue(); if (IMC.VAT_RECIPE.equals(key)) { VatRecipeManager.getInstance().addCustomRecipes(value); } else if (IMC.SAG_RECIPE.equals(key)) { SagMillRecipeManager.getInstance().addCustomRecipes(value); } else if (IMC.ALLOY_RECIPE.equals(key)) { AlloyRecipeManager.getInstance().addCustomRecipes(value); } else if (IMC.POWERED_SPAWNER_BLACKLIST_ADD.equals(key)) { PoweredSpawnerConfig.getInstance().addToBlacklist(value); } else if (IMC.TELEPORT_BLACKLIST_ADD.equals(key)) { TRAVEL_BLACKLIST.add(value); } else if (IMC.SOUL_VIAL_BLACKLIST.equals(key) && itemSoulVessel != null) { CapturedMob.addToBlackList(value); } else if (IMC.ENCHANTER_RECIPE.equals(key)) { EnchanterRecipeManager.getInstance().addCustomRecipes(value); } else if (IMC.SLINE_N_SPLICE_RECIPE.equals(key)) { SliceAndSpliceRecipeManager.getInstance().addCustomRecipes(key); } } else if (msg.isNBTMessage()) { if (IMC.SOUL_BINDER_RECIPE.equals(key)) { SoulBinderRecipeManager.getInstance().addRecipeFromNBT(msg.getNBTValue()); } else if (IMC.POWERED_SPAWNER_COST_MULTIPLIER.equals(key)) { PoweredSpawnerConfig.getInstance().addEntityCostFromNBT(msg.getNBTValue()); } else if (IMC.FLUID_FUEL_ADD.equals(key)) { FluidFuelRegister.instance.addFuel(msg.getNBTValue()); } else if (IMC.FLUID_COOLANT_ADD.equals(key)) { FluidFuelRegister.instance.addCoolant(msg.getNBTValue()); } else if (IMC.REDSTONE_CONNECTABLE_ADD.equals(key)) { InsulatedRedstoneConduit.addConnectableBlock(msg.getNBTValue()); } } else if (msg.isItemStackMessage()) { if (IMC.PAINTER_WHITELIST_ADD.equals(key)) { PaintSourceValidator.instance.addToWhitelist(msg.getItemStackValue()); } else if (IMC.PAINTER_BLACKLIST_ADD.equals(key)) { PaintSourceValidator.instance.addToBlacklist(msg.getItemStackValue()); } } } catch (Exception e) { Log.error("Error occured handling IMC message " + key + " from " + msg.getSender()); } } } private void dumpMobNamesToFile() { File dumpFile = new File(Config.configDirectory, "mobTypes.txt"); List<String> names = EntityUtil.getAllRegisteredMobNames(); try { BufferedWriter br = new BufferedWriter(new FileWriter(dumpFile, false)); for (String name : names) { br.append(name); br.newLine(); } br.flush(); br.close(); } catch (Exception e) { Log.error("Could not write mob types file: " + e); } } static { // uncomment to always use the universal bucket. leave it out to only use it if another mod requests it. // net.minecraftforge.fluids.FluidRegistry.enableUniversalBucket(); } }
package creator; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.json.JSONObject; import de.ust.skill.common.java.api.SkillFile; import de.ust.skill.common.java.api.Access; import de.ust.skill.common.java.internal.FieldDeclaration; import de.ust.skill.common.java.internal.SkillObject; public class SkillObjectCreator { private static final String FIELD_DECLARATION_CLASS_NAME = "de.ust.skill.common.java.api.FieldDeclaration"; public static void main(String[] args) { String className = "age.Age"; String fieldToSet = "age"; String fieldTypeToSet = "long"; Long valueToSet = 255L; Map<String, Object> values = new HashMap<>(); Map<String, String> fieldTypes = new HashMap<>(); values.put(fieldToSet, valueToSet); fieldTypes.put(fieldToSet, fieldTypeToSet); try { SkillObject obj = instantiateSkillObject(className, values, fieldTypes); System.out.println(obj.prettyString(null)); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } /** * Initialise a SKilLObject based on a JSON representation of it and its * data * * @param sf * SKilL file from which type and field definitions are loaded * @param jsonObj * JSON representation of the object which should be initialised * @return */ public static void generateSkillFileMappings(SkillFile sf, Map<String, Access<?>> types, Map<String, HashMap<String, FieldDeclaration<?, ?>>> typeFieldMapping) { // Iterate over all SkilL types present in the given SKilL file for (Access<?> currentType : sf.allTypes()) { types.put(currentType.name(), currentType); // Save all fields defined in this type into a map HashMap<String, FieldDeclaration<?, ?>> fieldMapping = new HashMap<String, FieldDeclaration<?, ?>>(); Iterator<? extends de.ust.skill.common.java.api.FieldDeclaration<?>> iter = currentType.fields(); while (iter.hasNext()) { FieldDeclaration<?, ?> fieldDeclaration = (FieldDeclaration<?, ?>) iter.next(); fieldMapping.put(fieldDeclaration.name(), fieldDeclaration); } typeFieldMapping.put(currentType.name(), fieldMapping); } } /** * Create an empty SkillObject from a fully specified class name * * @param className * fully classified class name incl. package identifier * @return empty SkillObject of the specified class */ public static SkillObject createSkillObject(String className) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { Class<?> refClass = Class.forName(className); Constructor<?> refConstructor = refClass.getConstructor(); SkillObject refVar = (SkillObject) refConstructor.newInstance(); return refVar; } /** * Create and fill a SkillObject with the provided values * * @param className * fully specified class name incl. package identifier of the * object to be created * @param values * mapping of field names to values * @param fieldTypes * mapping of field names to the corresponding types of values * @return a SkillObject with the provided values as attributes */ public static SkillObject instantiateSkillObject(String className, Map<String, Object> values, Map<String, String> fieldTypes) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { SkillObject obj = createSkillObject(className); Map<String, Type> fieldMapping = getFieldMapping(className); for (String key : fieldMapping.keySet()) { String type = fieldMapping.get(key).getTypeName(); System.out.println("Present field: " + key + "(Type: " + type + ")"); if (values.containsKey(key)) { System.out.println("Setting field '" + key + "' to be " + values.get(key)); reflectiveSetValue(obj, values.get(key), key, fieldTypes.get(key)); } } return obj; } /** * Set the specified field of a SkillObject to a given value * * @param obj * the SkillObject for which the field is to be set * @param value * the value to set the field of the SkillObject to * @param fieldName * the name of the field to be set * @param fieldType * fully qualified class name of the field to be set * @return the provided SkillObject with a set new value */ public static SkillObject reflectiveSetValue(SkillObject obj, Object value, String fieldName, String fieldType) { try { Method setterMethod = obj.getClass().getMethod(getSetterName(fieldName), getAptClass(fieldType)); System.out.println("Found method " + setterMethod.getName()); setterMethod.invoke(obj, value); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return null; } /** * Get a Class object from a fully qualified class name incl. package * identifier * * @param type * fully qualified class name * @return Class object for the provided class name * @throws ClassNotFoundException */ private static Class<?> getAptClass(String type) throws ClassNotFoundException { if (!SKilLType.isPrimitive(type)) { return Class.forName(type); } else { switch (type) { case "byte": return byte.class; case "short": return short.class; case "int": return int.class; case "long": return long.class; case "float": return float.class; case "double": return double.class; case "boolean": return boolean.class; case "char": return char.class; default: return null; } } } /** * Parse a value encoded in a string to the specified type * * @param type * @param valueString * @return instance of the actual class of the provided value */ public static Object valueOf(String type, String valueString) { switch (type) { case "byte": return Byte.valueOf(valueString); case "short": return Short.valueOf(valueString); case "int": return Integer.valueOf(valueString); case "long": return Long.valueOf(valueString); case "float": return Float.valueOf(valueString); case "double": return Double.valueOf(valueString); case "boolean": return Boolean.valueOf(valueString); case "char": return Character.valueOf(valueString.charAt(0)); case "java.lang.String": return valueString; default: return null; } } /** * Return the method name of the setter method responsible for the field * with the name 'fieldName'. * * @param fieldName * the name of the field for which to get the name of the setter * method * @return the name of the setter method */ public static String getSetterName(String fieldName) { return "set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); } /** * Create a mapping of field names and their corresponding types of the * given class. * * @param className * the name of the class for which to generate the mapping * @return a mapping of field names to Type objects */ public static Map<String, Type> getFieldMapping(String className) { Map<String, Type> fieldTypeMapping; try { Class<?> cls = Class.forName(className); Field[] declaredFields = cls.getDeclaredFields(); fieldTypeMapping = new HashMap<>(declaredFields.length); for (Field field : declaredFields) { fieldTypeMapping.put(field.getName(), field.getGenericType()); } return fieldTypeMapping; } catch (ClassNotFoundException e) { e.printStackTrace(); } return null; } /** * Create a mapping of field names and their corresponding types of the * given class. * * @param cls * the class for which to generate the mapping * @return a mapping of field names to Type objects */ public static Map<String, Type> getFieldMapping(Class<?> cls) { Map<String, Type> fieldTypeMapping; Field[] declaredFields = cls.getDeclaredFields(); fieldTypeMapping = new HashMap<>(declaredFields.length); for (Field field : declaredFields) { fieldTypeMapping.put(field.getName(), field.getGenericType()); } return fieldTypeMapping; } }
package de.bmoth.app; import de.bmoth.modelchecker.ModelChecker; import de.bmoth.modelchecker.ModelCheckingResult; import javafx.application.Platform; import javafx.collections.SetChangeListener; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.*; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyCodeCombination; import javafx.scene.input.KeyCombination; import javafx.scene.layout.Region; import javafx.stage.FileChooser; import javafx.stage.Stage; import org.fxmisc.richtext.LineNumberFactory; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Optional; import java.util.ResourceBundle; public class AppController implements Initializable { @FXML MenuItem open; @FXML MenuItem save; @FXML MenuItem saveAs; @FXML MenuItem options; @FXML MenuItem exit; @FXML MenuItem modelCheck; @FXML CodeArea codeArea; @FXML TextArea infoArea; private Stage primaryStage = new Stage(); private PersonalPreference personalPreference; private String currentFile; private Boolean hasChanged = false; private final String APPNAME = "Bmoth"; @Override public void initialize(URL fxmlFileLocation, ResourceBundle resources) { save.setAccelerator(new KeyCodeCombination(KeyCode.S, KeyCombination.CONTROL_ANY)); codeArea.selectRange(0,0); codeArea.setParagraphGraphicFactory(LineNumberFactory.get(codeArea)); codeArea.richChanges().filter(ch -> !ch.getInserted().equals(ch.getRemoved())) // XXX .subscribe(change -> { codeArea.setStyleSpans(0, Highlighter.computeHighlighting(codeArea.getText())); }); codeArea.setStyleSpans(0, Highlighter.computeHighlighting(codeArea.getText())); } void setupStage(Stage stage) { primaryStage = stage; primaryStage.setTitle(APPNAME); primaryStage.setOnCloseRequest(event -> { event.consume(); handleExit(); }); } void setupPersonalPreference(PersonalPreference preference) { personalPreference = preference; if (personalPreference.getLastFile() != null) { currentFile = personalPreference.getLastFile(); String fileContent = openFile(new File(personalPreference.getLastFile())); codeArea.replaceText(fileContent); codeArea.deletehistory(); } codeArea.textProperty().addListener((observableValue, s, t1) -> { hasChanged = true; infoArea.setText("Unsaved changes"); }); } @FXML public void handleOpen() { int nextStep = -1; if (hasChanged) { nextStep = saveChangedDialog(); switch (nextStep) { case 0: break; case 1: save.fire(); break; case 2: saveAs.fire(); break; case -1: break; } } if (nextStep != 0) { String fileContent = openFileChooser(); if(fileContent!=null) { codeArea.replaceText(fileContent); codeArea.deletehistory(); codeArea.selectRange(0, 0); hasChanged = false; infoArea.clear(); } } } @FXML public void handleSave() { if (currentFile != null) { try { saveFile(currentFile); hasChanged = false; infoArea.clear(); } catch (IOException e) { e.printStackTrace(); } } else { try { saveFileAs(); } catch (IOException e) { e.printStackTrace(); } } } @FXML public Boolean handleSaveAs() { try { Boolean saved = saveFileAs(); hasChanged = false; infoArea.clear(); return saved; } catch (IOException e) { e.printStackTrace(); } return false; } @FXML public void handleExit() { PersonalPreference.savePrefToFile(personalPreference); if (hasChanged) { int nextStep = saveChangedDialog(); switch (nextStep) { case 0: break; case 1: handleSave(); Platform.exit(); break; case 2: Boolean saved = handleSaveAs(); if (saved) { Platform.exit(); break; } else { hasChanged = true; infoArea.setText("Unsaved changes"); break; } case -1: Platform.exit(); break; } } else { Platform.exit(); } } public void handleOptions() throws IOException { } @FXML public void handleCheck() { ModelCheckingResult result = ModelChecker.doModelCheck(codeArea.getText(),personalPreference); Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.setTitle("Model Checking Result"); alert.setHeaderText("The model is..."); if (result.isCorrect()) { alert.setContentText("...correct!\nNo counter-example found."); } else { alert.setContentText("...not correct!\nCounter-example found in state " + result.getLastState().toString() + ".\nReversed path: " + ModelCheckingResult.getPath(result.getLastState())); } alert.getDialogPane().setMinHeight(Region.USE_PREF_SIZE); alert.showAndWait(); } /** * Save codeArea to a file. * * @param path Save-location * @throws IOException */ private void saveFile(String path) throws IOException { File file = new File(path); if (!file.exists()) { file.createNewFile(); } FileWriter fileWriter = new FileWriter(file); fileWriter.write(codeArea.getText()); fileWriter.close(); } /** * Ask for location and name and save codeArea. * * @throws IOException * @see #saveFile(String) */ private Boolean saveFileAs() throws IOException { FileChooser fileChooser = new FileChooser(); fileChooser.setInitialDirectory(new File(System.getProperty("user.dir"))); fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("MCH File", "*.mch")); File file = fileChooser.showSaveDialog(primaryStage); if (file != null) { //add .mch ending if not added by OS if (!file.getAbsolutePath().endsWith(".mch")) { saveFile(file.getAbsolutePath() + ".mch"); } else { saveFile(file.getAbsolutePath()); } return true; } else return false; } /** * Open a confirmation-alert to decide how to proceed with unsaved changes. * * @return UserChoice as Integer: -1 = Ignore, 0 = Cancel, 1 = Save , 2 = SaveAs */ private int saveChangedDialog() { Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.setTitle("UNSAVED CHANGES!"); alert.setHeaderText("Unsaved Changes! What do you want to do?"); alert.setContentText(null); ButtonType buttonTypeSave = new ButtonType("Save"); ButtonType buttonTypeSaveAs = new ButtonType("Save As"); ButtonType buttonTypeIgnoreChanges = new ButtonType("Ignore"); ButtonType buttonTypeCancel = new ButtonType("Back", ButtonBar.ButtonData.CANCEL_CLOSE); alert.getButtonTypes().setAll(buttonTypeSave, buttonTypeSaveAs, buttonTypeIgnoreChanges, buttonTypeCancel); alert.getDialogPane().setMinHeight(Region.USE_PREF_SIZE); Optional<ButtonType> result = alert.showAndWait(); if (result.isPresent()) { if (result.get() == buttonTypeSave) return 1; if (result.get() == buttonTypeSaveAs) return 2; if (result.get() == buttonTypeCancel) return 0; if (result.get() == buttonTypeIgnoreChanges) return -1; } return 0; } /** * Ask the user which file to open into the textarea. If the file is found, openFile is called. * * @return Returns the filepath as string or null if cancelled * @see #openFile(File) */ private String openFileChooser() { FileChooser fileChooser = new FileChooser(); fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("Open MCH File", "*.mch")); fileChooser.setTitle("Choose File"); fileChooser.setInitialDirectory(new File(personalPreference.getPrefdir())); File file = fileChooser.showOpenDialog(primaryStage); if (file != null) { personalPreference.setLastFile(file.getAbsolutePath()); personalPreference.setPrefdir(file.getParent()); String content = openFile(file); primaryStage.setTitle(APPNAME + " - " + file.getName()); return content; } return null; } /** * Load a given file into the CodeArea and change the title of the stage. * * @param file File to read from */ private String openFile(File file) { String content = null; try { content = new String(Files.readAllBytes(Paths.get(file.getPath()))); } catch (IOException e) { e.printStackTrace(); } return content; } }
package fr.jrds.snmpcodec; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.TreeSet; import org.snmp4j.smi.OID; import org.snmp4j.smi.Variable; import fr.jrds.snmpcodec.MibException.DuplicatedSymbolOid; import fr.jrds.snmpcodec.log.LogAdapter; import fr.jrds.snmpcodec.parsing.ObjectTypeBuilder; import fr.jrds.snmpcodec.parsing.OidPath; import fr.jrds.snmpcodec.smi.Index; import fr.jrds.snmpcodec.smi.IndirectSyntax; import fr.jrds.snmpcodec.smi.ObjectType; import fr.jrds.snmpcodec.smi.Oid; import fr.jrds.snmpcodec.smi.ProvidesTextualConvention; import fr.jrds.snmpcodec.smi.Referenced; import fr.jrds.snmpcodec.smi.Symbol; import fr.jrds.snmpcodec.smi.Syntax; import fr.jrds.snmpcodec.smi.TextualConvention; public class MibStore { LogAdapter logger = LogAdapter.getLogger(MibStore.class); private final Set<Symbol> badsymbols = new HashSet<>(); private Map<Symbol, Oid> buildOids = new HashMap<>(); private Map<Oid, Symbol> buildOidNames = new HashMap<>(); private Set<Oid> allOids = new HashSet<>(); private Map<Symbol, Syntax> buildSyntaxes = new HashMap<>(); private Map<Symbol, Map<Integer, Map<String, Object>>> buildTraps = new HashMap<>(); private Map<Symbol, Map<String, Object>> textualConventions = new HashMap<>(); private Map<Oid, ObjectTypeBuilder> buildObjects = new HashMap<>(); private Set<Symbol> symbols = new HashSet<>(); private Map<Symbol, OidTreeNode> resolvedOids = new HashMap<>(); public final OidTreeNode top = new OidTreeNode(); public final Map<String, List<OidTreeNode>> names = new HashMap<>(); private final Map<OidTreeNode, Syntax> _syntaxes = new HashMap<>(); public final Map<OidTreeNode, Syntax> syntaxes = Collections.unmodifiableMap(_syntaxes); private final Map<OidTreeNode, ObjectType> _objects = new HashMap<>(); public final Map<OidTreeNode, ObjectType> objects = Collections.unmodifiableMap(_objects); private final Map<OidTreeNode, Map<Integer, Map<String, Object>>> _resolvedTraps = new HashMap<>(); public final Map<OidTreeNode, Map<Integer, Map<String, Object>>> resolvedTraps = Collections.unmodifiableMap(_resolvedTraps); private final Set<String> _modules = new HashSet<>(); public final Set<String> modules = Collections.unmodifiableSet(_modules); public MibStore() { Symbol ccitt = new Symbol("ccitt"); Symbol iso = new Symbol("iso"); Symbol joint = new Symbol("joint-iso-ccitt"); Symbol broken = new Symbol("broken-module"); try { buildOids.put(ccitt, new Oid(new int[]{0}, ccitt.name)); buildOids.put(iso, new Oid(new int[]{1}, iso.name)); buildOids.put(joint, new Oid(new int[]{2}, joint.name)); buildOids.put(broken, new Oid(new int[]{-1}, broken.name)); top.add(new int[]{0}, ccitt.name, false); top.add(new int[]{1}, iso.name, false); top.add(new int[]{2}, joint.name, false); top.add(new int[]{-1}, broken.name, false); } catch (MibException e) { } } /** * Prepare a new module * @param currentModule * @return true if the module is indeed new. * @throws MibException */ public void newModule(String currentModule) throws MibException { if (_modules.contains(currentModule)) { throw new MibException.DuplicatedModuleException(currentModule); } else { _modules.add(currentModule); } } public void addValue(Symbol s, Syntax syntax, OidPath value) throws MibException { if (symbols.contains(s)) { throw new MibException.DuplicatedSymbolException(s); } addOid(s, (OidPath)value, false); } public void addType(Symbol s, Syntax type) throws MibException { if (symbols.contains(s) ) { throw new MibException.DuplicatedSymbolException(s); } buildSyntaxes.put(s, type); symbols.add(s); } public void addTextualConvention(Symbol s, Map<String, Object> attributes) throws MibException { if (symbols.contains(s) ) { throw new MibException.DuplicatedSymbolException(s); } textualConventions.put(s, attributes); symbols.add(s); } public void addObjectType(Symbol s, Map<String, Object> attributes, OidPath value) throws MibException { if (symbols.contains(s) ) { throw new MibException.DuplicatedSymbolException(s); } ObjectTypeBuilder newtype = new ObjectTypeBuilder(attributes); Oid oid = addOid(s, value, newtype.isIndexed()); buildObjects.put(oid, newtype); } public void addTrapType(Symbol s, String name, Map<String, Object> attributes, Number trapIndex) throws MibException { if (symbols.contains(s) ) { throw new MibException.DuplicatedSymbolException(s); } attributes.put("SYMBOL", s); Object enterprise = attributes.get("ENTERPRISE"); if (enterprise instanceof Symbol) { buildTraps.computeIfAbsent((Symbol)enterprise, k -> new HashMap<>()).put(trapIndex.intValue(), attributes); } } public void addModuleIdentity(Symbol s, Map<String, Object> attributes, OidPath value) throws MibException { if (symbols.contains(s) ) { throw new MibException.DuplicatedSymbolException(s); } addOid(s, value, false); } public void addMacroValue(Symbol s, String name, Map<String, Object> attributes, OidPath value) throws MibException { if (symbols.contains(s) ) { throw new MibException.DuplicatedSymbolException(s); } addOid(s, value, false); } private Oid addOid(Symbol s, OidPath p, boolean tableEntry) throws MibException { p.getAll(tableEntry).forEach( i-> { if (i.getName() != null) { allOids.add(i); } }); Oid oid = new Oid(p.getRoot(), p.getComponents(), s.name, tableEntry); allOids.add(oid); if (!buildOids.containsKey(s)) { buildOids.put(s, oid); } else { throw new DuplicatedSymbolOid(oid.toString()); } symbols.add(s); return oid; } public OidTreeNode resolveToBuild(Symbol s) { return this.resolvedOids.get(s); } public void buildTree() { // Check in provides symbolsalias.txt for known problems or frequent problems in mibs files Properties props = new Properties(); try { Collections.list(ClassLoader.getSystemResources("symbolsalias.txt")).forEach( i-> { try { InputStream is = i.openStream(); props.load(is); } catch (IOException e) { throw new UncheckedIOException("Invalid symbols aliases file: " + e.getMessage(), e); } }); } catch (IOException e) { throw new UncheckedIOException("Invalid symbols aliases file: " + e.getMessage(), e); } props.entrySet().iterator().forEachRemaining( i -> { Symbol bad = new Symbol(i.getKey().toString()); Symbol good = new Symbol(i.getValue().toString()); if (buildOids.containsKey(good) && ! badsymbols.contains(bad)) { logger.debug("adding invalid symbol mapping: %s -> %s" , bad, good); buildOids.put(bad, buildOids.get(good)); badsymbols.add(bad); } if (buildSyntaxes.containsKey(good) && ! buildSyntaxes.containsKey(bad)) { logger.debug("adding invalid type declaration mapping: %s -> %s" , bad, good); buildSyntaxes.put(bad, buildSyntaxes.get(good)); } }); // Replace some eventually defined TextualConvention with the smarter version Symbol dateAndTime = new Symbol("SNMPv2-TC", "DateAndTime"); if (buildSyntaxes.containsKey(dateAndTime)) { buildSyntaxes.put(dateAndTime, new TextualConvention.DateAndTime()); } Symbol displayString = new Symbol("SNMPv2-TC", "DisplayString"); if (buildSyntaxes.containsKey(displayString)) { buildSyntaxes.put(displayString, new TextualConvention.DisplayString()); } sortdOids(); allOids.forEach(oid -> { try { int[] content = oid.getPath(buildOids).stream().mapToInt(Integer::intValue).toArray(); OidTreeNode node = top.add(content, oid.getName(), oid.isTableEntry()); names.computeIfAbsent(oid.getName(), i -> new ArrayList<>()).add(node); } catch (MibException e) { try { int[] content = oid.getPath(buildOids).stream().mapToInt(Integer::intValue).toArray(); top.add(content, oid.getName(), oid.isTableEntry()); } catch (MibException e1) { System.out.println(e.getMessage()); } System.out.println(e.getMessage()); } }); buildObjects.forEach((k,v) -> { OidTreeNode node; try { node = top.find(k.getPath(buildOids).stream().mapToInt(Integer::intValue).toArray()); _objects.put(node, v.resolve(this, node)); } catch (MibException e) { System.out.println(e.getMessage()); } }); this.buildSyntaxes.forEach((k, v) -> { OidTreeNode node = resolvedOids.get(k); _syntaxes.put(node, checkSyntax(node, v)); }); resolveTextualConventions(); symbols.clear(); buildObjects = null; buildOids = null; buildSyntaxes = null; buildTraps = null; resolvedOids = null; } public Syntax checkSyntax(OidTreeNode node, Syntax syntax) { if (syntax instanceof Referenced) { Referenced ref = (Referenced) syntax; Symbol refSymbol = ref.getSymbol(); if (refSymbol != null) { OidTreeNode refNode = resolvedOids.get(ref.getSymbol()); ref.resolve(refNode, this); } } return syntax; } private void resolveTextualConventions() { textualConventions.forEach((s, attributes) -> { Syntax type = (Syntax) attributes.get("SYNTAX"); String hint = (String) attributes.get("DISPLAY-HINT"); TextualConvention tc; Syntax finaltype = type; while (! (finaltype instanceof ProvidesTextualConvention) && finaltype != null) { if (finaltype instanceof Referenced) { Referenced ref = (Referenced) finaltype; Symbol refSymbol = ref.getSymbol(); if (refSymbol != null) { OidTreeNode refNode = resolvedOids.get(ref.getSymbol()); ref.resolve(refNode, this); finaltype = buildSyntaxes.get(refSymbol); } else { finaltype = _syntaxes.get(ref.getNode()); } } else if (finaltype instanceof TextualConvention) { TextualConvention temporary = (TextualConvention) finaltype; finaltype = temporary.getSyntax(); } else { finaltype = ((IndirectSyntax) finaltype).getSyntax(); } } if (finaltype != null) { try { tc = ((ProvidesTextualConvention)finaltype).getTextualConvention(hint, type); if (tc != null) { OidTreeNode node = resolvedOids.get(s); _syntaxes.put(node, tc); } } catch (Exception e) { System.out.println("Broken hint for textual convention " + s + ": " + hint); } } else { System.out.println("Invalid textual convention " + s + " " + attributes); } }); textualConventions = null; } private void sortdOids() { Set<Oid> sortedoid = new TreeSet<>(new Comparator<Oid>() { @Override public int compare(Oid o1, Oid o2) { try { int sorted = Integer.compare(o1.getPath(buildOids).size(), o2.getPath(buildOids).size()); if (sorted == 0) { sorted = Integer.compare(o1.hashCode(), o2.hashCode()); } return sorted; } catch (MibException e) { throw e.getNonChecked(); } } }); allOids.forEach( i-> { try { if (! i.getPath(buildOids).isEmpty()) { sortedoid.add(i); } } catch (MibException | MibException.NonCheckedMibException e) { logger.error("Can't add new OID %s: %s", i, e.getMessage()); try { if (! i.getPath(buildOids).isEmpty()) { sortedoid.add(i); } } catch (MibException e1) { logger.error("Second failure: can't add new OID %s: %s", i, e.getMessage()); } } }); allOids = sortedoid; } public Object[] parseIndexOID(int[] oid) { OidTreeNode found = top.search(oid); if(found == null) { return new Object[] {new OID(oid)}; } List<Object> parts = new ArrayList<Object>(); int[] foundOID = found.getElements(); parts.add(found.getSymbol()); //The full path was not found, try to resolve the left other if(foundOID.length < oid.length ) { OidTreeNode parent = top.find(Arrays.copyOf(foundOID, foundOID.length -1 )); if (parent != null) { ObjectType parentCodec = objects.get(parent); if(parentCodec.isIndexed()) { Index idx = parentCodec.getIndex(); int[] index = Arrays.copyOfRange(oid, foundOID.length, oid.length); Arrays.stream(idx.resolve(index, this)).forEach(i -> parts.add(i)); } } } return parts.toArray(new Object[parts.size()]); } public boolean containsKey(String text) { return names.containsKey(text); } public int[] getFromName(String text) { if (names.containsKey(text)) { for(OidTreeNode s: names.get(text)) { return s.getElements(); } } return null; } public String format(OID instanceOID, Variable variable) { OidTreeNode s = top.find(instanceOID.getValue()); if (s == null) { return null; } else if (buildTraps.containsKey(s)) { Map<String, Object> trap = buildTraps.get(s).get(variable.toInt()); if (trap == null) { return null; } else { trap.get("SYMBOL").toString(); } } else if (buildObjects.containsKey(s)) { ObjectType ot = objects.get(s); return ot.format(variable); } return null; } public Variable parse(OID instanceOID, String text) { OidTreeNode node = top.search(instanceOID.getValue()); if (node == null) { return null; } else if (syntaxes.containsKey(node)) { return syntaxes.get(node).parse(text); } return null; } }
package group7.anemone; import java.awt.geom.Point2D; import java.util.ArrayList; import processing.core.PApplet; public class Environment { PApplet parent; // God & clock needed for breeding every n generations private God god; private int tick = 0; private ArrayList<Agent> fishes; private ArrayList<Agent> sharks; private ArrayList<Food> food; private ArrayList<Collision> collisions; public Environment(PApplet p){ this.parent = p; this.god = new God(); this.fishes = new ArrayList<Agent>(); this.sharks = new ArrayList<Agent>(); this.food = new ArrayList<Food>(); } // Method to get all collisions that occurred in the environment public ArrayList<Collision> updateCollisions() { collisions = new ArrayList<Collision>(); for (Agent ag: fishes) { //for each agent, check for any collision for (Agent aa: fishes) { // check if collides to any other agent if(ag == aa) continue; if(ag.getCoordinates().distance(aa.getCoordinates()) <= 20){ collisions.add(new Collision(ag, aa)); } } for (Food fd: food) { //check collisions to food if(ag.getCoordinates().distance(fd.getCoordinates()) <= 12){ collisions.add(new Collision(ag, fd)); } } } return collisions; } public void updateAgentsSight() { //update what each agent can see for (Agent ag: fishes) { ArrayList<SightInformation> result = new ArrayList<SightInformation>(); //angle of the top and bottom of the agent's field of view double headBelow = ag.getViewHeading() - ag.getFOV(); double headAbove = ag.getViewHeading() + ag.getFOV(); //TODO: move this into method and perform for food, other agents and enemies //check for food within FOV for (Food fd : food) { //check if the food is within viewable distance double distance = ag.getCoordinates().distance(fd.getCoordinates()); if(distance <= ag.getVisionRange()){ //get angle of food in relation to agent double angleBetween = Math.atan((fd.getCoordinates().y - ag.getCoordinates().y) / (fd.getCoordinates().x - ag.getCoordinates().x)); angleBetween = angleBetween * 180 / Math.PI; //adjust angles depending on quadrant to be represented in 0-360 rather than -180-180 if(fd.getX() > ag.getX()) { if (fd.getY() < ag.getY()) angleBetween = 360 + angleBetween; }else{ if (fd.getY() >= ag.getY()) angleBetween = 180 + angleBetween; else angleBetween += 180; } //check if the food falls within field of view if(angleBetween >= headBelow && angleBetween <= headAbove){ result.add(new SightInformation(ag, fd, distance, (angleBetween - headBelow) / (ag.getFOV() * 2))); //special cases where field of view crosses 0/360 divide }else if(headBelow < 0){ if(angleBetween >= 360 + headBelow) result.add(new SightInformation(ag, fd, distance, ((angleBetween <= headAbove ? angleBetween + 360 : angleBetween ) - (360 + headBelow)) / (ag.getFOV() * 2))); }else if(headAbove > 360){ if(angleBetween <= headAbove - 360) result.add(new SightInformation(ag, fd, distance, ((angleBetween <= headAbove-360 ? angleBetween + 360 : angleBetween ) - headBelow) / (ag.getFOV() * 2))); } } } /* //check for other agents in FOV for (Agent fi : fishes) { double distance = ag.getCoordinates().distance(fi.getCoordinates()); if(distance <= ag.getVisionRange()){ double angleBetween = Math.atan((fi.getCoordinates().y - ag.getCoordinates().y) / (fi.getCoordinates().x - ag.getCoordinates().x)); angleBetween = angleBetween * 180 / Math.PI; if(fi.getX() > ag.getX()) { if (fi.getY() < ag.getY()) angleBetween = 360 + angleBetween; }else{ if (fi.getY() >= ag.getY()) angleBetween = 180 + angleBetween; else angleBetween += 180; } if(angleBetween >= headBelow && angleBetween <= headAbove){ result.add(new SightInformation(ag, fi, distance)); }else if(headBelow < 0){ if(angleBetween >= 360 + headBelow) result.add(new SightInformation(ag, fi, distance)); }else if(headAbove > 360){ if(angleBetween <= headAbove - 360) result.add(new SightInformation(ag, fi, distance)); } } } //check for other sharks in FOV for (Agent sh : sharks) { double distance = ag.getCoordinates().distance(sh.getCoordinates()); if(distance <= ag.getVisionRange()){ double angleBetween = Math.atan((sh.getCoordinates().y - ag.getCoordinates().y) / (sh.getCoordinates().x - ag.getCoordinates().x)); angleBetween = angleBetween * 180 / Math.PI; if(sh.getX() > ag.getX()) { if (sh.getY() < ag.getY()) angleBetween = 360 + angleBetween; }else{ if (sh.getY() >= ag.getY()) angleBetween = 180 + angleBetween; else angleBetween += 180; } if(angleBetween >= headBelow && angleBetween <= headAbove){ result.add(new SightInformation(ag, sh, distance)); }else if(headBelow < 0){ if(angleBetween >= 360 + headBelow) result.add(new SightInformation(ag, sh, distance)); }else if(headAbove > 360){ if(angleBetween <= headAbove - 360) result.add(new SightInformation(ag, sh, distance)); } } } */ //return updated list ag.updateCanSee(result); } } protected ArrayList<Collision> getCollisions(){ return collisions; } // Method to get collisions for a specific agent protected ArrayList<Collision> GetCollision(Agent agent) { ArrayList<Collision> result = new ArrayList<Collision>(); for (Collision cc: result) { if(cc.getAgent() == agent){ result.add(cc); } } return result; } protected void updateAllAgents(){ for (Agent fish: fishes) { //drawing the ikkle fishes fish.update(); } for (Agent shark:sharks) { shark.update(); } tick++; /* Method not implemented yet: if (tick % 5 == 0) { god.BreedPopulation(fishes); god.BreedPopulation(sharks); // Reset tick (in case of overflow) tick = 0; }*/ } protected void addFish(Point2D.Double coords){ fishes.add(new Agent(coords, parent)); } protected void addFish(Point2D.Double coords, int heading){ fishes.add(new Agent(coords, heading, parent)); } protected void addShark(Point2D.Double coords) { sharks.add(new Agent(coords, parent)); } void addFood(Point2D.Double coords){ food.add(new Food(coords)); } protected void removeAgent(Agent ag){ fishes.remove(ag); } protected void removeFood(Food fd){ food.remove(fd); } protected ArrayList<Agent> getAllFishes(){ return fishes; } protected ArrayList<Agent> getAllSharks() { return sharks; } protected ArrayList<Agent> getAllAgents() { // We know the clone of fishes will be of type ArrayList<Agent>, so this cast is safe. @SuppressWarnings("unchecked") ArrayList<Agent> all_agents = (ArrayList<Agent>) fishes.clone(); all_agents.addAll(sharks); return all_agents; } protected ArrayList<Food> getAllFood(){ return food; } }
package io.measures.passage; import com.google.common.base.Joiner; import io.measures.passage.geometry.Model3D; import io.measures.passage.geometry.Point2D; import io.measures.passage.geometry.Projectable2D; import io.measures.passage.geometry.Projectable3D; import io.measures.passage.geometry.Rect2D; import io.measures.passage.geometry.SphericalPoint; import io.measures.passage.geometry.Triangle3D; import processing.core.PApplet; import processing.core.PGraphics; import processing.core.PImage; import processing.event.KeyEvent; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * Sketch * @author Dietrich Featherston */ public class Sketch extends PApplet { protected final long startedAt = System.currentTimeMillis()/1000L; protected final String homeDir; protected final String baseDataDir; protected static final Joiner pathJoiner = Joiner.on(File.separatorChar); public final int slate = color(50); public final int gray = color(180); public final int yellow = color(255, 255, 1); public final int pink = color(255, 46, 112); public final int teal = color(85, 195, 194); public final int nak = color(0, 170, 255); public final int blue = color(49, 130, 189); public final int darkblue = color(49, 130, 189); public final int lightblue = color(222, 235, 247); public final int redorange = color(240, 59, 32); private PGraphics paperGraphics; protected boolean recordPdf = false; protected long pdfTime = 0L; private boolean saveAnimation = false; private int numAnimationFrames = -1; // save an unbounded number of frames public Sketch() { String homeDir = getParameter("PASSAGE_HOME"); String userDir = System.getProperty("user.dir"); if(homeDir == null) { homeDir = userDir; } this.homeDir = homeDir; baseDataDir = getParameter("PASSAGE_DATA") == null ? homeDir : getParameter("PASSAGE_DATA"); // ensure the snapshot directory exists new File(getSnapshotDir()).mkdirs(); // ensure the data dir exists new File(getDataDir()).mkdirs(); } public void initSize(String type) { size(getTargetWidth(), getTargetHeight(), type); } public int getTargetWidth() { return 1280; } public int getTargetHeight() { return 720; } public float getAspectRatio() { return (float)getTargetWidth() / (float)getTargetHeight(); } public void saveAnimation() { this.saveAnimation = true; } public void animationFrames(int n) { numAnimationFrames = n; } @Override public final void draw() { beforeFrame(); try { renderFrame(); } catch(Exception e) { println(e.getMessage()); } finally { afterFrame(); } } public void beforeFrame() { if(recordPdf) { beginRaw(PDF, getSnapshotPath("vector-" + pdfTime + ".pdf")); } } public void renderFrame() { println("ERROR - sketch renderFrame() not implemented"); noLoop(); } public void afterFrame() { if(recordPdf) { endRaw(); recordPdf = false; } if(saveAnimation) { saveFrame(getSnapshotPath("frames-" + startedAt + "/frame- if(numAnimationFrames > 0 && frameCount >= numAnimationFrames) { exit(); } } } public int darker(int c) { return color(round(red(c)*0.6f), round(green(c)*0.6f), round(blue(c)*0.6f)); } public int lighter(int c) { return color( constrain(round(red(c)*1.1f), 0, 255), constrain(round(green(c)*1.1f), 0, 255), constrain(round(blue(c)*1.1f), 0, 255)); } public void point(Projectable2D p) { point(p.x(), p.y()); } public void points(Iterable<? extends Projectable2D> points) { for(Projectable2D p : points) { point(p); } } public void point(Projectable3D p) { point(p.x(), p.y(), p.z()); } public void vertex(Projectable3D p) { vertex(p.x(), p.y(), p.z()); } public void vertex(Projectable2D p) { vertex(p.x(), p.y()); } public void line(Projectable3D a, Projectable3D b) { line(a.x(), a.y(), a.z(), b.x(), b.y(), b.z()); } public void line(Projectable2D a, Projectable2D b) { line(a.x(), a.y(), b.x(), b.y()); } public Rect2D viewport() { return new Rect2D(new Point2D(0, 0), width, height); } public void renderModel(Model3D model) { beginShape(TRIANGLES); for(Triangle3D t : model.getTriangles()) { vertex(t.a()); vertex(t.b()); vertex(t.c()); } endShape(); } public void triangle(Triangle3D t) { beginShape(TRIANGLE); vertex(t.a()); vertex(t.b()); vertex(t.c()); endShape(); } public void translate(Projectable2D p) { translate(p.x(), p.y()); } public void translate(Projectable3D p) { translate(p.x(), p.y(), p.z()); } public void translateNormal(SphericalPoint p) { rotateZ(p.phi()); rotateY(p.theta()); translate(0, 0, p.r()); } public static float dist(Projectable2D p) { return dist(p.x(), p.y(), 0, 0); } public static float dist(Projectable2D a, Projectable2D b) { return dist(a.x(), a.y(), b.x(), b.y()); } public static float dist(Projectable3D a, Projectable3D b) { return dist(a.x(), a.y(), a.z(), b.x(), b.y(), b.z()); } public float noiseZ(float noiseScale, float x, float y, float z) { return noise(noiseScale*(x+10000), noiseScale*(y+10000), noiseScale*(z+10000)); } @Override public void keyPressed(KeyEvent e) { super.keyPressed(); if(key == ' ') { // snapshot raster graphics + code snapshot(); } else if(key == 'p') { // snapshot a pdf + code recordPdf = true; pdfTime = now(); snapshotCode(pdfTime); } } public long now() { return System.currentTimeMillis()/1000; } public void snapshot() { long time = now(); snapshotCode(time); snapshotFrame(time); } public void snapshotCode() { snapshotCode(startedAt); } public void snapshotCode(long time) { println("taking code snapshot"); copyFile(getSketchSourceFile(), getSnapshotPath("code-" + time + ".java")); } public void snapshotFrame() { snapshotFrame(now()); } public void snapshotFrame(long time) { println("taking raster snapshot"); saveFrame(getSnapshotPath("raster-" + time + ".jpg")); } // todo - compatibility public void copyFile(String from, String to) { try { String command = "cp " + from + " " + to; Process p = Runtime.getRuntime().exec(command); copy(p.getInputStream(), System.out); copy(p.getErrorStream(), System.err); } catch(Exception ignored) { println(ignored.getMessage()); ignored.printStackTrace(); } } public void copy(InputStream in, OutputStream out) throws IOException { while (true) { int c = in.read(); if (c == -1) break; out.write((char)c); } } public String getSketchSourceFile() { return pathJoiner.join(getSketchSourcePath(), getSketchPathComponent() + ".java"); } private String getSketchSourcePath() { return pathJoiner.join(homeDir, "src/main/java"); } public String getSketchPathComponent() { return this.getClass().getName().replace('.', File.separatorChar); } /** * @return the directory to which progress artifacts should be saved */ public String getSnapshotDir() { return pathJoiner.join(baseDataDir, getSketchPathComponent(), "snapshots"); } public String getSnapshotPath(String name) { return pathJoiner.join(getSnapshotDir(), name); } public String getDataDir() { return pathJoiner.join(baseDataDir, getSketchPathComponent(), "data"); } public String getDataPath(String name) { return pathJoiner.join(getDataDir(), name); } public String getHomeDir() { return homeDir; } public String getHomePath(String name) { return pathJoiner.join(getHomeDir(), name); } public static void fit(PImage img, int maxWidth, int maxHeight) { // oblig image resizing to fit in our space float imgratio = (float)img.width / (float)img.height; if(img.width > img.height) { img.resize(round(imgratio * maxHeight), maxHeight); } else { img.resize(maxWidth, round(maxWidth/imgratio)); } } public void fit(PImage img) { if((img.width > width) || (img.height > height)) { if(((float) img.width / (float)img.height) > ((float) width / (float) height)) { img.resize(width, 0); } else { img.resize(0, height); } } } @Override public File dataFile(String where) { File why = new File(where); if (why.isAbsolute()) return why; File sketchSpecificFile = new File(getDataPath(where)); if(sketchSpecificFile.exists()) { return sketchSpecificFile; } else { File f = new File(pathJoiner.join(baseDataDir, "data", where)); if(f.exists()) { return f; } } return why; } @Override public String getParameter(String name) { return System.getenv(name); } public void printenv() { System.out.println("sketch name: " + this.getClass().getName()); System.out.println("PASSAGE_HOME=" + homeDir); System.out.println("PASSAGE_DATA=" + baseDataDir); System.out.println("sketch-specific path = " + getSketchPathComponent()); System.out.println("sketch source = " + getSketchSourcePath()); System.out.println("sketch source file = " + getSketchSourceFile()); System.out.println("snapshot dir = " + getSnapshotDir()); } public void oldPaperBackground() { if(paperGraphics == null) { int center = color(252, 243, 211); int edge = color(245, 222, 191); PGraphics g = createGraphics(10, 10); g.beginDraw(); g.noStroke(); g.background(edge); g.fill(center); g.ellipse(g.width/2, g.height/2, g.width*0.8f, g.height*0.8f); g.filter(BLUR, 2); g.endDraw(); /* g.filter(BLUR, width/30); g.filter(BLUR, width/30); g.filter(BLUR, width/30); */ paperGraphics = g; } } }
package jwebform.element; import jwebform.element.structure.Element; import jwebform.element.structure.ElementResult; import jwebform.element.structure.HTMLProducer; import jwebform.element.structure.OneFieldDecoration; import jwebform.element.structure.OneValueElementProcessor; import jwebform.element.structure.StandardElementRenderer; import jwebform.element.structure.StaticElementInfo; import jwebform.env.Env.EnvWithSubmitInfo; import jwebform.validation.Validator; import jwebform.view.Tag; public class TextInput implements Element { public final static String KEY = "jwebform.element.TextInput"; final private String name; final private String initialValue; final private Validator validator; final public OneFieldDecoration decoration; public TextInput(String name, OneFieldDecoration decoration, String initialValue, Validator validator) { this.name = name; this.validator = validator; this.initialValue = initialValue; this.decoration = decoration; } @Override public ElementResult prepare(EnvWithSubmitInfo env) { OneValueElementProcessor oneValueElement = new OneValueElementProcessor(); return oneValueElement.calculateElementResult(env, name, initialValue, validator, new StaticElementInfo(name, getDefault(), 1, KEY), this, t -> true); } // very simple version! protected HTMLProducer getDefault() { return producerInfos -> { StandardElementRenderer renderer = new StandardElementRenderer(); String errorMessage = renderer.generateErrorMessage(producerInfos); Tag inputTag = renderer.generateInputTag(producerInfos, "text", "input"); String html = decoration.getLabel() + errorMessage + inputTag.getStartHtml(); return html; }; } @Override public String toString() { return String.format("TextInput. name=%s", name); } }
package logbook.internal.gui; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.nio.file.Files; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.StringJoiner; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.imageio.ImageIO; import org.controlsfx.control.Notifications; import javafx.beans.property.ObjectProperty; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.embed.swing.SwingFXUtils; import javafx.event.EventHandler; import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.SnapshotParameters; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.ButtonType; import javafx.scene.control.SplitPane; import javafx.scene.control.SplitPane.Divider; import javafx.scene.control.TableColumn; import javafx.scene.control.TableColumn.SortType; import javafx.scene.control.TableColumnBase; import javafx.scene.control.TableView; import javafx.scene.control.TextArea; import javafx.scene.control.TreeTableColumn; import javafx.scene.control.TreeTableView; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.image.WritableImage; import javafx.scene.input.Clipboard; import javafx.scene.input.ClipboardContent; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.paint.Color; import javafx.stage.FileChooser; import javafx.stage.FileChooser.ExtensionFilter; import javafx.stage.Stage; import javafx.stage.Window; import javafx.stage.WindowEvent; import javafx.util.Duration; import logbook.bean.AppConfig; import logbook.bean.WindowLocation; import logbook.internal.log.LogWriter; import logbook.plugin.PluginServices; /** * JavaFx Tools * */ public class Tools { /** * window * */ public static class Windows { /** * * @param stage Stage * @throws IOException */ public static void setIcon(Stage stage) throws IOException { String[] uris = { "logbook/gui/icon_256x256.png", "logbook/gui/icon_128x128.png", "logbook/gui/icon_64x64.png", "logbook/gui/icon_48x48.png", "logbook/gui/icon_32x32.png", "logbook/gui/icon_16x16.png" }; for (String uri : uris) { try (InputStream is = PluginServices.getResourceAsStream(uri)) { stage.getIcons().add(new Image(is)); } } } /** * * @param controller WindowController */ public static void defaultCloseAction(WindowController controller) { this.defaultCloseAction(controller, null); } /** * * @param controller WindowController * @param subkey String */ public static void defaultCloseAction(WindowController controller, String subkey) { if (controller.getWindow() != null) { EventHandler<WindowEvent> action = e -> { String key = controller.getClass().getCanonicalName()+ Optional.ofNullable(subkey).map(str -> "#"+ str).orElse(""); AppConfig.get() .getWindowLocationMap() .put(key, controller.getWindowLocation()); }; controller.getWindow() .addEventHandler(WindowEvent.WINDOW_HIDDEN, action); } } /** * * @param controller WindowController */ public static void defaultOpenAction(WindowController controller) { this.defaultOpenAction(controller, null); } /** * * @param controller WindowController * @param subkey String */ public static void defaultOpenAction(WindowController controller, String subkey) { String key = controller.getClass().getCanonicalName() + Optional.ofNullable(subkey).map(str -> "#"+ str).orElse(""); WindowLocation location = AppConfig.get() .getWindowLocationMap() .get(key); controller.setWindowLocation(location); } } /** * misc * */ public static class Conrtols { /** * PNG * * @param node * @param title * @param own */ public static void storeSnapshot(Node node, String title, Window own) { try { FileChooser chooser = new FileChooser(); chooser.setTitle(title + ""); chooser.setInitialFileName(title + ".png"); chooser.getExtensionFilters().addAll( new ExtensionFilter("PNG Files", "*.png")); File f = chooser.showSaveDialog(own); if (f != null) { SnapshotParameters sp = new SnapshotParameters(); sp.setFill(Color.WHITESMOKE); WritableImage image = node.snapshot(sp, null); try (OutputStream out = Files.newOutputStream(f.toPath())) { ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", out); } } } catch (Exception e) { alert(AlertType.WARNING, "", "", e, own); } } /** * * * @param type * @param title * @param message * @param own * @return */ public static Optional<ButtonType> alert(AlertType type, String title, String message, Window own) { return alert(type, title, message, (Node) null, own); } /** * () * * @param type * @param title * @param message * @param t * @param own * @return */ public static Optional<ButtonType> alert(AlertType type, String title, String message, Throwable t, Window own) { StringWriter w = new StringWriter(); t.printStackTrace(new PrintWriter(w)); String stackTrace = w.toString(); TextArea textArea = new TextArea(stackTrace); return alert(type, title, message, textArea, own); } /** * * * @param type * @param title * @param message * @param content * @param own * @return */ public static Optional<ButtonType> alert(AlertType type, String title, String message, Node content, Window own) { Alert alert = new Alert(type); alert.getDialogPane().getStylesheets().add("logbook/gui/application.css"); InternalFXMLLoader.setGlobal(alert.getDialogPane()); alert.initOwner(own); alert.setTitle(title); alert.setContentText(message); alert.getDialogPane().setExpandableContent(content); return alert.showAndWait(); } /** * * * @param node * @param title * @param message */ public static void showNotify(Node node, String title, String message) { showNotify(node, title, message, Duration.seconds(5)); } /** * * * @param node * @param title * @param message * @param hide */ public static void showNotify(Node node, String title, String message, Duration hide) { showNotify(node, title, message, hide, Optional.ofNullable(AppConfig.get().getToastLocation()).map(Pos::valueOf).orElse(Pos.BOTTOM_RIGHT)); } /** * * * @param node * @param title * @param message * @param hide * @param pos */ public static void showNotify(Node node, String title, String message, Duration hide, Pos position) { Notifications notifications = Notifications.create() .graphic(node) .title(title) .text(message) .hideAfter(hide) .position(position); if (node == null) { notifications.showInformation(); } else { notifications.show(); } } /** * * @param view {@link ImageView} * @return {@link ImageView} */ public static ImageView zoomImage(ImageView view) { int percent = AppConfig.get().getImageZoomRate(); if (percent != 100 && percent > 0) { double rate = (double) percent / 100; view.setFitHeight(view.getImage().getHeight() * rate); view.setFitWidth(view.getImage().getWidth() * rate); } return view; } /** * SplitPane * * @param pane SplitPane * @param key SplitPane */ public static void setSplitWidth(SplitPane pane, String key) { Double position = AppConfig.get().getDividerPositionMap() .get(key); Iterator<Divider> ite = pane.getDividers() .iterator(); if (ite.hasNext()) { Divider divider = ite.next(); if (position != null) { divider.setPosition(position); } divider.positionProperty().addListener((ob, o, n) -> { AppConfig.get().getDividerPositionMap().put(key, n.doubleValue()); }); } } } public static class TablesTreesBase { /** * * @param table * @param key */ public static <S> void setWidth(Supplier<Stream<? extends TableColumnBase<S, ?>>> columns, String key) { Map<String, Double> setting = AppConfig.get() .getColumnWidthMap() .get(key); if (setting != null) { columns.get().forEach(column -> { Double width = setting.get(getColumnName(column)); if (width != null) { column.setPrefWidth(width); } }); } columns.get().forEach(column -> { column.widthProperty().addListener((ob, o, n) -> { Map<String, Double> map = AppConfig.get() .getColumnWidthMap() .computeIfAbsent(key, e -> new HashMap<>()); map.put(getColumnName(column), n.doubleValue()); }); }); } public interface AbstractTable<S, C extends TableColumnBase<?, ?>> { public Stream<C> getColumns(); public ObservableList<C> getSortOrder(); public String getSortType(C column); public void setSortType(C column, String type); public ObjectProperty<?> sortTypeProperty(C column); } public static class TableWrapper<S> implements AbstractTable<S, TableColumn<S, ?>> { private final TableView<S> table; TableWrapper(TableView<S> table) { this.table = table; } @Override public Stream<TableColumn<S, ?>> getColumns() { return Tables.getColumns(this.table); } @Override public ObservableList<TableColumn<S, ?>> getSortOrder() { return this.table.getSortOrder(); } @Override public void setSortType(TableColumn<S, ?> column, String type) { column.setSortType(SortType.valueOf(type)); } @Override public ObjectProperty<?> sortTypeProperty(TableColumn<S, ?> column) { return column.sortTypeProperty(); } @Override public String getSortType(TableColumn<S, ?> column) { return column.getSortType().name(); } } public static class TreeWrapper<S> implements AbstractTable<S, TreeTableColumn<S, ?>> { private final TreeTableView<S> tree; TreeWrapper(TreeTableView<S> table) { this.tree = table; } @Override public Stream<TreeTableColumn<S, ?>> getColumns() { return Trees.getColumns(this.tree); } @Override public ObservableList<TreeTableColumn<S, ?>> getSortOrder() { return this.tree.getSortOrder(); } @Override public String getSortType(TreeTableColumn<S, ?> column) { return column.getSortType().name(); } @Override public void setSortType(TreeTableColumn<S, ?> column, String type) { column.setSortType(TreeTableColumn.SortType.valueOf(type)); } @Override public ObjectProperty<?> sortTypeProperty(TreeTableColumn<S, ?> column) { return column.sortTypeProperty(); } } /** * * @param table * @param key */ public static <S, C extends TableColumnBase<?, ?>> void setSortOrder(AbstractTable<S, C> table, String key) { Map<String, String> setting = AppConfig.get() .getColumnSortOrderMap() .get(key); ObservableList<C> sortOrder = table.getSortOrder(); if (setting != null) { Map<String, C> columnsMap = table.getColumns() .collect(Collectors.toMap(Tables::getColumnName, c -> c, (c1, c2) -> c1)); setting.forEach((k, v) -> { Optional.ofNullable(columnsMap.get(k)).ifPresent(col -> { sortOrder.add(col); table.setSortType(col, v); }); }); } sortOrder.addListener((ListChangeListener<C>) e -> storeSortOrder(table, key)); table.getColumns().forEach(col -> { table.sortTypeProperty(col).addListener((ob, o, n) -> storeSortOrder(table, key)); }); } private static <S, C extends TableColumnBase<?, ?>> void storeSortOrder(AbstractTable<S, C> table, String key) { ObservableList<C> sortOrder = table.getSortOrder(); Map<String, String> setting = AppConfig.get() .getColumnSortOrderMap() .computeIfAbsent(key, e1 -> new LinkedHashMap<>()); setting.clear(); sortOrder.stream().forEach(col -> setting.put(getColumnName(col), table.getSortType(col))); } /** * TableColumn * @param column TableColumn * @return TableColumn */ public static String getColumnName(TableColumnBase<?, ?> column) { LinkedList<String> names = null; TableColumnBase<?, ?> parent = column; while ((parent = parent.getParentColumn()) != null) { if (names == null) { names = new LinkedList<>(); } names.addFirst(parent.getText()); } if (names != null) { return names.stream().collect(Collectors.joining(".")) + "." + column.getText(); } else { return column.getText(); } } } /** * TableView * */ public static class Tables extends TablesTreesBase { private static final String SEPARATOR = "\t"; //$NON-NLS-1$ private static final String NL = "\n"; //$NON-NLS-1$ private static final String CSV_SEPARATOR = ","; //$NON-NLS-1$ private static final String CSV_NL = "\r\n"; //$NON-NLS-1$ /** * * * @param table * @param rows * @return */ public static <T> String toString(TableView<?> table, List<?> rows) { String body = rows.stream() .map(Object::toString) .collect(Collectors.joining(NL)); return new StringJoiner(NL).add(tableHeader(table, SEPARATOR)) .add(body) .toString(); } /** * * * @param table * @return */ public static String selectionToString(TableView<?> table) { return toString(table, table.getSelectionModel() .getSelectedItems()); } /** * * * @param table */ public static void selectionCopy(TableView<?> table) { ClipboardContent content = new ClipboardContent(); content.putString(selectionToString(table)); Clipboard.getSystemClipboard() .setContent(content); } /** * * * @param table */ public static void selectAll(TableView<?> table) { // Selection All table.getSelectionModel() .selectAll(); } /** * (Ctrl+C) * * @param event */ public static void defaultOnKeyPressedHandler(KeyEvent event) { if (event.getSource() instanceof TableView<?>) { TableView<?> table = (TableView<?>) event.getSource(); // Copy if (event.isControlDown() && event.getCode() == KeyCode.C) { selectionCopy(table); } } } /** * CSV * * @param table * @param title * @param own */ public static void store(TableView<?> table, String title, Window own) throws IOException { String body = table.getItems() .stream() .map(Object::toString) .collect(Collectors.joining(CSV_NL)) .replaceAll(SEPARATOR, CSV_SEPARATOR); String content = new StringJoiner(CSV_NL) .add(tableHeader(table, CSV_SEPARATOR)) .add(body) .toString(); FileChooser chooser = new FileChooser(); chooser.setTitle(title + ""); chooser.setInitialFileName(title + ".csv"); chooser.getExtensionFilters().addAll( new ExtensionFilter("CSV Files", "*.csv")); File f = chooser.showSaveDialog(own); if (f != null) { Files.write(f.toPath(), content.getBytes(LogWriter.DEFAULT_CHARSET)); } } /** * * @param table * @param key * @param window * @throws IOException */ public static void showVisibleSetting(TableView<?> table, String key, Stage window) throws IOException { InternalFXMLLoader.showWindow("logbook/gui/column_visible.fxml", window, "", w -> { ((ColumnVisibleController) w).setData(table, key); }, null); } /** * * @param table * @param key */ public static void setVisible(TableView<?> table, String key) { Set<String> setting = AppConfig.get() .getColumnVisibleMap() .get(key); if (setting != null) { getColumns(table).forEach(column -> { if (setting.contains(getColumnName(column))) { column.setVisible(false); } }); } } /** * * @param table * @param key */ public static void setWidth(TableView<?> table, String key) { TablesTreesBase.setWidth(() -> getColumns(table), key); } /** * * @param table * @param key */ public static <S> void setSortOrder(TableView<S> table, String key) { TablesTreesBase.setSortOrder(new TableWrapper<S>(table), key); } /** * TableViewTableColumn * @param table TableView * @return TableColumn */ public static <S> Stream<TableColumn<S, ?>> getColumns(TableView<S> table) { return table.getColumns() .stream() .flatMap(Tables::flatColumns); } private static String tableHeader(TableView<?> table, String separator) { return getColumns(table) .map(Tables::getColumnName) .filter(name -> !name.equals("")) .collect(Collectors.joining(separator)); } /** * TableColumnTableColumn * @param column TableColumn * @return TableColumn */ private static <S> Stream<TableColumn<S, ?>> flatColumns(TableColumn<S, ?> column) { if (!column.getColumns().isEmpty()) { return column.getColumns().stream() .flatMap(Tables::flatColumns); } return Stream.of(column); } } public static class Trees extends TablesTreesBase { /** * * @param table * @param key */ public static void setWidth(TreeTableView<?> tree, String key) { TablesTreesBase.setWidth(() -> getColumns(tree), key); } /** * * @param table * @param key */ public static <S> void setSortOrder(TreeTableView<S> table, String key) { TablesTreesBase.setSortOrder(new TreeWrapper<S>(table), key); } /** * TreeTableViewTreeTableColumn * @param tree TreeTableView * @return TreeTableColumn */ public static <S> Stream<TreeTableColumn<S, ?>> getColumns(TreeTableView<S> tree) { return tree.getColumns().stream(); } } }
package mho.qbar.objects; import mho.wheels.iterables.IterableUtils; import mho.wheels.iterables.RandomProvider; import mho.wheels.math.MathUtils; import mho.wheels.structures.Pair; import org.jetbrains.annotations.NotNull; import java.math.BigInteger; import java.util.*; import static mho.wheels.testing.Testing.*; /** * <p>The {@code Algebraic} class uniquely represents real algebraic numbers.</p> * * <p>There is only one instance of {@code ZERO} and one instance of {@code ONE}, so these may be compared with other * {@code Algebraic}s using {@code ==}.</p> * * <p>This class is immutable.</p> */ public class Algebraic { public static final @NotNull Algebraic ZERO = new Algebraic(Rational.ZERO); public static final @NotNull Algebraic ONE = new Algebraic(Rational.ONE); public static final @NotNull Algebraic TEN = new Algebraic(Rational.TEN); public static final @NotNull Algebraic TWO = new Algebraic(Rational.TWO); public static final @NotNull Algebraic NEGATIVE_ONE = new Algebraic(Rational.NEGATIVE_ONE); public static final @NotNull Algebraic ONE_HALF = new Algebraic(Rational.ONE_HALF); public static final @NotNull Algebraic PHI = of(Polynomial.read("x^2-x-1").get(), 1); private final int rootIndex; private final @NotNull Polynomial minimalPolynomial; private final @NotNull Optional<Rational> rational; private final @NotNull Interval isolatingInterval; private final int mpRootCount; private Algebraic( @NotNull Polynomial minimalPolynomial, int rootIndex, @NotNull Interval isolatingInterval, int mpRootCount ) { this.rootIndex = rootIndex; this.minimalPolynomial = minimalPolynomial; rational = Optional.empty(); this.isolatingInterval = isolatingInterval; this.mpRootCount = mpRootCount; } private Algebraic(@NotNull Rational rational) { rootIndex = 0; minimalPolynomial = Polynomial.fromRoot(rational); this.rational = Optional.of(rational); isolatingInterval = Interval.of(rational); mpRootCount = 1; } public static @NotNull Algebraic of(@NotNull Polynomial polynomial, int rootIndex) { if (rootIndex < 0) { throw new IllegalArgumentException(); } if (polynomial == Polynomial.ZERO) { throw new IllegalArgumentException(); } if (polynomial.degree() == 1) { if (rootIndex != 0) { throw new IllegalArgumentException(); } return new Algebraic(Rational.of(polynomial.coefficient(0).negate(), polynomial.coefficient(1))); } polynomial = polynomial.squareFreePart(); if (polynomial == Polynomial.ONE) { throw new IllegalArgumentException(); } int rootCount = polynomial.rootCount(); if (rootIndex >= rootCount) { throw new IllegalArgumentException(); } List<Polynomial> factors = polynomial.factor(); if (factors.size() == 1) { return new Algebraic(polynomial, rootIndex, polynomial.powerOfTwoIsolatingInterval(rootIndex), rootCount); } List<Pair<Polynomial, Integer>> polyRootPairs = new ArrayList<>(); List<Real> realRoots = new ArrayList<>(); List<Interval> isolatingIntervals = new ArrayList<>(); List<Integer> rootCounts = new ArrayList<>(); for (Polynomial factor : factors) { List<Interval> factorIsolatingIntervals = factor.powerOfTwoIsolatingIntervals(); int factorRootCount = factor.rootCount(); for (int i = 0; i < factorRootCount; i++) { polyRootPairs.add(new Pair<>(factor, i)); realRoots.add(Real.root(factor::signum, factorIsolatingIntervals.get(i))); isolatingIntervals.add(factorIsolatingIntervals.get(i)); rootCounts.add(factorRootCount); } } Interval isolatingInterval = polynomial.isolatingInterval(rootIndex); int matchIndex = Real.root(polynomial::signum, isolatingInterval).match(realRoots); Pair<Polynomial, Integer> pair = polyRootPairs.get(matchIndex); polynomial = pair.a; rootIndex = pair.b; if (polynomial.degree() == 1) { if (rootIndex != 0) { throw new IllegalArgumentException(); } return new Algebraic(Rational.of(polynomial.coefficient(0).negate(), polynomial.coefficient(1))); } return new Algebraic(pair.a, pair.b, isolatingIntervals.get(matchIndex), rootCounts.get(matchIndex)); } public @NotNull Algebraic of(@NotNull Rational rational) { return new Algebraic(rational); } public @NotNull Real realValue() { if (rational.isPresent()) { return Real.of(rational.get()); } else { return Real.root(minimalPolynomial::signum, isolatingInterval); } } @Override public boolean equals(Object that) { if (this == that) return true; if (that == null || getClass() != that.getClass()) return false; Algebraic algebraic = (Algebraic) that; if (rational.isPresent() != algebraic.rational.isPresent()) return false; if (rational.isPresent()) { return rational.get().equals(algebraic.rational.get()); } else { return rootIndex == algebraic.rootIndex && minimalPolynomial.equals(algebraic.minimalPolynomial); } } @Override public int hashCode() { if (rational.isPresent()) { return 31 + rational.get().hashCode(); } else { return 31 * rootIndex + minimalPolynomial.hashCode(); } } public @NotNull String toString() { if (rational.isPresent()) { return rational.get().toString(); } else { if (minimalPolynomial.degree() == 2) { BigInteger a = minimalPolynomial.coefficient(2); BigInteger b = minimalPolynomial.coefficient(1); BigInteger c = minimalPolynomial.coefficient(0); BigInteger discriminant = b.pow(2).subtract(a.multiply(c).shiftLeft(2)); if (discriminant.bitLength() < 32) { BigInteger beforeRadical = MathUtils.largestPerfectPowerFactor(2, discriminant); BigInteger underRadical = discriminant.divide(beforeRadical.pow(2)); BigInteger denominator = a.shiftLeft(1); BigInteger gcd = MathUtils.gcd(Arrays.asList(beforeRadical, denominator, b)); beforeRadical = beforeRadical.divide(gcd); BigInteger constant = b.divide(gcd).negate(); denominator = denominator.divide(gcd); boolean nonTrivialBeforeRadical = !beforeRadical.equals(BigInteger.ONE); boolean nonTrivialConstant = !constant.equals(BigInteger.ZERO); boolean nonTrivialDenominator = !denominator.equals(BigInteger.ONE); StringBuilder sb = new StringBuilder(); if (nonTrivialDenominator) { sb.append('('); } if (nonTrivialConstant) { sb.append(constant); } if (rootIndex == 0) { sb.append('-'); } else if (nonTrivialConstant) { sb.append('+'); } if (nonTrivialBeforeRadical) { sb.append(beforeRadical).append('*'); } sb.append("sqrt(").append(underRadical).append(')'); if (nonTrivialDenominator) { sb.append(")/").append(denominator); } return sb.toString(); } } return "root " + rootIndex + " of " + minimalPolynomial; } } /** * Ensures that {@code this} is valid. Must return without exceptions for any {@code Algebraic} used outside this * class. */ public void validate() { if (rational.isPresent()) { assertEquals(this, rootIndex, 0); assertEquals(this, minimalPolynomial, Polynomial.fromRoot(rational.get())); assertEquals(this, isolatingInterval, Interval.of(rational.get())); assertEquals(this, mpRootCount, 0); } else { assertTrue(this, minimalPolynomial.degree() > 1); assertTrue(this, minimalPolynomial.isIrreducible()); assertTrue(this, rootIndex >= 0); assertTrue(this, rootIndex < minimalPolynomial.rootCount()); assertEquals(this, isolatingInterval, minimalPolynomial.powerOfTwoIsolatingInterval(rootIndex)); assertEquals(this, mpRootCount, minimalPolynomial.rootCount()); } if (equals(ZERO)) { assertTrue(this, this == ZERO); } if (equals(ONE)) { assertTrue(this, this == ONE); } } }
package net.towerwarz; import net.towerwarz.exception.UnknownObjectException; import java.util.Arrays; /** * This file is the init file and contains functions to set and retrieve certain game properties */ public class GameInstance { private int WaveNumber; private String difficulty; private String MapName; private String[] maps = { "GrassLands", "HellWorld", "IceLand", "DarkForest" }; private String[] difficulties = { "Easy", "Normal", "Hard", "Sparta" }; public String setDifficulty(String diff) throws UnknownObjectException { if (Arrays.asList(difficulties).contains(diff)) { // Check if the difficulty is valid difficulty = diff; // Set difficulty } else { throw new UnknownObjectException("Invalid difficulty"); } return difficulty; } public String getDifficulty() { return difficulty; } public String setMap(String map) throws UnknownObjectException { if (Arrays.asList(maps).contains(map)) { MapName = map; } else { throw new UnknownObjectException("Invalid map"); } return MapName; } public String getMapName() { return MapName; } public int getWaveNumber() { return WaveNumber; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package qa.qcri.aidr.predictui.util; import java.io.Serializable; import java.util.List; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import com.fasterxml.jackson.annotation.JsonInclude; import qa.qcri.aidr.dbmanager.dto.CrisisAttributesDTO; import qa.qcri.aidr.dbmanager.dto.CrisisDTO; import qa.qcri.aidr.dbmanager.dto.CrisisTypeDTO; import qa.qcri.aidr.dbmanager.dto.DocumentDTO; import qa.qcri.aidr.dbmanager.dto.ModelDTO; import qa.qcri.aidr.dbmanager.dto.ModelFamilyDTO; import qa.qcri.aidr.dbmanager.dto.ModelNominalLabelDTO; import qa.qcri.aidr.dbmanager.dto.NominalAttributeDTO; import qa.qcri.aidr.dbmanager.dto.NominalLabelDTO; import qa.qcri.aidr.dbmanager.dto.taggerapi.ModelHistoryWrapper; import qa.qcri.aidr.dbmanager.dto.taggerapi.ModelWrapper; import qa.qcri.aidr.dbmanager.dto.taggerapi.TaggersForCodes; import qa.qcri.aidr.dbmanager.entities.model.ModelNominalLabel; import qa.qcri.aidr.predictui.dto.TrainingDataDTO; import qa.qcri.aidr.predictui.entities.AidrCollection; /** * * @author Muhammad Imran */ @XmlRootElement(name = "responseWrapper") @JsonInclude(JsonInclude.Include.NON_DEFAULT) public class ResponseWrapper implements Serializable { private static final long serialVersionUID = 1L; @XmlElement protected String statusCode; @XmlElement protected String message; @XmlElement protected Object dataObject; @XmlElement private List<CrisisTypeDTO> crisisTypes; @XmlElement private List<CrisisDTO> crisises; @XmlElement private List<NominalLabelDTO> nominalLabels; @XmlElement private List<NominalAttributeDTO> nominalAttributes; @XmlElement private List<ModelDTO> models; @XmlElement private List<DocumentDTO> documents; @XmlElement private List<ModelFamilyDTO> modelFamilies; @XmlElement private List<ModelNominalLabel> modelNominalLabels; @XmlElement private List<ModelNominalLabelDTO> modelNominalLabelsDTO; @XmlElement private List<AidrCollection> collections; @XmlElement private List<ModelWrapper> modelWrapper; @XmlElement private List<ModelHistoryWrapper> modelHistoryWrapper; @XmlElement private List<TaggersForCodes> taggersForCodes; @XmlElement private List<CrisisAttributesDTO> crisisAttributes; @XmlElement private List<TrainingDataDTO> trainingData; @XmlElement private Integer total; @XmlElement private Long entityID; // use this field to send IDs to manager public ResponseWrapper(String statusCode, String message) { this.statusCode = statusCode; this.message = message; } public ResponseWrapper(String statusCode) { this.statusCode = statusCode; } public ResponseWrapper(String statusCode, Object obj) { this.statusCode = statusCode; } public ResponseWrapper(String statusCode, String message, Object obj) { this.statusCode = statusCode; this.message = message; this.dataObject = obj; } public ResponseWrapper() { } public String getStatusCode() { return statusCode; } /** * @param statusCode the statusCode to set */ public void setStatusCode(String statusCode) { this.statusCode = statusCode; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } /** * @return the dataObject */ public Object getDataObject() { return dataObject; } /** * @param dataObject the dataObject to set */ public void setDataObject(Object dataObject) { this.dataObject = dataObject; } /** * @return the crisisTypes */ public List<CrisisTypeDTO> getCrisisTypes() { return crisisTypes; } /** * @param crisisTypes the crisisTypes to set */ public void setCrisisTypes(List<CrisisTypeDTO> crisisTypes) { this.crisisTypes = crisisTypes; } /** * @return the crisises */ public List<CrisisDTO> getCrisises() { return crisises; } /** * @param crisises the crisises to set */ public void setCrisises(List<CrisisDTO> crisises) { this.crisises = crisises; } /** * @return the nominalLabels */ public List<NominalLabelDTO> getNominalLabels() { return nominalLabels; } /** * @param nominalLabels the nominalLabels to set */ public void setNominalLabels(List<NominalLabelDTO> nominalLabels) { this.nominalLabels = nominalLabels; } /** * @return the nominalAttributes */ public List<NominalAttributeDTO> getNominalAttributes() { return nominalAttributes; } /** * @param nominalAttributes the nominalAttributes to set */ public void setNominalAttributes(List<NominalAttributeDTO> nominalAttributes) { this.nominalAttributes = nominalAttributes; } /** * @return the models */ public List<ModelDTO> getModels() { return models; } /** * @param models the models to set */ public void setModels(List<ModelDTO> models) { this.models = models; } /** * @return the documents */ public List<DocumentDTO> getDocuments() { return documents; } /** * @param documents the documents to set */ public void setDocuments(List<DocumentDTO> documents) { this.documents = documents; } /** * @return the modelFamilies */ public List<ModelFamilyDTO> getModelFamilies() { return modelFamilies; } /** * @param modelFamilies the modelFamilies to set */ public void setModelFamilies(List<ModelFamilyDTO> modelFamilies) { this.modelFamilies = modelFamilies; } /** * @return the modelNominalLabels */ public List<ModelNominalLabel> getModelNominalLabels() { return modelNominalLabels; } /** * @param modelNominalLabels the modelNominalLabels to set */ public void setModelNominalLabels(List<ModelNominalLabel> modelNominalLabels) { this.modelNominalLabels = modelNominalLabels; } /** * @return the collections */ public List<AidrCollection> getCollections() { return collections; } /** * @param collections the collections to set */ public void setCollections(List<AidrCollection> collections) { this.collections = collections; } /** * @return the modelWrapper */ public List<ModelWrapper> getModelWrapper() { return modelWrapper; } /** * @param modelWrapper the modelWrapper to set */ public void setModelWrapper(List<ModelWrapper> modelWrapper) { this.modelWrapper = modelWrapper; } /** * @return the modelHistoryWrapper */ public List<ModelHistoryWrapper> getModelHistoryWrapper() { return modelHistoryWrapper; } /** * @param modelHistoryWrapper the modelHistoryWrapper to set */ public void setModelHistoryWrapper(List<ModelHistoryWrapper> modelHistoryWrapper) { this.modelHistoryWrapper = modelHistoryWrapper; } /** * @return the taggersForCodes */ public List<TaggersForCodes> getTaggersForCodes() { return taggersForCodes; } /** * @param taggersForCodes the taggersForCodes to set */ public void setTaggersForCodes(List<TaggersForCodes> taggersForCodes) { this.taggersForCodes = taggersForCodes; } /** * @return the crisisAttributes */ public List<CrisisAttributesDTO> getCrisisAttributes() { return crisisAttributes; } /** * @param crisisAttributes the crisisAttributes to set */ public void setCrisisAttributes(List<CrisisAttributesDTO> crisisAttributes) { this.crisisAttributes = crisisAttributes; } /** * @return the trainingData */ public List<TrainingDataDTO> getTrainingData() { return trainingData; } /** * @param trainingData the trainingData to set */ public void setTrainingData(List<TrainingDataDTO> trainingData) { this.trainingData = trainingData; } /** * @return the modelNominalLabelsDTO */ public List<ModelNominalLabelDTO> getModelNominalLabelsDTO() { return modelNominalLabelsDTO; } /** * @param modelNominalLabelsDTO the modelNominalLabelsDTO to set */ public void setModelNominalLabelsDTO(List<ModelNominalLabelDTO> modelNominalLabelsDTO) { this.modelNominalLabelsDTO = modelNominalLabelsDTO; } /** * @return the total */ public Integer getTotal() { return total; } /** * @param total the total to set */ public void setTotal(Integer total) { this.total = total; } /** * @return the entityID */ public Long getEntityID() { return entityID; } /** * @param entityID the entityID to set */ public void setEntityID(Long entityID) { this.entityID = entityID; } }
package nl.opengeogroep.dbk; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.sql.Connection; import java.sql.SQLException; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.sql.DataSource; import org.apache.commons.dbutils.DbUtils; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.MapHandler; import org.apache.commons.dbutils.handlers.MapListHandler; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.json.JSONArray; import org.json.JSONObject; import org.apache.commons.io.IOUtils; /** * * @author Meine Toonen */ public class DBKAPI extends HttpServlet { private static final Log log = LogFactory.getLog(DBKAPI.class); private static final String API_PART = "/api/"; private static final String FEATURES = "features.json"; private static final String OBJECT = "object/"; private static final String MEDIA = "media/"; private static final String JSON = ".json"; private static final String PARAMETER_SRID = "srid"; protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException { String method = null; OutputStream out = response.getOutputStream(); try{ String requestedUri = request.getRequestURI(); method = requestedUri.substring(requestedUri.indexOf(API_PART)+ API_PART.length()); JSONObject output = new JSONObject(); if(method.contains(FEATURES)||method.contains(OBJECT)){ if(method.contains(FEATURES)){ output = processFeatureRequest(request); }else { output = processObjectRequest(request,method); } response.setContentType("application/json;charset=UTF-8"); out.write(output.toString().getBytes("UTF-8")); } else if(method.contains(MEDIA)){ processMedia(method,request,response,out); } else{ response.setStatus(HttpServletResponse.SC_BAD_REQUEST); output.put("success", Boolean.FALSE); output.put("message", "Requested method not understood. Method was: " + method + " but expected are: " + FEATURES +", " + OBJECT + " or " +MEDIA); out.write(output.toString().getBytes()); } }catch (IllegalArgumentException ex){ response.setContentType("text/plain;charset=UTF-8"); log.error("Error happened with " + method +":",ex); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); out.write(ex.getLocalizedMessage().getBytes()); }catch(Exception e){ log.error("Error happened with " + method +":",e ); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); out.write(("Exception occured:" +e.getLocalizedMessage()).getBytes()); }finally{ out.flush(); out.close(); } } /** * Process the call to /api/features.json[?srid=<integer>] * @param request The requestobject * @return A JSONObject with the GeoJSON representation of all the DBK's * @throws SQLException */ private JSONObject processFeatureRequest(HttpServletRequest request) throws SQLException, Exception { JSONObject geoJSON = new JSONObject(); JSONArray jFeatures = new JSONArray(); boolean hasParameter = request.getParameter(PARAMETER_SRID) != null; Connection conn = getConnection(); if(conn == null){ throw new Exception("Connection could not be established"); } MapListHandler h = new MapListHandler(); QueryRunner run = new QueryRunner(); geoJSON.put("type", "FeatureCollection"); geoJSON.put("features",jFeatures); try { List<Map<String,Object>> features; if(hasParameter){ String sridString = request.getParameter(PARAMETER_SRID); Integer srid = Integer.parseInt(sridString); features = run.query(conn, "select \"feature\" from dbk.dbkfeatures_json(?)", h,srid); }else{ features = run.query(conn, "select \"feature\" from dbk.dbkfeatures_json()", h); } for (Map<String, Object> feature : features) { JSONObject jFeature = processFeature(feature); jFeatures.put(jFeature); } } finally { DbUtils.close(conn); } return geoJSON; } /** * Method for requesting a single DBKObject * @param request The HttpServletRequest of this request * @param method Method containing possible (mandatory!) parameters: the id * @return An JSONObject representing the requested DBKObject, of an empty JSONObject if none is found * @throws Exception */ private JSONObject processObjectRequest(HttpServletRequest request,String method) throws Exception { JSONObject json = new JSONObject(); boolean hasSrid = request.getParameter(PARAMETER_SRID) != null; Connection conn = getConnection(); if(conn == null){ throw new Exception("Connection could not be established"); } MapHandler h = new MapHandler(); QueryRunner run = new QueryRunner(); String idString = null; Integer id = null; try{ idString = method.substring(method.indexOf(OBJECT) + OBJECT.length(), method.indexOf(JSON)); id = Integer.parseInt(idString); }catch(NumberFormatException ex){ throw new IllegalArgumentException("Given id not correct, should be an integer. Was: " + idString); } try { Map<String, Object> feature; if (hasSrid) { String sridString = request.getParameter(PARAMETER_SRID); Integer srid = Integer.parseInt(sridString); feature = run.query(conn, "select \"DBKObject\" from dbk.dbkobject_json(?,?)", h, id, srid); } else { feature = run.query(conn, "select \"DBKObject\" from dbk.dbkobject_json(?)", h, id); } if(feature == null){ throw new IllegalArgumentException("Given id didn't yield any results."); } JSONObject pgObject = new JSONObject( feature.get("DBKObject")); json = new JSONObject(); json.put("DBKObject", new JSONObject(pgObject.getString("value"))); } finally { DbUtils.close(conn); } return json; } /** * Processes the request for retrieving the media belonging to a DBK. * @param method The part of the url after /api/, containing the file name (and possible subdirectory) * @param request The http request * @param response The http response * @param out The outputstream to which the file must be written. * @throws IOException */ private void processMedia( String method, HttpServletRequest request,HttpServletResponse response, OutputStream out) throws IOException { FileInputStream fis = null; File requestedFile = null; String basePath = request.getServletContext().getInitParameter("dbk.media.path"); try { String fileArgument = method.substring(method.indexOf(MEDIA) + MEDIA.length()); String totalPath = basePath + File.separatorChar + fileArgument; requestedFile = new File(totalPath); fis = new FileInputStream(requestedFile); response.setContentType(request.getServletContext().getMimeType(totalPath)); Long size = requestedFile.length(); response.setContentLength(size.intValue()); IOUtils.copy(fis, out); } catch (IOException ex) { log.error("Error retrieving media.", ex); if (requestedFile != null) { log.error("Cannot load media: " + requestedFile.getCanonicalPath() + " from basePath: " + basePath); } response.setStatus(HttpServletResponse.SC_NOT_FOUND); }finally{ if(fis != null){ fis.close(); } } } private JSONObject processFeature(Map<String,Object> feature){ JSONObject jsonFeature = new JSONObject(); JSONObject properties = new JSONObject(); JSONObject dbFeatureObject = new JSONObject(feature.get("feature")); JSONObject featureValues = new JSONObject(dbFeatureObject.getString("value")); jsonFeature.put("type", "Feature"); jsonFeature.put("id", "DBKFeature.gid--" + featureValues.get("gid")); jsonFeature.put("geometry", featureValues.get("geometry")); jsonFeature.put("properties", properties); for (Iterator it = featureValues.keys(); it.hasNext();) { String key = (String)it.next(); if(key.equals("geometry")){ continue; } Object value = featureValues.get(key); properties.put(key, value); } return jsonFeature; } public Connection getConnection() { try { InitialContext cxt = new InitialContext(); if (cxt == null) { throw new Exception("Uh oh -- no context!"); } DataSource ds = (DataSource) cxt.lookup("java:/comp/env/jdbc/dbk-api"); if (ds == null) { throw new Exception("Data source not found!"); } Connection connection = ds.getConnection(); return connection; } catch (NamingException ex) { log.error("naming",ex); } catch (Exception ex) { log.error("exception",ex); } return null; } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { processRequest(request, response); } catch (SQLException ex) { log.error("GET failed: ",ex); } } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { processRequest(request, response); } catch (SQLException ex) { log.error("POST failed: ",ex); } } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
package ti.modules.titanium.network; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.FilterOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.lang.ref.WeakReference; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpVersion; import org.apache.http.MethodNotSupportedException; import org.apache.http.NameValuePair; import org.apache.http.ParseException; import org.apache.http.ProtocolException; import org.apache.http.StatusLine; import org.apache.http.auth.AuthScope; import org.apache.http.auth.Credentials; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.HttpResponseException; import org.apache.http.client.ResponseHandler; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.conn.params.ConnManagerParams; import org.apache.http.conn.params.ConnPerRouteBean; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.cookie.Cookie; import org.apache.http.entity.AbstractHttpEntity; import org.apache.http.entity.StringEntity; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.ContentBody; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.DefaultHttpRequestFactory; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.DefaultRedirectHandler; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.message.BasicHttpEntityEnclosingRequest; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParams; import org.apache.http.protocol.HTTP; import org.apache.http.protocol.HttpContext; import org.apache.http.util.EntityUtils; import org.appcelerator.kroll.KrollDict; import org.appcelerator.kroll.KrollFunction; import org.appcelerator.kroll.KrollProxy; import org.appcelerator.kroll.common.Log; import org.appcelerator.kroll.common.TiConfig; import org.appcelerator.titanium.TiApplication; import org.appcelerator.titanium.TiBlob; import org.appcelerator.titanium.TiFileProxy; import org.appcelerator.titanium.io.TiBaseFile; import org.appcelerator.titanium.io.TiFile; import org.appcelerator.titanium.util.TiConvert; import org.appcelerator.titanium.util.TiMimeTypeHelper; import org.appcelerator.titanium.util.TiTempFileHelper; import ti.modules.titanium.xml.DocumentProxy; import ti.modules.titanium.xml.XMLModule; import android.net.Uri; public class TiHTTPClient { private static final String LCAT = "TiHttpClient"; private static final boolean DBG = TiConfig.LOGD; private static final int IS_BINARY_THRESHOLD = 30; private static final int DEFAULT_MAX_BUFFER_SIZE = 512 * 1024; private static final String PROPERTY_MAX_BUFFER_SIZE = "ti.android.httpclient.maxbuffersize"; private static final int PROTOCOL_DEFAULT_PORT = -1; private static final String ON_READY_STATE_CHANGE = "onreadystatechange"; private static final String ON_LOAD = "onload"; private static final String ON_ERROR = "onerror"; private static final String ON_DATA_STREAM = "ondatastream"; private static final String ON_SEND_STREAM = "onsendstream"; private static AtomicInteger httpClientThreadCounter; private static DefaultHttpClient nonValidatingClient; private static DefaultHttpClient validatingClient; private DefaultHttpClient client; private KrollProxy proxy; private int readyState; private String responseText; private DocumentProxy responseXml; private int status; private String statusText; private boolean connected; private HttpRequest request; private HttpResponse response; private String method; private HttpHost host; private LocalResponseHandler handler; private Credentials credentials; private TiBlob responseData; private OutputStream responseOut; private String charset; private String contentType; private long maxBufferSize; private ArrayList<NameValuePair> nvPairs; private HashMap<String, ContentBody> parts; private String data; private boolean needMultipart; private Thread clientThread; private boolean aborted; private int timeout = -1; private boolean autoEncodeUrl = true; private boolean autoRedirect = true; private Uri uri; private String url; protected HashMap<String,String> headers = new HashMap<String,String>(); public static final int READY_STATE_UNSENT = 0; // Unsent, open() has not yet been called public static final int READY_STATE_OPENED = 1; // Opened, send() has not yet been called public static final int READY_STATE_HEADERS_RECEIVED = 2; // Headers received, headers have returned and the status is available public static final int READY_STATE_LOADING = 3; // Loading, responseText is being loaded with data public static final int READY_STATE_DONE = 4; // Done, all operations have finished class RedirectHandler extends DefaultRedirectHandler { @Override public URI getLocationURI(HttpResponse response, HttpContext context) throws ProtocolException { if (response == null) { throw new IllegalArgumentException("HTTP response may not be null"); } // get the location header to find out where to redirect to Header locationHeader = response.getFirstHeader("location"); if (locationHeader == null) { // got a redirect response, but no location header throw new ProtocolException("Received redirect response " + response.getStatusLine() + " but no location header"); } // bug // in some cases we have to manually replace spaces in the URI (probably because the HTTP server isn't correctly escaping them) String location = locationHeader.getValue().replaceAll (" ", "%20"); response.setHeader("location", location); return super.getLocationURI(response, context); } @Override public boolean isRedirectRequested(HttpResponse response, HttpContext context) { if (autoRedirect) { return super.isRedirectRequested(response, context); } else { return false; } } } class LocalResponseHandler implements ResponseHandler<String> { public WeakReference<TiHTTPClient> client; public InputStream is; public HttpEntity entity; public LocalResponseHandler(TiHTTPClient client) { this.client = new WeakReference<TiHTTPClient>(client); } public String handleResponse(HttpResponse response) throws HttpResponseException, IOException { connected = true; String clientResponse = null; if (client != null) { TiHTTPClient c = client.get(); if (c != null) { c.response = response; c.setReadyState(READY_STATE_HEADERS_RECEIVED); c.setStatus(response.getStatusLine().getStatusCode()); c.setStatusText(response.getStatusLine().getReasonPhrase()); c.setReadyState(READY_STATE_LOADING); } if (DBG) { try { Log.w(LCAT, "Entity Type: " + response.getEntity().getClass()); Log.w(LCAT, "Entity Content Type: " + response.getEntity().getContentType().getValue()); Log.w(LCAT, "Entity isChunked: " + response.getEntity().isChunked()); Log.w(LCAT, "Entity isStreaming: " + response.getEntity().isStreaming()); } catch (Throwable t) { // Ignore } } StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() >= 300) { setResponseText(response.getEntity()); throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase()); } entity = response.getEntity(); if (entity != null) { if (entity.getContentType() != null) { contentType = entity.getContentType().getValue(); } is = entity.getContent(); charset = EntityUtils.getContentCharSet(entity); } else { is = null; } responseData = null; if (is != null) { long contentLength = entity.getContentLength(); if (DBG) { Log.d(LCAT, "Content length: " + contentLength); } int count = 0; long totalSize = 0; byte[] buf = new byte[4096]; if (DBG) { Log.d(LCAT, "Available: " + is.available()); } if (entity != null) { charset = EntityUtils.getContentCharSet(entity); } while((count = is.read(buf)) != -1) { totalSize += count; try { handleEntityData(buf, count, totalSize, contentLength); } catch (IOException e) { Log.e(LCAT, "Error handling entity data", e); // TODO //Context.throwAsScriptRuntimeEx(e); } } if (entity != null) { try { entity.consumeContent(); } catch (IOException e) { e.printStackTrace(); } } if (totalSize > 0) { finishedReceivingEntityData(totalSize); } } } return clientResponse; } private TiFile createFileResponseData(boolean dumpResponseOut) throws IOException { File outFile; TiApplication app = TiApplication.getInstance(); if (app != null) { TiTempFileHelper helper = app.getTempFileHelper(); outFile = helper.createTempFile("tihttp", "tmp"); } else { outFile = File.createTempFile("tihttp", "tmp"); } TiFile tiFile = new TiFile(outFile, outFile.getAbsolutePath(), false); if (dumpResponseOut) { ByteArrayOutputStream byteStream = (ByteArrayOutputStream) responseOut; tiFile.write(TiBlob.blobFromData(byteStream.toByteArray()), false); } responseOut = new FileOutputStream(outFile, dumpResponseOut); responseData = TiBlob.blobFromFile(tiFile, contentType); return tiFile; } private void handleEntityData(byte[] data, int size, long totalSize, long contentLength) throws IOException { if (responseOut == null) { if (contentLength > maxBufferSize) { createFileResponseData(false); } else { long streamSize = contentLength > 0 ? contentLength : 512; responseOut = new ByteArrayOutputStream((int)streamSize); } } if (totalSize > maxBufferSize && responseOut instanceof ByteArrayOutputStream) { // Content length may not have been reported, dump the current stream // to a file and re-open as a FileOutputStream w/ append createFileResponseData(true); } responseOut.write(data, 0, size); KrollFunction onDataStreamCallback = getCallback(ON_DATA_STREAM); if (onDataStreamCallback != null) { KrollDict o = new KrollDict(); o.put("totalCount", contentLength); o.put("totalSize", totalSize); o.put("size", size); byte[] blobData = new byte[size]; System.arraycopy(data, 0, blobData, 0, size); TiBlob blob = TiBlob.blobFromData(blobData, contentType); o.put("blob", blob); o.put("progress", ((double)totalSize)/((double)contentLength)); onDataStreamCallback.callAsync(proxy.getKrollObject(), o); } } private void finishedReceivingEntityData(long contentLength) throws IOException { if (responseOut instanceof ByteArrayOutputStream) { ByteArrayOutputStream byteStream = (ByteArrayOutputStream) responseOut; responseData = TiBlob.blobFromData(byteStream.toByteArray(), contentType); } responseOut.close(); responseOut = null; } private void setResponseText(HttpEntity entity) throws IOException, ParseException { if (entity != null) { responseText = EntityUtils.toString(entity); } } } private interface ProgressListener { public void progress(int progress); } private class ProgressEntity implements HttpEntity { private HttpEntity delegate; private ProgressListener listener; public ProgressEntity(HttpEntity delegate, ProgressListener listener) { this.delegate = delegate; this.listener = listener; } public void consumeContent() throws IOException { delegate.consumeContent(); } public InputStream getContent() throws IOException, IllegalStateException { return delegate.getContent(); } public Header getContentEncoding() { return delegate.getContentEncoding(); } public long getContentLength() { return delegate.getContentLength(); } public Header getContentType() { return delegate.getContentType(); } public boolean isChunked() { return delegate.isChunked(); } public boolean isRepeatable() { return delegate.isRepeatable(); } public boolean isStreaming() { return delegate.isStreaming(); } public void writeTo(OutputStream stream) throws IOException { OutputStream progressOut = new ProgressOutputStream(stream, listener); delegate.writeTo(progressOut); } } private class ProgressOutputStream extends FilterOutputStream { private ProgressListener listener; private int transferred = 0, lastTransferred = 0; public ProgressOutputStream(OutputStream delegate, ProgressListener listener) { super(delegate); this.listener = listener; } private void fireProgress() { // filter to 512 bytes of granularity if (transferred - lastTransferred >= 512) { lastTransferred = transferred; listener.progress(transferred); } } @Override public void write(int b) throws IOException { super.write(b); transferred++; fireProgress(); } } public TiHTTPClient(KrollProxy proxy) { this.proxy = proxy; this.client = getClient(false); if (httpClientThreadCounter == null) { httpClientThreadCounter = new AtomicInteger(); } readyState = 0; responseText = ""; credentials = null; connected = false; this.nvPairs = new ArrayList<NameValuePair>(); this.parts = new HashMap<String,ContentBody>(); this.maxBufferSize = TiApplication.getInstance() .getSystemProperties().getInt(PROPERTY_MAX_BUFFER_SIZE, DEFAULT_MAX_BUFFER_SIZE); } public int getReadyState() { synchronized(this) { this.notify(); } return readyState; } public KrollFunction getCallback(String name) { Object value = proxy.getProperty(name); if (value != null && value instanceof KrollFunction) { return (KrollFunction) value; } return null; } public void fireCallback(String name) { KrollDict eventProperties = new KrollDict(); eventProperties.put("source", proxy); fireCallback(name, new Object [] {eventProperties}); } public void fireCallback(String name, Object[] args) { KrollFunction cb = getCallback(name); if (cb != null) { // TODO - implement converter method for array to hashmap? cb.callAsync(proxy.getKrollObject(), args); } } public boolean validatesSecureCertificate() { if (proxy.hasProperty("validatesSecureCertificate")) { return TiConvert.toBoolean(proxy.getProperty("validatesSecureCertificate")); } else { if (TiApplication.getInstance().getDeployType().equals( TiApplication.DEPLOY_TYPE_PRODUCTION)) { return true; } } return false; } public void setReadyState(int readyState) { Log.d(LCAT, "Setting ready state to " + readyState); this.readyState = readyState; fireCallback(ON_READY_STATE_CHANGE); if (readyState == READY_STATE_DONE) { // Fire onload callback fireCallback(ON_LOAD); } } public void sendError(String error) { Log.i(LCAT, "Sending error " + error); KrollDict event = new KrollDict(); event.put("error", error); event.put("source", proxy); fireCallback(ON_ERROR, new Object[] {event}); } public String getResponseText() { if (responseData != null && responseText == null) { byte[] data = responseData.getBytes(); if (charset == null) { // Detect binary int binaryCount = 0; int len = data.length; if (len > 0) { for (int i = 0; i < len; i++) { byte b = data[i]; if (b < 32 || b > 127 ) { if (b != '\n' && b != '\r' && b != '\t' && b != '\b') { binaryCount++; } } } if ((binaryCount * 100)/len >= IS_BINARY_THRESHOLD) { return null; } } charset = HTTP.DEFAULT_CONTENT_CHARSET; } try { responseText = new String(data, charset); } catch (UnsupportedEncodingException e) { Log.e(LCAT, "Unable to convert to String using charset: " + charset); } } return responseText; } public TiBlob getResponseData() { return responseData; } public DocumentProxy getResponseXML() { // avoid eating up tons of memory if we have a large binary data blob if (TiMimeTypeHelper.isBinaryMimeType(contentType)) { return null; } if (responseXml == null && (responseData != null || responseText != null)) { try { String text = getResponseText(); if (text == null || text.length() == 0) { return null; } if (charset != null && charset.length() > 0) { responseXml = XMLModule.parse(text, charset); } else { responseXml = XMLModule.parse(text); } } catch (Exception e) { Log.e(LCAT, "Error parsing XML", e); } } return responseXml; } public void setResponseText(String responseText) { this.responseText = responseText; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public String getStatusText() { return statusText; } public void setStatusText(String statusText) { this.statusText = statusText; } public void abort() { if (readyState > READY_STATE_UNSENT && readyState < READY_STATE_DONE) { aborted = true; if (client != null) { client.getConnectionManager().shutdown(); client = null; } if (validatingClient != null) validatingClient = null; if (nonValidatingClient != null) nonValidatingClient = null; } } public String getAllResponseHeaders() { String result = ""; if (readyState >= READY_STATE_HEADERS_RECEIVED && response != null) { StringBuilder sb = new StringBuilder(1024); Header[] headers = response.getAllHeaders(); int len = headers.length; for(int i = 0; i < len; i++) { Header h = headers[i]; sb.append(h.getName()).append(":").append(h.getValue()).append("\n"); } result = sb.toString(); } else { // Spec says return ""; } return result; } public void clearCookies(String url) { List<Cookie> cookies = new ArrayList(client.getCookieStore().getCookies()); client.getCookieStore().clear(); String lower_url = url.toLowerCase(); for (Cookie cookie : cookies) { if (!lower_url.contains(cookie.getDomain().toLowerCase())) { client.getCookieStore().addCookie(cookie); } } } public void setRequestHeader(String header, String value) { if (readyState == READY_STATE_OPENED) { headers.put(header, value); } else { throw new IllegalStateException("setRequestHeader can only be called before invoking send."); } } public String getResponseHeader(String headerName) { String result = ""; if (readyState > READY_STATE_OPENED) { String delimiter = ""; boolean firstPass = true; // headers will be an empty array if none can be found Header[] headers = response.getHeaders(headerName); for (Header header : headers) { if (!firstPass) { delimiter = ", "; } result += delimiter + header.getValue(); firstPass = false; } if (headers.length == 0) { Log.w(LCAT, "No value for response header: " + headerName); } } else { throw new IllegalStateException("getResponseHeader can only be called when readyState > 1"); } return result; } private static Uri getCleanUri(String uri) { Uri base = Uri.parse(uri); Uri.Builder builder = base.buildUpon(); builder.encodedQuery(Uri.encode(Uri.decode(base.getQuery()), "&=")); String encodedAuthority = Uri.encode(Uri.decode(base.getAuthority()),"/:@"); int firstAt = encodedAuthority.indexOf('@'); if (firstAt >= 0) { int lastAt = encodedAuthority.lastIndexOf('@'); if (lastAt > firstAt) { // We have a situation that might be like this: // i.e., the user name is user@domain.com, and the host // is api.mickey.com. We need all at-signs prior to the final one (which // indicates the host) to be encoded. encodedAuthority = Uri.encode(encodedAuthority.substring(0, lastAt), "/:") + encodedAuthority.substring(lastAt); } } builder.encodedAuthority(encodedAuthority); builder.encodedPath(Uri.encode(Uri.decode(base.getPath()), "/")); return builder.build(); } public void open(String method, String url) { if (DBG) { Log.d(LCAT, "open request method=" + method + " url=" + url); } if (url == null) { Log.e(LCAT, "unable to open a null URL"); throw new IllegalArgumentException("URL cannot be null"); } // if the url is not prepended with either http or // https, then default to http and prepend the protocol // to the url if (!url.startsWith("http: url = "http://" + url; } if (autoEncodeUrl) { this.uri = getCleanUri(url); } else { this.uri = Uri.parse(url); } // If the original url does not contain any // escaped query string (i.e., does not look // pre-encoded), go ahead and reset it to the // clean uri. Else keep it as is so the user's // escaping stays in effect. The users are on their own // at that point. if (autoEncodeUrl && !url.matches(".*\\?.*\\%\\d\\d.*$")) { this.url = this.uri.toString(); } else { this.url = url; } this.method = method; String hostString = uri.getHost(); int port = PROTOCOL_DEFAULT_PORT; // The Android Uri doesn't seem to handle user ids with at-signs (@) in them // properly, even if the @ is escaped. It will set the host (uri.getHost()) to // the part of the user name after the @. For example, this Uri would get // the host set to appcelerator.com when it should be mickey.com: // ... even if that first one is escaped to ... // Tests show that Java URL handles it properly, however. So revert to using Java URL.getHost() // if we see that the Uri.getUserInfo has an at-sign in it. // Also, uri.getPort() will throw an exception as it will try to parse what it thinks is the port // part of the Uri (":password....") as an int. So in this case we'll get the port number // as well from Java URL. See Lighthouse ticket 2150. if (uri.getUserInfo() != null && uri.getUserInfo().contains("@")) { URL javaUrl; try { javaUrl = new URL(uri.toString()); hostString = javaUrl.getHost(); port = javaUrl.getPort(); } catch (MalformedURLException e) { Log.e(LCAT, "Error attempting to derive Java url from uri: " + e.getMessage(), e); } } else { port = uri.getPort(); } if (DBG) { Log.d(LCAT, "Instantiating host with hostString='" + hostString + "', port='" + port + "', scheme='" + uri.getScheme() + "'"); } host = new HttpHost(hostString, port, uri.getScheme()); if (uri.getUserInfo() != null) { credentials = new UsernamePasswordCredentials(uri.getUserInfo()); } setReadyState(READY_STATE_OPENED); setRequestHeader("User-Agent", (String) proxy.getProperty("userAgent")); // Causes Auth to Fail with twitter and other size apparently block X- as well // Ticket #729, ignore twitter for now if (!hostString.contains("twitter.com")) { setRequestHeader("X-Requested-With","XMLHttpRequest"); } else { Log.i(LCAT, "Twitter: not sending X-Requested-With header"); } } public void addStringData(String data) { this.data = data; } public void addPostData(String name, String value) { if (value == null) { value = ""; } try { if (needMultipart) { // JGH NOTE: this seems to be a bug in RoR where it would puke if you // send a content-type of text/plain for key/value pairs in form-data // so we send an empty string by default instead which will cause the // StringBody to not include the content-type header. this should be // harmless for all other cases parts.put(name, new StringBody(value,"",null)); } else { nvPairs.add(new BasicNameValuePair(name, value.toString())); } } catch (UnsupportedEncodingException e) { nvPairs.add(new BasicNameValuePair(name, value.toString())); } } public int addTitaniumFileAsPostData(String name, Object value) { try { if (value instanceof TiBaseFile) { TiBaseFile baseFile = (TiBaseFile) value; FileBody body = new FileBody(baseFile.getNativeFile(), TiMimeTypeHelper.getMimeType(baseFile.nativePath())); parts.put(name, body); return (int)baseFile.getNativeFile().length(); } else if (value instanceof TiBlob) { TiBlob blob = (TiBlob) value; String mimeType = blob.getMimeType(); File tmpFile = File.createTempFile("tixhr", "." + TiMimeTypeHelper.getFileExtensionFromMimeType(mimeType, "txt")); FileOutputStream fos = new FileOutputStream(tmpFile); fos.write(blob.getBytes()); fos.close(); FileBody body = new FileBody(tmpFile, mimeType); parts.put(name, body); return blob.getLength(); } else { if (value != null) { Log.e(LCAT, name + " is a " + value.getClass().getSimpleName()); } else { Log.e(LCAT, name + " is null"); } } } catch (IOException e) { Log.e(LCAT, "Error adding post data ("+name+"): " + e.getMessage()); } return 0; } protected DefaultHttpClient createClient() { SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); HttpParams params = new BasicHttpParams(); ConnManagerParams.setMaxTotalConnections(params, 5); ConnPerRouteBean connPerRoute = new ConnPerRouteBean(5); ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute); HttpProtocolParams.setUseExpectContinue(params, false); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); return new DefaultHttpClient(new ThreadSafeClientConnManager(params, registry), params); } protected DefaultHttpClient getClient(boolean validating) { if (validating) { if (nonValidatingClient != null) { return nonValidatingClient; } nonValidatingClient = createClient(); nonValidatingClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); return nonValidatingClient; } else { if (validatingClient != null) { return validatingClient; } validatingClient = createClient(); validatingClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", new NonValidatingSSLSocketFactory(), 443)); return validatingClient; } } public void send(Object userData) throws MethodNotSupportedException { aborted = false; // TODO consider using task manager double totalLength = 0; needMultipart = false; if (userData != null) { if (userData instanceof HashMap) { HashMap<String, Object> data = (HashMap) userData; boolean isPostOrPut = method.equals("POST") || method.equals("PUT"); boolean isGet = !isPostOrPut && method.equals("GET"); // first time through check if we need multipart for POST for (String key : data.keySet()) { Object value = data.get(key); if(value != null) { // if the value is a proxy, we need to get the actual file object if (value instanceof TiFileProxy) { value = ((TiFileProxy) value).getBaseFile(); } if (value instanceof TiBaseFile || value instanceof TiBlob) { needMultipart = true; break; } } } boolean queryStringAltered = false; for (String key : data.keySet()) { Object value = data.get(key); if (isPostOrPut && (value != null)) { // if the value is a proxy, we need to get the actual file object if (value instanceof TiFileProxy) { value = ((TiFileProxy) value).getBaseFile(); } if (value instanceof TiBaseFile || value instanceof TiBlob) { totalLength += addTitaniumFileAsPostData(key, value); } else { String str = TiConvert.toString(value); addPostData(key, str); totalLength += str.length(); } } else if (isGet) { uri = uri.buildUpon().appendQueryParameter( key, TiConvert.toString(value)).build(); queryStringAltered = true; } } if (queryStringAltered) { this.url = uri.toString(); } } else { addStringData(TiConvert.toString(userData)); } } if (DBG) { Log.d(LCAT, "Instantiating http request with method='" + method + "' and this url:"); Log.d(LCAT, this.url); } request = new DefaultHttpRequestFactory().newHttpRequest(method, this.url); for (String header : headers.keySet()) { request.setHeader(header, headers.get(header)); } clientThread = new Thread(new ClientRunnable(totalLength), "TiHttpClient-" + httpClientThreadCounter.incrementAndGet()); clientThread.setPriority(Thread.MIN_PRIORITY); clientThread.start(); if (DBG) { Log.d(LCAT, "Leaving send()"); } } private class ClientRunnable implements Runnable { private double totalLength; public ClientRunnable(double totalLength) { this.totalLength = totalLength; } public void run() { try { Thread.sleep(10); if (DBG) { Log.d(LCAT, "send()"); } /* Header[] h = request.getAllHeaders(); for(int i=0; i < h.length; i++) { Header hdr = h[i]; //Log.e(LCAT, "HEADER: " + hdr.toString()); } */ handler = new LocalResponseHandler(TiHTTPClient.this); // lazy get client each time in case the validatesSecureCertificate() changes client = getClient(validatesSecureCertificate()); if (credentials != null) { client.getCredentialsProvider().setCredentials (new AuthScope(uri.getHost(), -1), credentials); credentials = null; } client.setRedirectHandler(new RedirectHandler()); if(request instanceof BasicHttpEntityEnclosingRequest) { UrlEncodedFormEntity form = null; MultipartEntity mpe = null; if (nvPairs.size() > 0) { try { form = new UrlEncodedFormEntity(nvPairs, "UTF-8"); } catch (UnsupportedEncodingException e) { Log.e(LCAT, "Unsupported encoding: ", e); } } if (parts.size() > 0 && needMultipart) { mpe = new MultipartEntity(); for(String name : parts.keySet()) { Log.d(LCAT, "adding part " + name + ", part type: " + parts.get(name).getMimeType() + ", len: " + parts.get(name).getContentLength()); mpe.addPart(name, parts.get(name)); } if (form != null) { try { ByteArrayOutputStream bos = new ByteArrayOutputStream((int) form.getContentLength()); form.writeTo(bos); mpe.addPart("form", new StringBody(bos.toString(), "application/x-www-form-urlencoded", Charset.forName("UTF-8"))); } catch (UnsupportedEncodingException e) { Log.e(LCAT, "Unsupported encoding: ", e); } catch (IOException e) { Log.e(LCAT, "Error converting form to string: ", e); } } HttpEntityEnclosingRequest e = (HttpEntityEnclosingRequest) request; Log.d(LCAT, "totalLength="+totalLength); ProgressEntity progressEntity = new ProgressEntity(mpe, new ProgressListener() { public void progress(int progress) { KrollFunction cb = getCallback(ON_SEND_STREAM); if (cb != null) { KrollDict data = new KrollDict(); data.put("progress", ((double)progress)/totalLength); data.put("source", proxy); cb.callAsync(proxy.getKrollObject(), data); } } }); e.setEntity(progressEntity); e.addHeader("Length", totalLength+""); } else { handleURLEncodedData(form); } } // set request specific parameters if (timeout != -1) { HttpConnectionParams.setConnectionTimeout(request.getParams(), timeout); HttpConnectionParams.setSoTimeout(request.getParams(), timeout); } if (DBG) { Log.d(LCAT, "Preparing to execute request"); } String result = null; try { result = client.execute(host, request, handler); } catch (IOException e) { if (!aborted) { throw e; } } if(result != null) { Log.d(LCAT, "Have result back from request len=" + result.length()); } connected = false; setResponseText(result); setReadyState(READY_STATE_DONE); } catch(Throwable t) { if (client != null) { Log.d(LCAT, "clearing the expired and idle connections"); client.getConnectionManager().closeExpiredConnections(); client.getConnectionManager().closeIdleConnections(0, TimeUnit.NANOSECONDS); } else { Log.d(LCAT, "client is not valid, unable to clear expired and idle connections"); } String msg = t.getMessage(); if (msg == null && t.getCause() != null) { msg = t.getCause().getMessage(); } if (msg == null) { msg = t.getClass().getName(); } Log.e(LCAT, "HTTP Error (" + t.getClass().getName() + "): " + msg, t); sendError(msg); } } } private void handleURLEncodedData(UrlEncodedFormEntity form) { AbstractHttpEntity entity = null; if (data != null) { try { entity = new StringEntity(data, "UTF-8"); } catch(Exception ex) { //FIXME Log.e(LCAT, "Exception, implement recovery: ", ex); } } else { entity = form; } if (entity != null) { Header header = request.getFirstHeader("Content-Type"); if(header == null) { entity.setContentType("application/x-www-form-urlencoded"); } else { entity.setContentType(header.getValue()); } HttpEntityEnclosingRequest e = (HttpEntityEnclosingRequest)request; e.setEntity(entity); } } public String getLocation() { return url; } public String getConnectionType() { return method; } public boolean isConnected() { return connected; } public void setTimeout(int millis) { timeout = millis; } protected void setAutoEncodeUrl(boolean value) { autoEncodeUrl = value; } protected boolean getAutoEncodeUrl() { return autoEncodeUrl; } protected void setAutoRedirect(boolean value) { autoRedirect = value; } protected boolean getAutoRedirect() { return autoRedirect; } }
package ti.modules.titanium.network; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FilterOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.net.CookieManager; import java.net.HttpCookie; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.GZIPInputStream; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.KeyManager; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509KeyManager; import javax.net.ssl.X509TrustManager; import android.util.Base64; import org.appcelerator.kroll.KrollDict; import org.appcelerator.kroll.KrollProxy; import org.appcelerator.kroll.common.Log; import org.appcelerator.titanium.TiApplication; import org.appcelerator.titanium.TiBlob; import org.appcelerator.titanium.TiC; import org.appcelerator.titanium.TiFileProxy; import org.appcelerator.titanium.io.TiBaseFile; import org.appcelerator.titanium.io.TiFile; import org.appcelerator.titanium.io.TiFileFactory; import org.appcelerator.titanium.io.TiResourceFile; import org.appcelerator.titanium.util.TiConvert; import org.appcelerator.titanium.util.TiMimeTypeHelper; import org.appcelerator.titanium.util.TiPlatformHelper; import org.appcelerator.titanium.util.TiUrl; import org.json.JSONObject; import ti.modules.titanium.network.httpurlconnection.ContentBody; import ti.modules.titanium.network.httpurlconnection.Entity; import ti.modules.titanium.network.httpurlconnection.FileEntity; import ti.modules.titanium.network.httpurlconnection.HttpUrlConnectionUtils; import ti.modules.titanium.network.httpurlconnection.JsonBody; import ti.modules.titanium.network.httpurlconnection.NameValuePair; import ti.modules.titanium.network.httpurlconnection.NullHostNameVerifier; import ti.modules.titanium.network.httpurlconnection.StringBody; import ti.modules.titanium.network.httpurlconnection.StringEntity; import ti.modules.titanium.network.httpurlconnection.FileBody; import ti.modules.titanium.network.httpurlconnection.UrlEncodedFormEntity; import ti.modules.titanium.xml.DocumentProxy; import ti.modules.titanium.xml.XMLModule; import android.net.Uri; import android.os.Build; import android.util.Base64OutputStream; public class TiHTTPClient { private static final String TAG = "TiHTTPClient"; private static final int DEFAULT_MAX_BUFFER_SIZE = 512 * 1024; private static final String PROPERTY_MAX_BUFFER_SIZE = "ti.android.httpclient.maxbuffersize"; private static final int PROTOCOL_DEFAULT_PORT = -1; private static final String TITANIUM_ID_HEADER = "X-Titanium-Id"; private static final String TITANIUM_USER_AGENT = "Appcelerator Titanium/" + TiApplication.getInstance().getTiBuildVersion() + " ("+ Build.MODEL + "; Android API Level: " + Integer.toString(Build.VERSION.SDK_INT) + "; " + TiPlatformHelper.getInstance().getLocale() +";)"; private static final String[] FALLBACK_CHARSETS = {"UTF_8", "ISO_8859_1"}; // Regular expressions for detecting charset information in response documents (ex: html, xml). private static final String HTML_META_TAG_REGEX = "charset=([^\"\']*)"; private static final String XML_DECLARATION_TAG_REGEX = "encoding=[\"\']([^\"\']*)[\"\']"; private static AtomicInteger httpClientThreadCounter; private HttpURLConnection client; private HTTPClientProxy proxy; private int readyState; private String responseText; private DocumentProxy responseXml; private int status; private String statusText; private boolean connected; private String method; private TiBlob responseData; private OutputStream responseOut; private String charset; private String contentType; private String contentEncoding; private long maxBufferSize; private Object data; private boolean needMultipart; private Thread clientThread; private boolean aborted; private int timeout = -1; private boolean autoEncodeUrl = true; private boolean autoRedirect = true; private Uri uri; private String url; private URL mURL; private String redirectedLocation; private ArrayList<File> tmpFiles = new ArrayList<File>(); private ArrayList<X509TrustManager> trustManagers = new ArrayList<X509TrustManager>(); private ArrayList<X509KeyManager> keyManagers = new ArrayList<X509KeyManager>(); protected SecurityManagerProtocol securityManager; private int tlsVersion = NetworkModule.TLS_DEFAULT; private static CookieManager cookieManager = NetworkModule.getCookieManagerInstance(); protected HashMap<String,String> requestHeaders = new HashMap<String,String>(); private ArrayList<NameValuePair> nvPairs; private HashMap<String, ContentBody> parts; protected Map<String, List<String>> responseHeaders; public static final int READY_STATE_UNSENT = 0; // Unsent, open() has not yet been called public static final int READY_STATE_OPENED = 1; // Opened, send() has not yet been called public static final int READY_STATE_HEADERS_RECEIVED = 2; // Headers received, headers have returned and the status is available public static final int READY_STATE_LOADING = 3; // Loading, responseText is being loaded with data public static final int READY_STATE_DONE = 4; // Done, all operations have finished public static final int REDIRECTS = 5; private TiFile responseFile; private boolean hasAuthentication = false; private String username; private String password; private void handleResponse(HttpURLConnection connection) throws IOException { connected = true; long contentLength; if (connection != null) { TiHTTPClient c = this; contentLength = connection.getContentLength(); // Note on getHeaderFields() // HttpURLConnection include a mapping // for the null key; in HTTP's case, this maps to the HTTP status line and is // treated as being at position 0 when indexing into the header fields. responseHeaders = connection.getHeaderFields(); setStatus(connection.getResponseCode()); // Send the READY_STATE_HEADERS_RECEIVED state once the headers and the status are read setReadyState(READY_STATE_HEADERS_RECEIVED); setStatusText(connection.getResponseMessage()); setReadyState(READY_STATE_LOADING); if (proxy.hasProperty(TiC.PROPERTY_FILE)) { Object f = c.proxy.getProperty(TiC.PROPERTY_FILE); if (f instanceof String) { String fileName = (String) f; TiBaseFile baseFile = TiFileFactory.createTitaniumFile(fileName, false); if (baseFile instanceof TiFile) { responseFile = (TiFile) baseFile; } } if (responseFile == null && Log.isDebugModeEnabled()) { Log.w(TAG, "Ignore the provided response file because it is not valid / writable."); } } // Check for new url that is redirected URL currentLocation = connection.getURL(); if (autoRedirect && !mURL.sameFile(currentLocation)) { redirectedLocation = currentLocation.toString(); } contentEncoding = connection.getContentEncoding(); contentType = connection.getContentType(); String charset = ""; if (contentType != null) { String[] values = contentType.split(";"); //The values.length must be equal to 2... for (String value : values) { value = value.trim(); if (value.toLowerCase().startsWith("charset=")) { charset = value.substring("charset=".length()); } } } // If no charset is defined, default to UTF-8 if (charset.isEmpty()) { charset = "UTF-8"; } responseData = null; int status = connection.getResponseCode(); InputStream in; if (status >= 400) { in = connection.getErrorStream(); } else { in = connection.getInputStream(); } if ("gzip".equalsIgnoreCase(contentEncoding)) { in = new GZIPInputStream(in); } InputStream is = new BufferedInputStream(in); if (is != null) { Log.d(TAG, "Content length: " + contentLength, Log.DEBUG_MODE); int count = 0; long totalSize = 0; byte[] buf = new byte[4096]; Log.d(TAG, "Available: " + is.available(), Log.DEBUG_MODE); while((count = is.read(buf)) != -1) { if (aborted) { break; } totalSize += count; try { responseText = new String(Arrays.copyOfRange(buf, 0, count)); handleEntityData(buf, count, totalSize, contentLength); } catch (IOException e) { Log.e(TAG, "Error handling entity data", e); } } if (totalSize > 0) { finishedReceivingEntityData(totalSize); } } } } private TiFile createFileResponseData(boolean dumpResponseOut) throws IOException { TiFile tiFile = null; File outFile = null; if (responseFile != null) { tiFile = responseFile; outFile = tiFile.getFile(); try { responseOut = new FileOutputStream(outFile, dumpResponseOut); // If the response file is in the temp folder, don't delete it during cleanup. TiApplication app = TiApplication.getInstance(); if (app != null) { app.getTempFileHelper().excludeFileOnCleanup(outFile); } } catch (FileNotFoundException e) { responseFile = null; tiFile = null; if (Log.isDebugModeEnabled()) { Log.e(TAG, "Unable to create / write to the response file. Will write the response data to the internal data directory."); } } } if (tiFile == null) { outFile = TiFileFactory.createDataFile("tihttp", "tmp"); tiFile = new TiFile(outFile, outFile.getAbsolutePath(), false); } if (dumpResponseOut) { ByteArrayOutputStream byteStream = (ByteArrayOutputStream) responseOut; tiFile.write(TiBlob.blobFromData(byteStream.toByteArray()), false); } responseOut = new FileOutputStream(outFile, dumpResponseOut); responseData = TiBlob.blobFromFile(tiFile, contentType); return tiFile; } private void createFileFromBlob(TiBlob blob, File file) throws FileNotFoundException, IOException { BufferedInputStream bufferedInput = new BufferedInputStream(blob.getInputStream()); BufferedOutputStream bufferedOutput = new BufferedOutputStream(new FileOutputStream(file)); byte[] buffer = new byte[1024 * 1024 * 8]; // 8MB buffer int available = -1; while((available = bufferedInput.read(buffer)) > 0) { bufferedOutput.write(buffer, 0, available); } bufferedOutput.flush(); bufferedOutput.close(); bufferedInput.close(); } private void handleEntityData(byte[] data, int size, long totalSize, long contentLength) throws IOException { if (responseOut == null) { if (responseFile != null) { createFileResponseData(false); } else if (contentLength > maxBufferSize) { createFileResponseData(false); } else { long streamSize = contentLength > 0 ? contentLength : 512; responseOut = new ByteArrayOutputStream((int)streamSize); } } if (totalSize > maxBufferSize && responseOut instanceof ByteArrayOutputStream) { // Content length may not have been reported, dump the current stream // to a file and re-open as a FileOutputStream w/ append createFileResponseData(true); } responseOut.write(data, 0, size); KrollDict callbackData = new KrollDict(); callbackData.put("totalCount", contentLength); callbackData.put("totalSize", totalSize); callbackData.put("size", size); byte[] blobData = new byte[size]; System.arraycopy(data, 0, blobData, 0, size); TiBlob blob = TiBlob.blobFromData(blobData, contentType); callbackData.put("blob", blob); double progress = ((double)totalSize)/((double)contentLength); // return progress as -1 if it is outside the valid range if (progress > 1 || progress < 0) { progress = NetworkModule.PROGRESS_UNKNOWN; } callbackData.put("progress", progress); dispatchCallback(TiC.PROPERTY_ONDATASTREAM, callbackData); } private void finishedReceivingEntityData(long contentLength) throws IOException { if (responseOut instanceof ByteArrayOutputStream) { ByteArrayOutputStream byteStream = (ByteArrayOutputStream) responseOut; responseData = TiBlob.blobFromData(byteStream.toByteArray(), contentType); } responseOut.close(); responseOut = null; } private interface ProgressListener { public void progress(int progress); } private class ProgressOutputStream extends FilterOutputStream { private ProgressListener listener; private int transferred = 0, lastTransferred = 0; public ProgressOutputStream(OutputStream delegate, ProgressListener listener) { super(delegate); this.listener = listener; } private void fireProgress() { // filter to 512 bytes of granularity if (transferred - lastTransferred >= 512) { lastTransferred = transferred; listener.progress(transferred); } } @Override public void write(int b) throws IOException { //Donot write if request is aborted if (!aborted) { super.write(b); transferred++; fireProgress(); } } } public TiHTTPClient(HTTPClientProxy proxy) { this.proxy = proxy; if (httpClientThreadCounter == null) { httpClientThreadCounter = new AtomicInteger(); } readyState = 0; responseText = ""; connected = false; this.nvPairs = new ArrayList<NameValuePair>(); this.parts = new HashMap<String,ContentBody>(); this.maxBufferSize = TiApplication.getInstance() .getAppProperties().getInt(PROPERTY_MAX_BUFFER_SIZE, DEFAULT_MAX_BUFFER_SIZE); } public int getReadyState() { synchronized(this) { this.notify(); } return readyState; } public boolean validatesSecureCertificate() { if (proxy.hasProperty("validatesSecureCertificate")) { return TiConvert.toBoolean(proxy.getProperty("validatesSecureCertificate")); } else { if (TiApplication.getInstance().getDeployType().equals( TiApplication.DEPLOY_TYPE_PRODUCTION)) { return true; } } return false; } /* public void addAuthFactory(String scheme, AuthSchemeFactory theFactory) { customAuthenticators.put(scheme, theFactory); } */ public void setReadyState(int readyState) { Log.d(TAG, "Setting ready state to " + readyState); this.readyState = readyState; KrollDict data = new KrollDict(); data.put("readyState", Integer.valueOf(readyState)); dispatchCallback(TiC.PROPERTY_ONREADYSTATECHANGE, data); if (readyState == READY_STATE_DONE) { KrollDict data1 = new KrollDict(); data1.putCodeAndMessage(TiC.ERROR_CODE_NO_ERROR, null); dispatchCallback(TiC.PROPERTY_ONLOAD, data1); } } private String decodeResponseData(String charsetName) { Charset charset; try { charset = Charset.forName(charsetName); } catch (IllegalArgumentException e) { Log.e(TAG, "Could not find charset: " + e.getMessage()); return null; } CharsetDecoder decoder = charset.newDecoder(); ByteBuffer in = ByteBuffer.wrap(responseData.getBytes()); try { CharBuffer decodedText = decoder.decode(in); return decodedText.toString(); } catch (CharacterCodingException e) { return null; } catch (OutOfMemoryError e) { Log.e(TAG, "Not enough memory to decode response data."); return null; } } /** * Attempts to scan the response data to determine the encoding of the text. * Looks for meta information usually found in HTML or XML documents. * * @return The name of the encoding if detected, otherwise null if no encoding could be determined. */ private String detectResponseDataEncoding() { String regex; if (contentType == null) { Log.w(TAG, "Could not detect charset, no content type specified.", Log.DEBUG_MODE); return null; } else if (contentType.contains("xml")) { regex = XML_DECLARATION_TAG_REGEX; } else if (contentType.contains("html")) { regex = HTML_META_TAG_REGEX; } else { Log.w(TAG, "Cannot detect charset, unknown content type: " + contentType, Log.DEBUG_MODE); return null; } CharSequence responseSequence = responseData.toString(); Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(responseSequence); if (matcher.find()) { return matcher.group(1); } return null; } public String getResponseText() { if (responseText != null || responseData == null) { return responseText; } // First try decoding the response data using the charset // specified in the response content-type header. if (charset != null) { responseText = decodeResponseData(charset); if (responseText != null) { return responseText; } } // If the first attempt to decode fails try detecting the correct // charset by scanning the response data. String detectedCharset = detectResponseDataEncoding(); if (detectedCharset != null) { Log.d(TAG, "detected charset: " + detectedCharset, Log.DEBUG_MODE); responseText = decodeResponseData(detectedCharset); if (responseText != null) { charset = detectedCharset; return responseText; } } // As a last resort try our fallback charsets to decode the data. for (String charset : FALLBACK_CHARSETS) { responseText = decodeResponseData(charset); if (responseText != null) { return responseText; } } Log.e(TAG, "Could not decode response text."); return responseText; } public TiBlob getResponseData() { return responseData; } public DocumentProxy getResponseXML() { // avoid eating up tons of memory if we have a large binary data blob if (TiMimeTypeHelper.isBinaryMimeType(contentType)) { return null; } if (responseXml == null && (responseData != null || responseText != null)) { try { String text = getResponseText(); if (text == null || text.length() == 0) { return null; } if (charset != null && charset.length() > 0) { responseXml = XMLModule.parse(text, charset); } else { responseXml = XMLModule.parse(text); } } catch (Exception e) { Log.e(TAG, "Error parsing XML", e); } } return responseXml; } public void setResponseText(String responseText) { this.responseText = responseText; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public String getStatusText() { return statusText; } public void setStatusText(String statusText) { this.statusText = statusText; } public void abort() { if (readyState > READY_STATE_UNSENT && readyState < READY_STATE_DONE) { aborted = true; if (client != null) { client.disconnect(); client = null; } // Fire the disposehandle event if the request is aborted. // And it will dispose the handle of the httpclient in the JS. proxy.fireEvent(TiC.EVENT_DISPOSE_HANDLE, null); } } public String getAllResponseHeaders() { String result = ""; if(responseHeaders!=null && !responseHeaders.isEmpty()){ StringBuilder sb = new StringBuilder(256); Set<Map.Entry<String, List<String>>> entrySet = responseHeaders.entrySet(); for (Map.Entry<String, List<String>> entry : entrySet) { String headerName = entry.getKey(); sb.append(headerName).append(":"); List<String> headerValues = entry.getValue(); for (String value : headerValues) { sb.append(value).append("\n"); } } result = sb.toString(); } return result; } public void clearCookies(String url) { List<HttpCookie> cookies = new ArrayList<HttpCookie>(cookieManager.getCookieStore().getCookies()); cookieManager.getCookieStore().removeAll(); String lower_url = url.toLowerCase(); for (HttpCookie cookie : cookies) { String cookieDomain = cookie.getDomain(); if (!lower_url.contains(cookieDomain.toLowerCase())) { URI uriDomain; try { uriDomain = new URI(cookieDomain); } catch (URISyntaxException e) { uriDomain = null; } cookieManager.getCookieStore().add(uriDomain, cookie); } } } public void setRequestHeader(String header, String value) { if (readyState <= READY_STATE_OPENED) { if (value == null) { // If value is null, remove header requestHeaders.remove(header); } else { if (requestHeaders.containsKey(header)){ // Appends a value to a header // If it is a cookie, use ';'. If not, use ','. String separator = ("Cookie".equalsIgnoreCase(header))? "; " : ", "; StringBuffer val = new StringBuffer(requestHeaders.get(header)); val.append(separator+value); requestHeaders.put(header, val.toString()); } else { // Set header for the first time requestHeaders.put(header, value); } } } else { throw new IllegalStateException("setRequestHeader can only be called before invoking send."); } } public String getResponseHeader(String getHeaderName) { String result = ""; if (!responseHeaders.isEmpty()) { boolean firstPass = true; StringBuilder sb = new StringBuilder(256); Set<Map.Entry<String, List<String>>> entrySet = responseHeaders.entrySet(); for (Map.Entry<String, List<String>> entry : entrySet) { String headerName = entry.getKey(); if (headerName != null && headerName.equalsIgnoreCase(getHeaderName)) { List<String> headerValues = entry.getValue(); for (String value : headerValues) { if (!firstPass) { sb.append(", "); } sb.append(value); firstPass = false; } } } result = sb.toString(); } if (result.length() == 0) { Log.w(TAG, "No value for response header: " + getHeaderName, Log.DEBUG_MODE); } return result; } public void open(String method, String url) { Log.d(TAG, "open request method=" + method + " url=" + url, Log.DEBUG_MODE); if (url == null) { Log.e(TAG, "Unable to open a null URL"); throw new IllegalArgumentException("URL cannot be null"); } // if the url is not prepended with either http or // https, then default to http and prepend the protocol // to the url String lowerCaseUrl = url.toLowerCase(); if (!lowerCaseUrl.startsWith("http: url = "http://" + url; } if (autoEncodeUrl) { this.uri = TiUrl.getCleanUri(url); } else { this.uri = Uri.parse(url); } // If the original url does not contain any // escaped query string (i.e., does not look // pre-encoded), go ahead and reset it to the // clean uri. Else keep it as is so the user's // escaping stays in effect. The users are on their own // at that point. if (autoEncodeUrl && !url.matches(".*\\?.*\\%\\d\\d.*$")) { this.url = this.uri.toString(); } else { this.url = url; } redirectedLocation = null; this.method = method; String hostString = uri.getHost(); int port = PROTOCOL_DEFAULT_PORT; // The Android Uri doesn't seem to handle user ids with at-signs (@) in them // properly, even if the @ is escaped. It will set the host (uri.getHost()) to // the part of the user name after the @. For example, this Uri would get // the host set to appcelerator.com when it should be mickey.com: // ... even if that first one is escaped to ... // Tests show that Java URL handles it properly, however. So revert to using Java URL.getHost() // if we see that the Uri.getUserInfo has an at-sign in it. // Also, uri.getPort() will throw an exception as it will try to parse what it thinks is the port // part of the Uri (":password....") as an int. So in this case we'll get the port number // as well from Java URL. See Lighthouse ticket 2150. if (uri.getUserInfo() != null && uri.getUserInfo().contains("@")) { URL javaUrl; try { javaUrl = new URL(uri.toString()); hostString = javaUrl.getHost(); port = javaUrl.getPort(); } catch (MalformedURLException e) { Log.e(TAG, "Error attempting to derive Java url from uri: " + e.getMessage(), e); } } else { port = uri.getPort(); } Log.d( TAG, "Instantiating host with hostString='" + hostString + "', port='" + port + "', scheme='" + uri.getScheme() + "'", Log.DEBUG_MODE); username = proxy.getUsername(); password = proxy.getPassword(); if ((username != null) && (password != null)) { hasAuthentication = true; } setReadyState(READY_STATE_OPENED); setRequestHeader("User-Agent", TITANIUM_USER_AGENT); // Causes Auth to Fail with twitter and other size apparently block X- as well // Ticket #729, ignore twitter for now if (!hostString.contains("twitter.com")) { setRequestHeader("X-Requested-With","XMLHttpRequest"); } else { Log.i(TAG, "Twitter: not sending X-Requested-With header", Log.DEBUG_MODE); } } public void setRawData(Object data) { this.data = data; } public void addPostData(String name, String value) throws UnsupportedEncodingException { if (value == null) { value = ""; } if (needMultipart) { // JGH NOTE: this seems to be a bug in RoR where it would puke if you // send a content-type of text/plain for key/value pairs in form-data // so we send an empty string by default instead which will cause the // StringBody to not include the content-type header. this should be // harmless for all other cases parts.put(name, new StringBody(value,"",null)); } else { nvPairs.add(new NameValuePair(name, value.toString())); } } private void dispatchCallback(String name, KrollDict data) { if (data == null) { data = new KrollDict(); } data.put("source", proxy); proxy.callPropertyAsync(name, new Object[] { data }); } private int addTitaniumFileAsPostData(String name, Object value) { try { // TiResourceFile cannot use the FileBody approach directly, because it requires // a java File object, which you can't get from packaged resources. So // TiResourceFile uses the approach we use for blobs, which is write out the // contents to a temp file, then use that for the FileBody. if (value instanceof TiBaseFile && !(value instanceof TiResourceFile)) { TiBaseFile baseFile = (TiBaseFile) value; FileBody body = new FileBody(baseFile.getNativeFile(), TiMimeTypeHelper.getMimeType(baseFile.nativePath())); parts.put(name, body); return (int)baseFile.getNativeFile().length(); } else if (value instanceof TiBlob || value instanceof TiResourceFile) { TiBlob blob; if (value instanceof TiBlob) { blob = (TiBlob) value; } else { blob = ((TiResourceFile) value).read(); } String mimeType = blob.getMimeType(); File tmpFile = File.createTempFile("tixhr", "." + TiMimeTypeHelper.getFileExtensionFromMimeType(mimeType, "txt")); if (blob.getType() == TiBlob.TYPE_STREAM_BASE64) { FileOutputStream fos = new FileOutputStream(tmpFile); TiBaseFile.copyStream(blob.getInputStream(), new Base64OutputStream(fos, android.util.Base64.DEFAULT)); fos.close(); } else { createFileFromBlob(blob, tmpFile); } tmpFiles.add(tmpFile); FileBody body = new FileBody(tmpFile, mimeType); parts.put(name, body); return (int)tmpFile.length(); } else if (value instanceof HashMap) { // If value is a HashMap, it is actually a JSON JSONObject jsonObject = TiConvert.toJSON( (HashMap<String, Object>) value); JsonBody jsonBody = new JsonBody(jsonObject, null); parts.put(name, jsonBody); return (int) jsonBody.getContentLength(); } else { if (value != null) { Log.e(TAG, name + " is a " + value.getClass().getSimpleName()); } else { Log.e(TAG, name + " is null"); } } } catch (IOException e) { Log.e(TAG, "Error adding post data ("+name+"): " + e.getMessage()); } return 0; } private void setUpSSL(boolean validating, HttpsURLConnection securedConnection) { SSLSocketFactory sslSocketFactory = null; if (this.securityManager != null) { if (this.securityManager.willHandleURL(this.uri)) { TrustManager[] trustManagerArray = this.securityManager.getTrustManagers(this.proxy); KeyManager[] keyManagerArray = this.securityManager.getKeyManagers(this.proxy); try { sslSocketFactory = new TiSocketFactory(keyManagerArray, trustManagerArray, tlsVersion); } catch(Exception e) { Log.e(TAG, "Error creating SSLSocketFactory: " + e.getMessage()); sslSocketFactory = null; } } } if (sslSocketFactory == null) { if (trustManagers.size() > 0 || keyManagers.size() > 0) { TrustManager[] trustManagerArray = null; KeyManager[] keyManagerArray = null; if (trustManagers.size() > 0) { trustManagerArray = new X509TrustManager[trustManagers.size()]; trustManagerArray = trustManagers.toArray(trustManagerArray); } if (keyManagers.size() > 0) { keyManagerArray = new X509KeyManager[keyManagers.size()]; keyManagerArray = keyManagers.toArray(keyManagerArray); } try { sslSocketFactory = new TiSocketFactory(keyManagerArray, trustManagerArray, tlsVersion); } catch(Exception e) { Log.e(TAG, "Error creating SSLSocketFactory: " + e.getMessage()); sslSocketFactory = null; } } else if (!validating) { TrustManager trustManagerArray[] = new TrustManager[] { new NonValidatingTrustManager() }; try { sslSocketFactory = new TiSocketFactory(null, trustManagerArray, tlsVersion); } catch(Exception e) { Log.e(TAG, "Error creating SSLSocketFactory: " + e.getMessage()); sslSocketFactory = null; } } else { try { sslSocketFactory = new TiSocketFactory(null, null, tlsVersion); } catch(Exception e) { Log.e(TAG, "Error creating SSLSocketFactory: " + e.getMessage()); sslSocketFactory = null; } } } if (sslSocketFactory != null) { securedConnection.setSSLSocketFactory(sslSocketFactory); } else if (!validating) { securedConnection.setSSLSocketFactory(new NonValidatingSSLSocketFactory()); } if (!validating) { securedConnection.setHostnameVerifier(new NullHostNameVerifier()); } // Fortunately, HttpsURLConnection supports SNI since Android 2.3. // We don't have to handle SNI explicitly } private Object titaniumFileAsPutData(Object value) { if (value instanceof TiBaseFile && !(value instanceof TiResourceFile)) { TiBaseFile baseFile = (TiBaseFile) value; return new FileEntity(baseFile.getNativeFile(), TiMimeTypeHelper.getMimeType(baseFile.nativePath())); } else if (value instanceof TiBlob || value instanceof TiResourceFile) { try { TiBlob blob; if (value instanceof TiBlob) { blob = (TiBlob) value; } else { blob = ((TiResourceFile) value).read(); } String mimeType = blob.getMimeType(); File tmpFile = File.createTempFile("tixhr", "." + TiMimeTypeHelper.getFileExtensionFromMimeType(mimeType, "txt")); createFileFromBlob(blob, tmpFile); tmpFiles.add(tmpFile); return new FileEntity(tmpFile, mimeType); } catch (IOException e) { Log.e(TAG, "Error adding put data: " + e.getMessage()); } } return value; } public void send(Object userData) throws UnsupportedEncodingException { aborted = false; // TODO consider using task manager int totalLength = 0; needMultipart = false; if (userData != null) { if (userData instanceof HashMap) { HashMap<String, Object> data = (HashMap) userData; boolean isPostOrPutOrPatch = method.equals("POST") || method.equals("PUT") || method.equals("PATCH"); boolean isGet = !isPostOrPutOrPatch && method.equals("GET"); // first time through check if we need multipart for POST for (String key : data.keySet()) { Object value = data.get(key); if(value != null) { // if the value is a proxy, we need to get the actual file object if (value instanceof TiFileProxy) { value = ((TiFileProxy) value).getBaseFile(); } if (value instanceof TiBaseFile || value instanceof TiBlob) { needMultipart = true; break; } } } boolean queryStringAltered = false; for (String key : data.keySet()) { Object value = data.get(key); if (isPostOrPutOrPatch && (value != null)) { // if the value is a proxy, we need to get the actual file object if (value instanceof TiFileProxy) { value = ((TiFileProxy) value).getBaseFile(); } if (value instanceof TiBaseFile || value instanceof TiBlob || value instanceof HashMap) { totalLength += addTitaniumFileAsPostData(key, value); } else { String str = TiConvert.toString(value); addPostData(key, str); totalLength += str.length(); } } else if (isGet) { uri = uri.buildUpon().appendQueryParameter( key, TiConvert.toString(value)).build(); queryStringAltered = true; } } if (queryStringAltered) { this.url = uri.toString(); } } else if (userData instanceof TiFileProxy || userData instanceof TiBaseFile || userData instanceof TiBlob) { Object value = userData; if (value instanceof TiFileProxy) { value = ((TiFileProxy) value).getBaseFile(); } if (value instanceof TiBaseFile || value instanceof TiBlob) { setRawData(titaniumFileAsPutData(value)); } else { setRawData(TiConvert.toString(value)); } } else { setRawData(TiConvert.toString(userData)); } } Log.d(TAG, "Instantiating http request with method='" + method + "' and this url:", Log.DEBUG_MODE); Log.d(TAG, this.url, Log.DEBUG_MODE); clientThread = new Thread(new ClientRunnable(totalLength), "TiHttpClient-" + httpClientThreadCounter.incrementAndGet()); clientThread.setPriority(Thread.MIN_PRIORITY); clientThread.start(); Log.d(TAG, "Leaving send()", Log.DEBUG_MODE); } private class ClientRunnable implements Runnable { private final int totalLength; private int contentLength; private PrintWriter printWriter; private OutputStream outputStream; private String boundary; private static final String LINE_FEED = "\r\n"; public ClientRunnable(int totalLength) { this.totalLength = totalLength; this.contentLength = 0; } public void run() { try { Thread.sleep(10); Log.d(TAG, "send()", Log.DEBUG_MODE); //If there are any custom authentication factories registered with the client add them here /* Enumeration<String> authSchemes = customAuthenticators.keys(); while (authSchemes.hasMoreElements()) { String scheme = authSchemes.nextElement(); client.getAuthSchemes().register(scheme, customAuthenticators.get(scheme)); } */ Log.d(TAG, "Preparing to execute request", Log.DEBUG_MODE); String result = null; try { mURL = new URL(url); client = (HttpURLConnection) mURL.openConnection(); boolean isPostOrPutOrPatch = method.equals("POST") || method.equals("PUT") || method.equals("PATCH"); setUpClient(client, isPostOrPutOrPatch); if (isPostOrPutOrPatch) { UrlEncodedFormEntity form = null; if (nvPairs.size() > 0) { try { form = new UrlEncodedFormEntity(nvPairs, "UTF-8"); } catch (UnsupportedEncodingException e) { Log.e(TAG, "Unsupported encoding: ", e); } } // calculate content length if (parts.size() > 0 && needMultipart) { for(String name : parts.keySet()) { contentLength += constructFilePart(name, parts.get(name)).length(); contentLength += parts.get(name).getContentLength() + 2; } if (form != null) { contentLength += (int) form.getContentLength(); try { ByteArrayOutputStream bos = new ByteArrayOutputStream((int) form.getContentLength()); form.writeTo(bos); contentLength += constructFilePart("form", new StringBody(bos.toString(), "application/x-www-form-urlencoded", Charset.forName("UTF-8"))).length(); contentLength += form.getContentLength() + 2; } catch (UnsupportedEncodingException e) { Log.e(TAG, "Unsupported encoding: ", e); } catch (IOException e) { Log.e(TAG, "Error converting form to string: ", e); } } contentLength += 6 + boundary.length(); } else { if (data instanceof String) { contentLength += ((String) data).getBytes().length; } else if (data instanceof FileEntity) { contentLength += ((FileEntity) data).getContentLength(); } else if (form != null) { contentLength += (int) form.getContentLength(); } } // disable internal buffer client.setFixedLengthStreamingMode(contentLength); outputStream = new ProgressOutputStream(client.getOutputStream(), new ProgressListener() { public void progress(int progress) { KrollDict data = new KrollDict(); double currentProgress = ((double) progress/totalLength); if (currentProgress > 1) currentProgress = 1; data.put("progress", currentProgress); dispatchCallback(TiC.PROPERTY_ONSENDSTREAM, data); } }); printWriter = new PrintWriter(outputStream, true); if (parts.size() > 0 && needMultipart) { for(String name : parts.keySet()) { Log.d(TAG, "adding part " + name + ", part type: " + parts.get(name).getMimeType() + ", len: " + parts.get(name).getContentLength(), Log.DEBUG_MODE); addFilePart(name, parts.get(name)); } if (form != null) { try { ByteArrayOutputStream bos = new ByteArrayOutputStream((int) form.getContentLength()); form.writeTo(bos); addFilePart("form", new StringBody(bos.toString(), "application/x-www-form-urlencoded", Charset.forName("UTF-8"))); } catch (UnsupportedEncodingException e) { Log.e(TAG, "Unsupported encoding: ", e); } catch (IOException e) { Log.e(TAG, "Error converting form to string: ", e); } } completeSendingMultipart(); } else { handleURLEncodedData(form); } } // HttpURLConnection does not follow redirects from HTTPS to HTTP (vice versa). // This section of the code handles that. if (autoRedirect) { // Hardcoded to follow a max of 5 redirects for (int i = 0; i < REDIRECTS; i++) { // Checks manually if a redirect is needed int status = client.getResponseCode(); if (status != HttpURLConnection.HTTP_OK && (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER)) { redirectedLocation = client.getHeaderField("Location"); if (redirectedLocation != null) { client.disconnect(); client = (HttpURLConnection) new URL(redirectedLocation).openConnection(); // Configure the headers and SSL connection again if required setUpClient(client, isPostOrPutOrPatch); } else { // There are no redirected URLs to follow. break; } } else { // No more redirects to follow. break; } } } handleResponse(client); }catch (IOException e) { if (!aborted) { throw e; } } finally { if (client != null) { client.disconnect(); } } if(result != null) { Log.d(TAG, "Have result back from request len=" + result.length(), Log.DEBUG_MODE); } connected = false; setResponseText(result); if (getStatus() >= 400) { throw new IOException(getStatus() + " : " + getStatusText()); } if (!aborted) { setReadyState(READY_STATE_DONE); } } catch(Throwable t) { if (client != null) { Log.d(TAG, "clearing the expired and idle connections", Log.DEBUG_MODE); client.disconnect(); } else { Log.d(TAG, "client is not valid, unable to clear expired and idle connections"); } String msg = t.getMessage(); if (msg == null && t.getCause() != null) { msg = t.getCause().getMessage(); } if (msg == null) { msg = t.getClass().getName(); } Log.e(TAG, "HTTP Error (" + t.getClass().getName() + "): " + msg, t); KrollDict data = new KrollDict(); data.putCodeAndMessage((getStatus() >= 400)? getStatus() : TiC.ERROR_CODE_UNKNOWN, msg); dispatchCallback(TiC.PROPERTY_ONERROR, data); } finally { deleteTmpFiles(); //Clean up client and clientThread client = null; clientThread = null; // Fire the disposehandle event if the request is finished successfully or the errors occur. // And it will dispose the handle of the httpclient in the JS. proxy.fireEvent(TiC.EVENT_DISPOSE_HANDLE, null); } } protected void setUpClient(HttpURLConnection client, Boolean isPostOrPutOrPatch) throws ProtocolException { client.setInstanceFollowRedirects(autoRedirect); if (client instanceof HttpsURLConnection) { HttpsURLConnection securedConnection = (HttpsURLConnection) client; setUpSSL(validatesSecureCertificate(), securedConnection); } if (timeout != -1) { client.setReadTimeout(timeout); client.setConnectTimeout(timeout); } if (aborted) { return; } client.setRequestMethod(method); client.setDoInput(true); if (isPostOrPutOrPatch) { client.setDoOutput(true); } client.setUseCaches(false); //Set Authorization value for Basic authentication if (hasAuthentication) { String domain = proxy.getDomain(); if (domain != null) { username = domain + "\\" + username; } String encodedCredentials = Base64.encodeToString((username + ":" + password).getBytes(),Base64.DEFAULT); client.setRequestProperty("Authorization", "Basic " + encodedCredentials); } // This is to set gzip default to disable client.setRequestProperty("Accept-Encoding", "identity"); client.setRequestProperty(TITANIUM_ID_HEADER, TiApplication.getInstance().getAppGUID()); if (parts.size() > 0 && needMultipart) { boundary = HttpUrlConnectionUtils.generateBoundary(); client.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); } else if (isPostOrPutOrPatch) { client.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); } for (String header : requestHeaders.keySet()) { client.setRequestProperty(header, requestHeaders.get(header)); } } private String constructFilePart(String name, ContentBody contentBody) { String part = ""; String fileName = contentBody.getFilename(); part += "--" + boundary + LINE_FEED; part += "Content-Disposition: form-data; name=\"" + name + "\""; if (fileName != null) { part += "; filename=\"" + fileName + "\""; } part += LINE_FEED; String mimeType = contentBody.getMimeType(); if (mimeType != null && !mimeType.isEmpty()) { part += "Content-Type: " + contentBody.getMimeType(); if (contentBody.getCharset() != null) { part += "; charset=" + contentBody.getCharset(); } part += LINE_FEED; } part += "Content-Transfer-Encoding: "+ contentBody.getTransferEncoding() + LINE_FEED + LINE_FEED; return part; } private void addFilePart(String name, ContentBody contentBody) throws IOException{ printWriter.append(constructFilePart(name, contentBody)); printWriter.flush(); contentBody.writeTo(outputStream); printWriter.append(LINE_FEED); printWriter.flush(); } public void completeSendingMultipart() throws IOException { printWriter.append("--" + boundary + "--").append(LINE_FEED); printWriter.close(); } private void handleURLEncodedData(UrlEncodedFormEntity form) throws IOException { //If set rawDate is set with a String, need to do this Entity entity = null; if (data instanceof String) { try { entity = new StringEntity((String) data, "UTF-8"); } catch(Exception ex) { //FIXME Log.e(TAG, "Exception, implement recovery: ", ex); } } else if (data instanceof Entity) { entity = (Entity) data; } else { entity = form; } //This code sets the content type from the headers //Then casts the request so that it can put in the form which is the entity. if (entity != null) { entity.writeTo(outputStream); printWriter.flush(); } } } private void deleteTmpFiles() { if (tmpFiles.isEmpty()) { return; } for (File tmpFile : tmpFiles) { tmpFile.delete(); } tmpFiles.clear(); } public String getLocation() { if (redirectedLocation != null) { return redirectedLocation; } return url; } public String getConnectionType() { return method; } public boolean isConnected() { return connected; } public void setTimeout(int millis) { timeout = millis; } protected void setAutoEncodeUrl(boolean value) { autoEncodeUrl = value; } protected boolean getAutoEncodeUrl() { return autoEncodeUrl; } protected void setAutoRedirect(boolean value) { autoRedirect = value; } protected boolean getAutoRedirect() { return autoRedirect; } protected void addKeyManager(X509KeyManager manager) { if (Log.isDebugModeEnabled()) { Log.d(TAG, "addKeyManager method is deprecated. Use the securityManager property on the HttpClient to define custom SSL Contexts", Log.DEBUG_MODE); } keyManagers.add(manager); } protected void addTrustManager(X509TrustManager manager) { if (Log.isDebugModeEnabled()) { Log.d(TAG, "addTrustManager method is deprecated. Use the securityManager property on the HttpClient to define custom SSL Contexts", Log.DEBUG_MODE); } trustManagers.add(manager); } protected void setTlsVersion(int value) { this.proxy.setProperty(TiC.PROPERTY_TLS_VERSION, value); tlsVersion = value; } }
package com.artursworld.reactiontest.view.games; import android.app.Activity; import android.content.Intent; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.text.InputType; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.Spinner; import com.afollestad.materialdialogs.DialogAction; import com.afollestad.materialdialogs.MaterialDialog; import com.artursworld.reactiontest.R; import com.artursworld.reactiontest.controller.adapters.CustomSpinnerAdapter; import com.artursworld.reactiontest.controller.adapters.MedicalUserSpinnerAdapter; import com.artursworld.reactiontest.controller.helper.Type; import com.artursworld.reactiontest.controller.util.UtilsRG; import com.artursworld.reactiontest.model.entity.MedicalUser; import com.artursworld.reactiontest.model.entity.OperationIssue; import com.artursworld.reactiontest.model.persistence.manager.MedicalUserManager; import com.artursworld.reactiontest.model.persistence.manager.OperationIssueManager; import com.artursworld.reactiontest.view.settings.SettingsActivity; import com.artursworld.reactiontest.view.user.AddMedicalUser; import com.artursworld.reactiontest.view.user.UserManagementView; import com.roughike.swipeselector.SwipeItem; import com.roughike.swipeselector.SwipeSelector; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * Displays pre configuration. The user can select the game type, test type, the operation etc. * before the game can start. */ public class StartGameSettings extends AppCompatActivity { // Extras constants to transmit values from activity to other activity public final static String EXTRA_MEDICAL_USER_ID = "com.artursworld.reactiontest.EXTRA_MEDICAL_USER_ID"; public final static String EXTRA_OPERATION_ISSUE_NAME = "com.artursworld.reactiontest.EXTRA_OPERATION_ISSUE_NAME"; public final static String EXTRA_TEST_TYPE = "com.artursworld.reactiontest.EXTRA_TEST_TYPE"; public final static String EXTRA_GAME_TYPE = "com.artursworld.reactiontest.EXTRA_GAME_TYPE"; public final static String EXTRA_REACTION_GAME_ID = "com.artursworld.reactiontest.EXTRA_REACTION_GAME_ID"; // UI elements private Spinner medicalUserSpinner; private Spinner operationIssueSpinner; private SwipeSelector testTypeSelector; private SwipeSelector gameTypeSelector; private String selectedMedicalUserId; // List of operations for a certain user private List<OperationIssue> selectedOperationIssuesList; private Activity activity; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); activity = this; setContentView(R.layout.activity_start_game_settings); initToolBar(); initGuiElements(); initMedicalUserSpinnerAsync(); addSwipeElements(); } @Override protected void onResume() { super.onResume(); initMedicalUserSpinnerAsync(); } private void addSwipeElements() { if (activity != null) { addItemsIntoSwipeSelector(Type.getTestTypesList(activity), testTypeSelector, R.id.test_type_swipe_selector); addItemsIntoSwipeSelector(Type.getGameTypesList(activity), gameTypeSelector, R.id.game_type_swipe_selector); } } /** * Initializes the toolbar */ private void initToolBar() { Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); if (toolbar != null) { int color = 0; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { color = getResources().getColor(R.color.colorPrimaryWhite, getTheme()); } else { color = getResources().getColor(R.color.colorPrimaryWhite); } toolbar.setTitleTextColor(color); setSupportActionBar(toolbar); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayShowTitleEnabled(true); } } } /** * Adds all operations of the selected user into a spinner */ public void addItemsOnOperationIssueSpinner(List<OperationIssue> selectedOperationIssuesList, Spinner operationIssueSpinner) { if (operationIssueSpinner == null) operationIssueSpinner = (Spinner) findViewById(R.id.start_game_settings_operation_issue_spinner); List<String> list = new ArrayList<String>(); if (selectedOperationIssuesList != null) { if (selectedOperationIssuesList.size() > 0) { for (OperationIssue issue : selectedOperationIssuesList) { list.add(issue.getDisplayName()); } } else { list.add(getResources().getString(R.string.create_automatic)); } } //ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list); CustomSpinnerAdapter dataAdapter = new CustomSpinnerAdapter(this, list); //dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); operationIssueSpinner.setAdapter(dataAdapter); } /** * Helper method for adding Strings into a swipe selector */ public void addItemsIntoSwipeSelector(SwipeItem[] items, SwipeSelector selector, int rId) { if (selector == null) selector = (SwipeSelector) findViewById(rId); selector.setItems(items); } /** * Initializes UI elements */ private void initGuiElements() { medicalUserSpinner = (Spinner) findViewById(R.id.start_game_settings_medicalid_spinner); operationIssueSpinner = (Spinner) findViewById(R.id.start_game_settings_operation_issue_spinner); testTypeSelector = (SwipeSelector) findViewById(R.id.test_type_swipe_selector); gameTypeSelector = (SwipeSelector) findViewById(R.id.game_type_swipe_selector); } /** * Sets all a users operations into a list and displays results in a spinnr asynchronous */ private void initOperationIssueListAsync() { new OperationIssueManager.getAllOperationIssuesByMedicoIdAsync(new OperationIssueManager.AsyncResponse() { @Override public void getAllOperationIssuesByMedicoId(List<OperationIssue> operationIssuesList) { selectedOperationIssuesList = operationIssuesList; addItemsOnOperationIssueSpinner(operationIssuesList, operationIssueSpinner); UtilsRG.info("Operation issues loaded for user(" + selectedMedicalUserId + ")=" + operationIssuesList.toString()); } }, getApplicationContext()).execute(selectedMedicalUserId); } /** * Adds all existing users into a spinner asynchronous */ private void initMedicalUserSpinnerAsync() { new MedicalUserManager.getAllMedicalUsers(new MedicalUserManager.AsyncResponse() { @Override public void getMedicalUserList(List<MedicalUser> medicalUserResultList) { initMedicalUserSpinner(medicalUserResultList); } }, getApplicationContext()).execute(); } /** * Uses adapter to display some attributes per user in the spinner */ private void initMedicalUserSpinner(List<MedicalUser> userList) { boolean isEmptyUserList = true; if (userList != null) { if (userList.size() > 0) { isEmptyUserList = false; } // attributes to display per item in spinner String[] medicalIds = new String[userList.size()]; String[] birthDates = new String[userList.size()]; int[] images = new int[userList.size()]; // load those attributes for (int i = 0; i < userList.size(); i++) { medicalIds[i] = userList.get(i).getMedicalId(); birthDates[i] = userList.get(i).getBirthDateAsString(); images[i] = userList.get(i).getImage(); } // use adapter to define UI order MedicalUserSpinnerAdapter adapter = new MedicalUserSpinnerAdapter(this, medicalIds, birthDates, images); medicalUserSpinner.setAdapter(adapter); // add click listener medicalUserSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { selectedMedicalUserId = parent.getItemAtPosition(position).toString(); initOperationIssueListAsync(); UtilsRG.info("selected item: " + selectedMedicalUserId); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } if (isEmptyUserList) { UtilsRG.info("no user to display"); } } /** * Displays dialog to add new operation for the selected user */ public void onAddOperationIssueBtnCLick(View view) { UtilsRG.info("onAddOperationIssueBtnCLick"); new MaterialDialog.Builder(this) .title(R.string.add_operation_issue) .inputType(InputType.TYPE_CLASS_TEXT) .input(R.string.operation_issue_name, R.string.operation_issue_name, new MaterialDialog.InputCallback() { @Override public void onInput(MaterialDialog dialog, CharSequence input) { if (input != null) { if (!input.toString().trim().equals("")) { UtilsRG.info("got new OP issue: " + input.toString()); onFinishInputDialog(input.toString()); initMedicalUserSpinnerAsync(); } } } }).show(); } public void onAddUserButtonClick(View view) { UtilsRG.info("Add User button has been clicked"); Intent intent = new Intent(activity, AddMedicalUser.class); intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); startActivity(intent); } /** * If user typed new operation name --> save new opration issue in database */ public void onFinishInputDialog(final String inputText) { if (inputText != null && !inputText.equals("")) { new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { new OperationIssueManager(getApplicationContext()).insertOperationIssueByMedIdAsync(selectedMedicalUserId, inputText); initMedicalUserSpinnerAsync(); return null; } }.execute(); } } /** * start the game intent and transmit settings to game intent */ public void onStartGameBtnClick(View view) { String medicalUserId = selectedMedicalUserId; String operationIssueName = ""; String testType = ""; String gameType = ""; boolean isCreateAutomatic = (operationIssueSpinner.getSelectedItem().equals(getResources().getString(R.string.create_automatic))); if (operationIssueSpinner == null) operationIssueSpinner = (Spinner) findViewById(R.id.start_game_settings_operation_issue_spinner); if ((operationIssueSpinner.getSelectedItem() == null) || isCreateAutomatic) { operationIssueName = getString(R.string.auto_genrated) + " " + UtilsRG.dayAndhourFormat.format(new Date()); final String finalOperationIssueName = operationIssueName; new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... unusedParams) { OperationIssueManager db = new OperationIssueManager(getApplicationContext()); if (db != null) { db.insertOperationIssueByMedIdAsync(selectedMedicalUserId, finalOperationIssueName); } return null; } }.execute(); } else { operationIssueName = operationIssueSpinner.getSelectedItem().toString(); } if (testTypeSelector != null) { SwipeItem selectedItem = testTypeSelector.getSelectedItem(); Type.TestTypes typeTest = Type.getTestType((Integer) selectedItem.value); testType = Type.getTestType(typeTest); } if (gameTypeSelector != null) { SwipeItem selectedItem = gameTypeSelector.getSelectedItem(); Type.GameTypes gameTest = Type.getGameType((Integer) selectedItem.value); gameType = Type.getGameType(gameTest); } UtilsRG.info("User(" + medicalUserId + ") with operation name(" + operationIssueName + "). Test type=" + testType + ", GameType=" + gameType); startGameActivityByTypes(medicalUserId, operationIssueName, gameType, testType); } private void startGameActivityByTypes(String medicalUserId, String operationIssueName, String gameType, String testType) { if (gameType != null && testType != null) { UtilsRG.putString(UtilsRG.MEDICAL_USER, medicalUserId, this); UtilsRG.putString(UtilsRG.OPERATION_ISSUE, operationIssueName, this); UtilsRG.putString(UtilsRG.GAME_TYPE, gameType, this); UtilsRG.putString(UtilsRG.TEST_TYPE, testType, this); if (Type.TestTypes.InOperation.name() == testType) { Intent goNoGoGameIntent = new Intent(this, OperationModeView.class); startActivity(goNoGoGameIntent); } else if (Type.GameTypes.GoGame.name() == gameType) { Intent intent = new Intent(this, GoGameView.class); intent.putExtra(StartGameSettings.EXTRA_MEDICAL_USER_ID, medicalUserId); intent.putExtra(StartGameSettings.EXTRA_OPERATION_ISSUE_NAME, operationIssueName); intent.putExtra(StartGameSettings.EXTRA_GAME_TYPE, gameType); intent.putExtra(StartGameSettings.EXTRA_TEST_TYPE, testType); intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); startActivity(intent); } else if (Type.GameTypes.GoNoGoGame.name() == gameType) { Intent goNoGoGameIntent = new Intent(this, GoNoGoGameView.class); goNoGoGameIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); startActivity(goNoGoGameIntent); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { UtilsRG.info("onCreateOptionsMenu()"); MenuInflater menuIf = getMenuInflater(); menuIf.inflate(R.menu.launcher_options_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.user_management_option_menu) { UtilsRG.info("Selected Option Menu user_management_option_menu"); Intent intent = new Intent(this, UserManagementView.class); startActivity(intent); } else if (item.getItemId() == R.id.settings_option_menu) { UtilsRG.info("Selected Option Menu settings_option_menu"); Intent intent = new Intent(this, SettingsActivity.class); startActivity(intent); } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { new MaterialDialog.Builder(activity) .title(R.string.attention) .positiveText(R.string.ok) .onPositive(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { StartGameSettings.super.onBackPressed(); } }) .negativeText(R.string.cancel) .content(R.string.do_you_want_to_leave_the_app) .show(); } }
package org.jabref.gui; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.TimerTask; import javafx.application.Platform; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.geometry.Orientation; import javafx.scene.Node; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.ButtonBar; import javafx.scene.control.ButtonType; import javafx.scene.control.Menu; import javafx.scene.control.MenuBar; import javafx.scene.control.MenuItem; import javafx.scene.control.ProgressBar; import javafx.scene.control.Separator; import javafx.scene.control.SeparatorMenuItem; import javafx.scene.control.SplitPane; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; import javafx.scene.control.TextInputControl; import javafx.scene.control.ToolBar; import javafx.scene.control.Tooltip; import javafx.scene.control.skin.TabPaneSkin; import javafx.scene.input.KeyEvent; import javafx.scene.input.TransferMode; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.layout.Priority; import javafx.scene.layout.VBox; import javafx.stage.Stage; import org.jabref.Globals; import org.jabref.JabRefExecutorService; import org.jabref.gui.actions.ActionFactory; import org.jabref.gui.actions.Actions; import org.jabref.gui.actions.OldDatabaseCommandWrapper; import org.jabref.gui.actions.SimpleCommand; import org.jabref.gui.actions.StandardActions; import org.jabref.gui.auximport.NewSubLibraryAction; import org.jabref.gui.bibtexextractor.ExtractBibtexAction; import org.jabref.gui.bibtexkeypattern.BibtexKeyPatternAction; import org.jabref.gui.contentselector.ManageContentSelectorAction; import org.jabref.gui.copyfiles.CopyFilesAction; import org.jabref.gui.customentrytypes.CustomizeEntryAction; import org.jabref.gui.customizefields.SetupGeneralFieldsAction; import org.jabref.gui.dialogs.AutosaveUIManager; import org.jabref.gui.documentviewer.ShowDocumentViewerAction; import org.jabref.gui.duplicationFinder.DuplicateSearch; import org.jabref.gui.edit.ManageKeywordsAction; import org.jabref.gui.edit.MassSetFieldsAction; import org.jabref.gui.edit.OpenBrowserAction; import org.jabref.gui.exporter.ExportCommand; import org.jabref.gui.exporter.ExportToClipboardAction; import org.jabref.gui.exporter.ManageCustomExportsAction; import org.jabref.gui.exporter.SaveAllAction; import org.jabref.gui.exporter.SaveDatabaseAction; import org.jabref.gui.externalfiles.AutoLinkFilesAction; import org.jabref.gui.externalfiles.FindUnlinkedFilesAction; import org.jabref.gui.externalfiletype.EditExternalFileTypesAction; import org.jabref.gui.externalfiletype.ExternalFileTypes; import org.jabref.gui.help.AboutAction; import org.jabref.gui.help.ErrorConsoleAction; import org.jabref.gui.help.HelpAction; import org.jabref.gui.help.SearchForUpdateAction; import org.jabref.gui.importer.ImportCommand; import org.jabref.gui.importer.ImportEntriesDialog; import org.jabref.gui.importer.ManageCustomImportsAction; import org.jabref.gui.importer.NewDatabaseAction; import org.jabref.gui.importer.NewEntryAction; import org.jabref.gui.importer.actions.OpenDatabaseAction; import org.jabref.gui.importer.fetcher.LookupIdentifierAction; import org.jabref.gui.integrity.IntegrityCheckAction; import org.jabref.gui.journals.ManageJournalsAction; import org.jabref.gui.keyboard.CustomizeKeyBindingAction; import org.jabref.gui.keyboard.KeyBinding; import org.jabref.gui.libraryproperties.LibraryPropertiesAction; import org.jabref.gui.menus.FileHistoryMenu; import org.jabref.gui.mergeentries.MergeEntriesAction; import org.jabref.gui.metadata.BibtexStringEditorAction; import org.jabref.gui.metadata.PreambleEditor; import org.jabref.gui.preferences.ShowPreferencesAction; import org.jabref.gui.protectedterms.ManageProtectedTermsAction; import org.jabref.gui.push.PushToApplicationAction; import org.jabref.gui.push.PushToApplicationsManager; import org.jabref.gui.search.GlobalSearchBar; import org.jabref.gui.shared.ConnectToSharedDatabaseCommand; import org.jabref.gui.specialfields.SpecialFieldMenuItemFactory; import org.jabref.gui.texparser.ParseTexAction; import org.jabref.gui.undo.CountingUndoManager; import org.jabref.gui.util.BackgroundTask; import org.jabref.gui.util.DefaultTaskExecutor; import org.jabref.logic.autosaveandbackup.AutosaveManager; import org.jabref.logic.autosaveandbackup.BackupManager; import org.jabref.logic.importer.IdFetcher; import org.jabref.logic.importer.ParserResult; import org.jabref.logic.importer.WebFetchers; import org.jabref.logic.l10n.Localization; import org.jabref.logic.undo.AddUndoableActionEvent; import org.jabref.logic.undo.UndoChangeEvent; import org.jabref.logic.undo.UndoRedoEvent; import org.jabref.logic.util.io.FileUtil; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.database.BibDatabaseMode; import org.jabref.model.database.shared.DatabaseLocation; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.SpecialField; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.preferences.JabRefPreferences; import org.jabref.preferences.LastFocusedTabPreferences; import com.google.common.eventbus.Subscribe; import org.fxmisc.easybind.EasyBind; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The main window of the application. */ public class JabRefFrame extends BorderPane { // Frame titles. public static final String FRAME_TITLE = "JabRef"; private static final Logger LOGGER = LoggerFactory.getLogger(JabRefFrame.class); private final SplitPane splitPane = new SplitPane(); private final JabRefPreferences prefs = Globals.prefs; private final GlobalSearchBar globalSearchBar = new GlobalSearchBar(this, Globals.stateManager); private final ProgressBar progressBar = new ProgressBar(); private final FileHistoryMenu fileHistory; private final Stage mainStage; private final StateManager stateManager; private final CountingUndoManager undoManager; private final PushToApplicationsManager pushToApplicationsManager; private final DialogService dialogService; private final JabRefExecutorService executorService; private SidePaneManager sidePaneManager; private TabPane tabbedPane; private SidePane sidePane; public JabRefFrame(Stage mainStage) { this.mainStage = mainStage; this.dialogService = new JabRefDialogService(mainStage, this); this.stateManager = Globals.stateManager; this.pushToApplicationsManager = new PushToApplicationsManager(dialogService, stateManager); this.undoManager = Globals.undoManager; this.fileHistory = new FileHistoryMenu(prefs, dialogService, getOpenDatabaseAction()); this.executorService = JabRefExecutorService.INSTANCE; } private static BasePanel getBasePanel(Tab tab) { return (BasePanel) tab.getContent(); } private void initDragAndDrop() { Tab dndIndicator = new Tab(Localization.lang("Open files..."), null); dndIndicator.getStyleClass().add("drop"); EasyBind.subscribe(tabbedPane.skinProperty(), skin -> { if (!(skin instanceof TabPaneSkin)) { return; } // We need to get the tab header, the following is a ugly workaround Node tabHeaderArea = ((TabPaneSkin) this.tabbedPane.getSkin()) .getChildren() .stream() .filter(node -> node.getStyleClass().contains("tab-header-area")) .findFirst() .orElseThrow(); tabHeaderArea.setOnDragOver(event -> { if (DragAndDropHelper.hasBibFiles(event.getDragboard())) { event.acceptTransferModes(TransferMode.ANY); if (!tabbedPane.getTabs().contains(dndIndicator)) { tabbedPane.getTabs().add(dndIndicator); } event.consume(); } else { tabbedPane.getTabs().remove(dndIndicator); } }); tabHeaderArea.setOnDragExited(event -> tabbedPane.getTabs().remove(dndIndicator)); tabHeaderArea.setOnDragDropped(event -> { tabbedPane.getTabs().remove(dndIndicator); List<Path> bibFiles = DragAndDropHelper.getBibFiles(event.getDragboard()); OpenDatabaseAction openDatabaseAction = this.getOpenDatabaseAction(); openDatabaseAction.openFiles(bibFiles, true); event.setDropCompleted(true); event.consume(); }); }); } private void initKeyBindings() { addEventFilter(KeyEvent.KEY_PRESSED, event -> { Optional<KeyBinding> keyBinding = Globals.getKeyPrefs().mapToKeyBinding(event); if (keyBinding.isPresent()) { switch (keyBinding.get()) { case FOCUS_ENTRY_TABLE: getCurrentBasePanel().getMainTable().requestFocus(); event.consume(); break; case NEXT_LIBRARY: tabbedPane.getSelectionModel().selectNext(); event.consume(); break; case PREVIOUS_LIBRARY: tabbedPane.getSelectionModel().selectPrevious(); event.consume(); break; case INCREASE_TABLE_FONT_SIZE: increaseTableFontSize(); event.consume(); break; case DECREASE_TABLE_FONT_SIZE: decreaseTableFontSize(); event.consume(); break; case DEFAULT_TABLE_FONT_SIZE: setDefaultTableFontSize(); event.consume(); break; case SEARCH: getGlobalSearchBar().focus(); break; default: } } }); } private void initShowTrackingNotification() { if (!Globals.prefs.shouldAskToCollectTelemetry()) { JabRefExecutorService.INSTANCE.submit(new TimerTask() { @Override public void run() { DefaultTaskExecutor.runInJavaFXThread(JabRefFrame.this::showTrackingNotification); } }, 60000); // run in one minute } } private Void showTrackingNotification() { if (!Globals.prefs.shouldCollectTelemetry()) { boolean shouldCollect = dialogService.showConfirmationDialogAndWait( Localization.lang("Telemetry: Help make JabRef better"), Localization.lang("To improve the user experience, we would like to collect anonymous statistics on the features you use. We will only record what features you access and how often you do it. We will neither collect any personal data nor the content of bibliographic items. If you choose to allow data collection, you can later disable it via Options -> Preferences -> General."), Localization.lang("Share anonymous statistics"), Localization.lang("Don't share")); Globals.prefs.setShouldCollectTelemetry(shouldCollect); } Globals.prefs.askedToCollectTelemetry(); return null; } public void refreshTitleAndTabs() { DefaultTaskExecutor.runInJavaFXThread(() -> { setWindowTitle(); updateAllTabTitles(); }); } /** * Sets the title of the main window. */ public void setWindowTitle() { BasePanel panel = getCurrentBasePanel(); // no database open if (panel == null) { //setTitle(FRAME_TITLE); return; } String mode = panel.getBibDatabaseContext().getMode().getFormattedName(); String modeInfo = String.format(" (%s)", Localization.lang("%0 mode", mode)); boolean isAutosaveEnabled = Globals.prefs.getBoolean(JabRefPreferences.LOCAL_AUTO_SAVE); if (panel.getBibDatabaseContext().getLocation() == DatabaseLocation.LOCAL) { String changeFlag = panel.isModified() && !isAutosaveEnabled ? "*" : ""; String databaseFile = panel.getBibDatabaseContext() .getDatabaseFile() .map(File::getPath) .orElse(GUIGlobals.UNTITLED_TITLE); //setTitle(FRAME_TITLE + " - " + databaseFile + changeFlag + modeInfo); } else if (panel.getBibDatabaseContext().getLocation() == DatabaseLocation.SHARED) { //setTitle(FRAME_TITLE + " - " + panel.getBibDatabaseContext().getDBMSSynchronizer().getDBName() + " [" // + Localization.lang("shared") + "]" + modeInfo); } } /** * The MacAdapter calls this method when a "BIB" file has been double-clicked from the Finder. */ public void openAction(String filePath) { Path file = Paths.get(filePath); // all the logic is done in openIt. Even raising an existing panel getOpenDatabaseAction().openFile(file, true); } /** * The MacAdapter calls this method when "About" is selected from the application menu. */ public void about() { HelpAction.getMainHelpPageCommand().execute(); } public JabRefPreferences prefs() { return prefs; } /** * Tears down all things started by JabRef * <p> * FIXME: Currently some threads remain and therefore hinder JabRef to be closed properly * * @param filenames the filenames of all currently opened files - used for storing them if prefs openLastEdited is * set to true */ private void tearDownJabRef(List<String> filenames) { //prefs.putBoolean(JabRefPreferences.WINDOW_MAXIMISED, getExtendedState() == Frame.MAXIMIZED_BOTH); if (prefs.getBoolean(JabRefPreferences.OPEN_LAST_EDITED)) { // Here we store the names of all current files. If // there is no current file, we remove any // previously stored filename. if (filenames.isEmpty()) { prefs.remove(JabRefPreferences.LAST_EDITED); } else { prefs.putStringList(JabRefPreferences.LAST_EDITED, filenames); File focusedDatabase = getCurrentBasePanel().getBibDatabaseContext().getDatabaseFile().orElse(null); new LastFocusedTabPreferences(prefs).setLastFocusedTab(focusedDatabase); } } fileHistory.storeHistory(); prefs.flush(); } /** * General info dialog. The MacAdapter calls this method when "Quit" is selected from the application menu, Cmd-Q * is pressed, or "Quit" is selected from the Dock. The function returns a boolean indicating if quitting is ok or * not. * <p> * Non-OSX JabRef calls this when choosing "Quit" from the menu * <p> * SIDE EFFECT: tears down JabRef * * @return true if the user chose to quit; false otherwise */ public boolean quit() { // First ask if the user really wants to close, if the library has not been saved since last save. List<String> filenames = new ArrayList<>(); for (int i = 0; i < tabbedPane.getTabs().size(); i++) { BasePanel panel = getBasePanelAt(i); BibDatabaseContext context = panel.getBibDatabaseContext(); if (panel.isModified() && (context.getLocation() == DatabaseLocation.LOCAL)) { tabbedPane.getSelectionModel().select(i); if (!confirmClose(panel)) { return false; } } else if (context.getLocation() == DatabaseLocation.SHARED) { context.convertToLocalDatabase(); context.getDBMSSynchronizer().closeSharedDatabase(); context.clearDBMSSynchronizer(); } AutosaveManager.shutdown(context); BackupManager.shutdown(context); context.getDatabaseFile().map(File::getAbsolutePath).ifPresent(filenames::add); } WaitForSaveFinishedDialog waitForSaveFinishedDialog = new WaitForSaveFinishedDialog(dialogService); waitForSaveFinishedDialog.showAndWait(getBasePanelList()); // Good bye! tearDownJabRef(filenames); Platform.exit(); return true; } private void initLayout() { setProgressBarVisible(false); setId("frame"); VBox head = new VBox(createMenu(),createToolbar()); head.setSpacing(0d); setTop(head); splitPane.getItems().addAll(sidePane, tabbedPane); // We need to wait with setting the divider since it gets reset a few times during the initial set-up mainStage.showingProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean showing) { if (showing) { setDividerPosition(); EasyBind.subscribe(sidePane.visibleProperty(), visible -> { if (visible) { if (!splitPane.getItems().contains(sidePane)) { splitPane.getItems().add(0, sidePane); setDividerPosition(); } } else { splitPane.getItems().remove(sidePane); } }); mainStage.showingProperty().removeListener(this); observable.removeListener(this); } } }); setCenter(splitPane); } private void setDividerPosition() { splitPane.setDividerPositions(prefs.getDouble(JabRefPreferences.SIDE_PANE_WIDTH)); if (!splitPane.getDividers().isEmpty()) { EasyBind.subscribe(splitPane.getDividers().get(0).positionProperty(), position -> prefs.putDouble(JabRefPreferences.SIDE_PANE_WIDTH, position.doubleValue())); } } private Node createToolbar() { Pane leftSpacer = new Pane(); leftSpacer.setMinWidth(50); HBox.setHgrow(leftSpacer, Priority.SOMETIMES); Pane rightSpacer = new Pane(); HBox.setHgrow(rightSpacer, Priority.SOMETIMES); ActionFactory factory = new ActionFactory(Globals.getKeyPrefs()); Button newLibrary; if (Globals.prefs.getBoolean(JabRefPreferences.BIBLATEX_DEFAULT_MODE)) { newLibrary = factory.createIconButton(StandardActions.NEW_LIBRARY_BIBLATEX, new NewDatabaseAction(this, BibDatabaseMode.BIBLATEX)); } else { newLibrary = factory.createIconButton(StandardActions.NEW_LIBRARY_BIBTEX, new NewDatabaseAction(this, BibDatabaseMode.BIBTEX)); } HBox leftSide = new HBox( newLibrary, factory.createIconButton(StandardActions.OPEN_LIBRARY, new OpenDatabaseAction(this)), factory.createIconButton(StandardActions.SAVE_LIBRARY, new OldDatabaseCommandWrapper(Actions.SAVE, this, stateManager)), leftSpacer ); final PushToApplicationAction pushToApplicationAction = getPushToApplicationsManager().getPushToApplicationAction(); final Button pushToApplicationButton = factory.createIconButton(pushToApplicationAction.getActionInformation(), pushToApplicationAction); pushToApplicationsManager.setToolBarButton(pushToApplicationButton); HBox rightSide = new HBox( factory.createIconButton(StandardActions.NEW_ARTICLE, new NewEntryAction(this, StandardEntryType.Article, dialogService, Globals.prefs, stateManager)), factory.createIconButton(StandardActions.NEW_ENTRY, new NewEntryAction(this, dialogService, Globals.prefs, stateManager)), factory.createIconButton(StandardActions.NEW_ENTRY_FROM_PLAIN_TEXT, new ExtractBibtexAction(stateManager)), factory.createIconButton(StandardActions.DELETE_ENTRY, new OldDatabaseCommandWrapper(Actions.DELETE, this, stateManager)), new Separator(Orientation.VERTICAL), factory.createIconButton(StandardActions.UNDO, new OldDatabaseCommandWrapper(Actions.UNDO, this, stateManager)), factory.createIconButton(StandardActions.REDO, new OldDatabaseCommandWrapper(Actions.REDO, this, stateManager)), factory.createIconButton(StandardActions.CUT, new OldDatabaseCommandWrapper(Actions.CUT, this, stateManager)), factory.createIconButton(StandardActions.COPY, new OldDatabaseCommandWrapper(Actions.COPY, this, stateManager)), factory.createIconButton(StandardActions.PASTE, new OldDatabaseCommandWrapper(Actions.PASTE, this, stateManager)), new Separator(Orientation.VERTICAL), pushToApplicationButton, factory.createIconButton(StandardActions.GENERATE_CITE_KEYS, new OldDatabaseCommandWrapper(Actions.MAKE_KEY, this, stateManager)), factory.createIconButton(StandardActions.CLEANUP_ENTRIES, new OldDatabaseCommandWrapper(Actions.CLEANUP, this, stateManager)), new Separator(Orientation.VERTICAL), factory.createIconButton(StandardActions.OPEN_GITHUB, new OpenBrowserAction("https://github.com/JabRef/jabref")), factory.createIconButton(StandardActions.OPEN_FACEBOOK, new OpenBrowserAction("https: factory.createIconButton(StandardActions.OPEN_TWITTER, new OpenBrowserAction("https://twitter.com/jabref_org")) ); HBox.setHgrow(globalSearchBar, Priority.ALWAYS); ToolBar toolBar = new ToolBar( leftSide, globalSearchBar, rightSpacer, rightSide); toolBar.getStyleClass().add("mainToolbar"); return toolBar; } /** * Returns the indexed BasePanel. * * @param i Index of base */ public BasePanel getBasePanelAt(int i) { return (BasePanel) tabbedPane.getTabs().get(i).getContent(); } /** * Returns a list of BasePanel. */ public List<BasePanel> getBasePanelList() { List<BasePanel> returnList = new ArrayList<>(); for (int i = 0; i < getBasePanelCount(); i++) { returnList.add(getBasePanelAt(i)); } return returnList; } public void showBasePanelAt(int i) { tabbedPane.getSelectionModel().select(i); } public void showBasePanel(BasePanel bp) { tabbedPane.getSelectionModel().select(getTab(bp)); } public void init() { sidePaneManager = new SidePaneManager(Globals.prefs, this); sidePane = sidePaneManager.getPane(); tabbedPane = new TabPane(); tabbedPane.setTabDragPolicy(TabPane.TabDragPolicy.REORDER); initLayout(); initKeyBindings(); initDragAndDrop(); //setBounds(GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds()); //WindowLocation pw = new WindowLocation(this, JabRefPreferences.POS_X, JabRefPreferences.POS_Y, JabRefPreferences.SIZE_X, // JabRefPreferences.SIZE_Y); //pw.displayWindowAtStoredLocation(); // Bind global state stateManager.activeDatabaseProperty().bind( EasyBind.map(tabbedPane.getSelectionModel().selectedItemProperty(), tab -> Optional.ofNullable(tab).map(JabRefFrame::getBasePanel).map(BasePanel::getBibDatabaseContext))); // Subscribe to the search EasyBind.subscribe(stateManager.activeSearchQueryProperty(), query -> { if (getCurrentBasePanel() != null) { getCurrentBasePanel().setCurrentSearchQuery(query); } }); /* * The following state listener makes sure focus is registered with the * correct database when the user switches tabs. Without this, * cut/paste/copy operations would some times occur in the wrong tab. */ EasyBind.subscribe(tabbedPane.getSelectionModel().selectedItemProperty(), tab -> { if (tab == null) { return; } BasePanel newBasePanel = getBasePanel(tab); // Poor-mans binding to global state stateManager.setSelectedEntries(newBasePanel.getSelectedEntries()); // Update active search query when switching between databases stateManager.activeSearchQueryProperty().set(newBasePanel.getCurrentSearchQuery()); // groupSidePane.getToggleCommand().setSelected(sidePaneManager.isComponentVisible(GroupSidePane.class)); //previewToggle.setSelected(Globals.prefs.getPreviewPreferences().isPreviewPanelEnabled()); //generalFetcher.getToggleCommand().setSelected(sidePaneManager.isComponentVisible(WebSearchPane.class)); //openOfficePanel.getToggleCommand().setSelected(sidePaneManager.isComponentVisible(OpenOfficeSidePanel.class)); setWindowTitle(); // Update search autocompleter with information for the correct database: newBasePanel.updateSearchManager(); newBasePanel.getUndoManager().postUndoRedoEvent(); newBasePanel.getMainTable().requestFocus(); }); initShowTrackingNotification(); } /** * Returns the currently viewed BasePanel. */ public BasePanel getCurrentBasePanel() { if ((tabbedPane == null) || (tabbedPane.getSelectionModel().getSelectedItem() == null)) { return null; } return getBasePanel(tabbedPane.getSelectionModel().getSelectedItem()); } /** * @return the BasePanel count. */ public int getBasePanelCount() { return tabbedPane.getTabs().size(); } private Tab getTab(BasePanel comp) { for (Tab tab : tabbedPane.getTabs()) { if (tab.getContent() == comp) { return tab; } } return null; } /** * @deprecated do not operate on tabs but on BibDatabaseContexts */ @Deprecated public TabPane getTabbedPane() { return tabbedPane; } public void setTabTitle(BasePanel comp, String title, String toolTip) { DefaultTaskExecutor.runInJavaFXThread(() -> { Tab tab = getTab(comp); tab.setText(title); tab.setTooltip(new Tooltip(toolTip)); }); } private MenuBar createMenu() { ActionFactory factory = new ActionFactory(Globals.getKeyPrefs()); Menu file = new Menu(Localization.lang("File")); Menu edit = new Menu(Localization.lang("Edit")); Menu library = new Menu(Localization.lang("Library")); Menu quality = new Menu(Localization.lang("Quality")); Menu view = new Menu(Localization.lang("View")); Menu tools = new Menu(Localization.lang("Tools")); Menu options = new Menu(Localization.lang("Options")); Menu help = new Menu(Localization.lang("Help")); file.getItems().addAll( factory.createSubMenu(StandardActions.NEW_LIBRARY, factory.createMenuItem(StandardActions.NEW_LIBRARY_BIBTEX, new NewDatabaseAction(this, BibDatabaseMode.BIBTEX)), factory.createMenuItem(StandardActions.NEW_LIBRARY_BIBLATEX, new NewDatabaseAction(this, BibDatabaseMode.BIBLATEX))), factory.createMenuItem(StandardActions.OPEN_LIBRARY, getOpenDatabaseAction()), fileHistory, factory.createMenuItem(StandardActions.SAVE_LIBRARY, new OldDatabaseCommandWrapper(Actions.SAVE, this, stateManager)), factory.createMenuItem(StandardActions.SAVE_LIBRARY_AS, new OldDatabaseCommandWrapper(Actions.SAVE_AS, this, stateManager)), factory.createMenuItem(StandardActions.SAVE_ALL, new SaveAllAction(this)), new SeparatorMenuItem(), factory.createSubMenu(StandardActions.IMPORT, factory.createMenuItem(StandardActions.MERGE_DATABASE, new OldDatabaseCommandWrapper(Actions.MERGE_DATABASE, this, stateManager)), // TODO: merge with import factory.createMenuItem(StandardActions.IMPORT_INTO_CURRENT_LIBRARY, new ImportCommand(this, false, stateManager)), factory.createMenuItem(StandardActions.IMPORT_INTO_NEW_LIBRARY, new ImportCommand(this, true, stateManager))), factory.createSubMenu(StandardActions.EXPORT, factory.createMenuItem(StandardActions.EXPORT_ALL, new ExportCommand(this, false, Globals.prefs)), factory.createMenuItem(StandardActions.EXPORT_SELECTED, new ExportCommand(this, true, Globals.prefs)), factory.createMenuItem(StandardActions.SAVE_SELECTED_AS_PLAIN_BIBTEX, new OldDatabaseCommandWrapper(Actions.SAVE_SELECTED_AS_PLAIN, this, stateManager))), factory.createMenuItem(StandardActions.CONNECT_TO_SHARED_DB, new ConnectToSharedDatabaseCommand(this)), factory.createMenuItem(StandardActions.PULL_CHANGES_FROM_SHARED_DB, new OldDatabaseCommandWrapper(Actions.PULL_CHANGES_FROM_SHARED_DATABASE, this, stateManager)), new SeparatorMenuItem(), factory.createMenuItem(StandardActions.CLOSE_LIBRARY, new CloseDatabaseAction()), factory.createMenuItem(StandardActions.QUIT, new CloseAction()) ); edit.getItems().addAll( factory.createMenuItem(StandardActions.UNDO, new OldDatabaseCommandWrapper(Actions.UNDO, this, stateManager)), factory.createMenuItem(StandardActions.REDO, new OldDatabaseCommandWrapper(Actions.REDO, this, stateManager)), new SeparatorMenuItem(), factory.createMenuItem(StandardActions.CUT, new EditAction(Actions.CUT)), factory.createMenuItem(StandardActions.COPY, new EditAction(Actions.COPY)), factory.createSubMenu(StandardActions.COPY_MORE, factory.createMenuItem(StandardActions.COPY_TITLE, new OldDatabaseCommandWrapper(Actions.COPY_TITLE, this, stateManager)), factory.createMenuItem(StandardActions.COPY_KEY, new OldDatabaseCommandWrapper(Actions.COPY_KEY, this, stateManager)), factory.createMenuItem(StandardActions.COPY_CITE_KEY, new OldDatabaseCommandWrapper(Actions.COPY_CITE_KEY, this, stateManager)), factory.createMenuItem(StandardActions.COPY_KEY_AND_TITLE, new OldDatabaseCommandWrapper(Actions.COPY_KEY_AND_TITLE, this, stateManager)), factory.createMenuItem(StandardActions.COPY_KEY_AND_LINK, new OldDatabaseCommandWrapper(Actions.COPY_KEY_AND_LINK, this, stateManager)), factory.createMenuItem(StandardActions.COPY_CITATION_PREVIEW, new OldDatabaseCommandWrapper(Actions.COPY_CITATION_HTML, this, stateManager)), factory.createMenuItem(StandardActions.EXPORT_SELECTED_TO_CLIPBOARD, new ExportToClipboardAction(this, dialogService))), factory.createMenuItem(StandardActions.PASTE, new EditAction(Actions.PASTE)), new SeparatorMenuItem(), factory.createMenuItem(StandardActions.REPLACE_ALL, new OldDatabaseCommandWrapper(Actions.REPLACE_ALL, this, stateManager)), new SeparatorMenuItem(), factory.createMenuItem(StandardActions.MANAGE_KEYWORDS, new ManageKeywordsAction(stateManager)) ); if (Globals.prefs.getBoolean(JabRefPreferences.SPECIALFIELDSENABLED)) { edit.getItems().addAll( new SeparatorMenuItem(), SpecialFieldMenuItemFactory.createSpecialFieldMenuForActiveDatabase(SpecialField.RANKING, factory, undoManager), SpecialFieldMenuItemFactory.getSpecialFieldSingleItemForActiveDatabase(SpecialField.RELEVANCE, factory), SpecialFieldMenuItemFactory.getSpecialFieldSingleItemForActiveDatabase(SpecialField.QUALITY, factory), SpecialFieldMenuItemFactory.getSpecialFieldSingleItemForActiveDatabase(SpecialField.PRINTED, factory), SpecialFieldMenuItemFactory.createSpecialFieldMenuForActiveDatabase(SpecialField.PRIORITY, factory, undoManager), SpecialFieldMenuItemFactory.createSpecialFieldMenuForActiveDatabase(SpecialField.READ_STATUS, factory, undoManager) ); } //@formatter:off library.getItems().addAll( factory.createMenuItem(StandardActions.NEW_ENTRY, new NewEntryAction(this, dialogService, Globals.prefs, stateManager)), factory.createMenuItem(StandardActions.NEW_ENTRY_FROM_PLAIN_TEXT, new ExtractBibtexAction(stateManager)), factory.createMenuItem(StandardActions.DELETE_ENTRY, new OldDatabaseCommandWrapper(Actions.DELETE, this, stateManager)), new SeparatorMenuItem(), factory.createMenuItem(StandardActions.LIBRARY_PROPERTIES, new LibraryPropertiesAction(this, dialogService, stateManager)), factory.createMenuItem(StandardActions.EDIT_PREAMBLE, new PreambleEditor(stateManager, undoManager, this.getDialogService())), factory.createMenuItem(StandardActions.EDIT_STRINGS, new BibtexStringEditorAction(stateManager)), factory.createMenuItem(StandardActions.MANAGE_CITE_KEY_PATTERNS, new BibtexKeyPatternAction(this, stateManager)), factory.createMenuItem(StandardActions.MASS_SET_FIELDS, new MassSetFieldsAction(stateManager, dialogService, undoManager)) ); Menu lookupIdentifiers = factory.createSubMenu(StandardActions.LOOKUP_DOC_IDENTIFIER); for (IdFetcher<?> fetcher : WebFetchers.getIdFetchers(Globals.prefs.getImportFormatPreferences())) { LookupIdentifierAction<?> identifierAction = new LookupIdentifierAction<>(this, fetcher, stateManager, undoManager); lookupIdentifiers.getItems().add(factory.createMenuItem(identifierAction.getAction(), identifierAction)); } quality.getItems().addAll( factory.createMenuItem(StandardActions.FIND_DUPLICATES, new DuplicateSearch(this, dialogService, stateManager)), factory.createMenuItem(StandardActions.MERGE_ENTRIES, new MergeEntriesAction(this, stateManager)), factory.createMenuItem(StandardActions.CHECK_INTEGRITY, new IntegrityCheckAction(this, stateManager, Globals.TASK_EXECUTOR)), factory.createMenuItem(StandardActions.CLEANUP_ENTRIES, new OldDatabaseCommandWrapper(Actions.CLEANUP, this, stateManager)), new SeparatorMenuItem(), factory.createMenuItem(StandardActions.SET_FILE_LINKS, new AutoLinkFilesAction(this, prefs, stateManager, undoManager, Globals.TASK_EXECUTOR)) ); // PushToApplication final PushToApplicationAction pushToApplicationAction = pushToApplicationsManager.getPushToApplicationAction(); final MenuItem pushToApplicationMenuItem = factory.createMenuItem(pushToApplicationAction.getActionInformation(), pushToApplicationAction); pushToApplicationsManager.setMenuItem(pushToApplicationMenuItem); tools.getItems().addAll( factory.createMenuItem(StandardActions.PARSE_TEX, new ParseTexAction(stateManager)), factory.createMenuItem(StandardActions.NEW_SUB_LIBRARY_FROM_AUX, new NewSubLibraryAction(this, stateManager)), new SeparatorMenuItem(), factory.createMenuItem(StandardActions.FIND_UNLINKED_FILES, new FindUnlinkedFilesAction(this, stateManager)), factory.createMenuItem(StandardActions.WRITE_XMP, new OldDatabaseCommandWrapper(Actions.WRITE_XMP, this, stateManager)), factory.createMenuItem(StandardActions.COPY_LINKED_FILES, new CopyFilesAction(stateManager, this.getDialogService())), new SeparatorMenuItem(), lookupIdentifiers, factory.createMenuItem(StandardActions.DOWNLOAD_FULL_TEXT, new OldDatabaseCommandWrapper(Actions.DOWNLOAD_FULL_TEXT, this, stateManager)), new SeparatorMenuItem(), factory.createMenuItem(StandardActions.GENERATE_CITE_KEYS, new OldDatabaseCommandWrapper(Actions.MAKE_KEY, this, stateManager)), factory.createMenuItem(StandardActions.SEND_AS_EMAIL, new OldDatabaseCommandWrapper(Actions.SEND_AS_EMAIL, this, stateManager)), pushToApplicationMenuItem, factory.createSubMenu(StandardActions.ABBREVIATE, factory.createMenuItem(StandardActions.ABBREVIATE_DEFAULT, new OldDatabaseCommandWrapper(Actions.ABBREVIATE_DEFAULT, this, stateManager)), factory.createMenuItem(StandardActions.ABBREVIATE_MEDLINE, new OldDatabaseCommandWrapper(Actions.ABBREVIATE_MEDLINE, this, stateManager)), factory.createMenuItem(StandardActions.ABBREVIATE_SHORTEST_UNIQUE, new OldDatabaseCommandWrapper(Actions.ABBREVIATE_SHORTEST_UNIQUE, this, stateManager))), factory.createMenuItem(StandardActions.UNABBREVIATE, new OldDatabaseCommandWrapper(Actions.UNABBREVIATE, this, stateManager)) ); SidePaneComponent webSearch = sidePaneManager.getComponent(SidePaneType.WEB_SEARCH); SidePaneComponent groups = sidePaneManager.getComponent(SidePaneType.GROUPS); SidePaneComponent openOffice = sidePaneManager.getComponent(SidePaneType.OPEN_OFFICE); view.getItems().add(new SeparatorMenuItem()); view.setOnShowing(event -> { view.getItems().clear(); view.getItems().addAll( factory.createCheckMenuItem(webSearch.getToggleAction(), webSearch.getToggleCommand(), sidePaneManager.isComponentVisible(SidePaneType.WEB_SEARCH)), factory.createCheckMenuItem(groups.getToggleAction(), groups.getToggleCommand(), sidePaneManager.isComponentVisible(SidePaneType.GROUPS)), factory.createCheckMenuItem(openOffice.getToggleAction(), openOffice.getToggleCommand(), sidePaneManager.isComponentVisible(SidePaneType.OPEN_OFFICE)), new SeparatorMenuItem(), factory.createMenuItem(StandardActions.NEXT_PREVIEW_STYLE, new OldDatabaseCommandWrapper(Actions.NEXT_PREVIEW_STYLE, this, stateManager)), factory.createMenuItem(StandardActions.PREVIOUS_PREVIEW_STYLE, new OldDatabaseCommandWrapper(Actions.PREVIOUS_PREVIEW_STYLE, this, stateManager)), new SeparatorMenuItem(), factory.createMenuItem(StandardActions.SHOW_PDF_VIEWER, new ShowDocumentViewerAction()), factory.createMenuItem(StandardActions.EDIT_ENTRY, new OldDatabaseCommandWrapper(Actions.EDIT, this, stateManager)), factory.createMenuItem(StandardActions.OPEN_CONSOLE, new OldDatabaseCommandWrapper(Actions.OPEN_CONSOLE, this, stateManager)) ); }); options.getItems().addAll( factory.createMenuItem(StandardActions.SHOW_PREFS, new ShowPreferencesAction(this, Globals.TASK_EXECUTOR)), new SeparatorMenuItem(), factory.createMenuItem(StandardActions.SETUP_GENERAL_FIELDS, new SetupGeneralFieldsAction()), factory.createMenuItem(StandardActions.MANAGE_CUSTOM_IMPORTS, new ManageCustomImportsAction()), factory.createMenuItem(StandardActions.MANAGE_CUSTOM_EXPORTS, new ManageCustomExportsAction()), factory.createMenuItem(StandardActions.MANAGE_EXTERNAL_FILETYPES, new EditExternalFileTypesAction()), factory.createMenuItem(StandardActions.MANAGE_JOURNALS, new ManageJournalsAction()), factory.createMenuItem(StandardActions.CUSTOMIZE_KEYBINDING, new CustomizeKeyBindingAction()), factory.createMenuItem(StandardActions.MANAGE_PROTECTED_TERMS, new ManageProtectedTermsAction()), new SeparatorMenuItem(), factory.createMenuItem(StandardActions.MANAGE_CONTENT_SELECTORS, new ManageContentSelectorAction(this, stateManager)), factory.createMenuItem(StandardActions.CUSTOMIZE_ENTRY_TYPES, new CustomizeEntryAction(stateManager, Globals.entryTypesManager)) ); help.getItems().addAll( factory.createMenuItem(StandardActions.HELP, HelpAction.getMainHelpPageCommand()), factory.createMenuItem(StandardActions.OPEN_FORUM, new OpenBrowserAction("http://discourse.jabref.org/")), new SeparatorMenuItem(), factory.createMenuItem(StandardActions.ERROR_CONSOLE, new ErrorConsoleAction()), new SeparatorMenuItem(), factory.createMenuItem(StandardActions.DONATE, new OpenBrowserAction("https://donations.jabref.org")), factory.createMenuItem(StandardActions.SEARCH_FOR_UPDATES, new SearchForUpdateAction(Globals.BUILD_INFO, prefs.getVersionPreferences(), dialogService, Globals.TASK_EXECUTOR)), factory.createSubMenu(StandardActions.WEB_MENU, factory.createMenuItem(StandardActions.OPEN_WEBPAGE, new OpenBrowserAction("https://jabref.org/")), factory.createMenuItem(StandardActions.OPEN_BLOG, new OpenBrowserAction("https://blog.jabref.org/")), factory.createMenuItem(StandardActions.OPEN_FACEBOOK, new OpenBrowserAction("https: factory.createMenuItem(StandardActions.OPEN_TWITTER, new OpenBrowserAction("https://twitter.com/jabref_org")), factory.createMenuItem(StandardActions.OPEN_GITHUB, new OpenBrowserAction("https://github.com/JabRef/jabref")), new SeparatorMenuItem(), factory.createMenuItem(StandardActions.OPEN_DEV_VERSION_LINK, new OpenBrowserAction("https://builds.jabref.org/master/")), factory.createMenuItem(StandardActions.OPEN_CHANGELOG, new OpenBrowserAction("https://github.com/JabRef/jabref/blob/master/CHANGELOG.md")) ), factory.createMenuItem(StandardActions.ABOUT, new AboutAction()) ); //@formatter:on MenuBar menu = new MenuBar(); menu.getStyleClass().add("mainMenu"); menu.getMenus().addAll( file, edit, library, quality, tools, view, options, help); menu.setUseSystemMenuBar(true); return menu; } public void addParserResult(ParserResult pr, boolean focusPanel) { if (pr.toOpenTab()) { // Add the entries to the open tab. BasePanel panel = getCurrentBasePanel(); if (panel == null) { // There is no open tab to add to, so we create a new tab: addTab(pr.getDatabaseContext(), focusPanel); } else { List<BibEntry> entries = new ArrayList<>(pr.getDatabase().getEntries()); addImportedEntries(panel, entries); } } else { // only add tab if DB is not already open Optional<BasePanel> panel = getBasePanelList().stream() .filter(p -> p.getBibDatabaseContext().getDatabasePath().equals(pr.getFile())) .findFirst(); if (panel.isPresent()) { tabbedPane.getSelectionModel().select(getTab(panel.get())); } else { addTab(pr.getDatabaseContext(), focusPanel); } } } /** * This method causes all open BasePanels to set up their tables anew. When called from PrefsDialog3, this updates * to the new settings. */ public void setupAllTables() { // This action can be invoked without an open database, so // we have to check if we have one before trying to invoke // methods to execute changes in the preferences. // We want to notify all tabs about the changes to // avoid problems when changing the column set. for (int i = 0; i < tabbedPane.getTabs().size(); i++) { BasePanel bf = getBasePanelAt(i); // Update tables: if (bf.getDatabase() != null) { DefaultTaskExecutor.runInJavaFXThread(bf::setupMainPanel); } } } private List<String> collectDatabaseFilePaths() { List<String> dbPaths = new ArrayList<>(getBasePanelCount()); for (BasePanel basePanel : getBasePanelList()) { try { // db file exists if (basePanel.getBibDatabaseContext().getDatabaseFile().isPresent()) { dbPaths.add(basePanel.getBibDatabaseContext().getDatabaseFile().get().getCanonicalPath()); } else { dbPaths.add(""); } } catch (IOException ex) { LOGGER.error("Invalid database file path: " + ex.getMessage()); } } return dbPaths; } private List<String> getUniquePathParts() { List<String> dbPaths = collectDatabaseFilePaths(); return FileUtil.uniquePathSubstrings(dbPaths); } public void updateAllTabTitles() { List<String> paths = getUniquePathParts(); for (int i = 0; i < getBasePanelCount(); i++) { String uniqPath = paths.get(i); Optional<File> file = getBasePanelAt(i).getBibDatabaseContext().getDatabaseFile(); if (file.isPresent()) { if (!uniqPath.equals(file.get().getName()) && uniqPath.contains(File.separator)) { // remove filename uniqPath = uniqPath.substring(0, uniqPath.lastIndexOf(File.separator)); tabbedPane.getTabs().get(i).setText(getBasePanelAt(i).getTabTitle() + " \u2014 " + uniqPath); } else { // set original filename (again) tabbedPane.getTabs().get(i).setText(getBasePanelAt(i).getTabTitle()); } } else { tabbedPane.getTabs().get(i).setText(getBasePanelAt(i).getTabTitle()); } tabbedPane.getTabs().get(i).setTooltip(new Tooltip(file.map(File::getAbsolutePath).orElse(null))); } } public void addTab(BasePanel basePanel, boolean raisePanel) { // add tab Tab newTab = new Tab(basePanel.getTabTitle(), basePanel); tabbedPane.getTabs().add(newTab); newTab.setOnCloseRequest(event -> { closeTab((BasePanel) newTab.getContent()); event.consume(); }); // update all tab titles updateAllTabTitles(); if (raisePanel) { tabbedPane.getSelectionModel().select(newTab); } // Register undo/redo listener basePanel.getUndoManager().registerListener(new UndoRedoEventManager()); BibDatabaseContext context = basePanel.getBibDatabaseContext(); if (readyForAutosave(context)) { AutosaveManager autosaver = AutosaveManager.start(context); autosaver.registerListener(new AutosaveUIManager(basePanel)); } BackupManager.start(context, Globals.entryTypesManager, prefs); // Track opening trackOpenNewDatabase(basePanel); } private void trackOpenNewDatabase(BasePanel basePanel) { Map<String, String> properties = new HashMap<>(); Map<String, Double> measurements = new HashMap<>(); measurements.put("NumberOfEntries", (double) basePanel.getBibDatabaseContext().getDatabase().getEntryCount()); Globals.getTelemetryClient().ifPresent(client -> client.trackEvent("OpenNewDatabase", properties, measurements)); } public BasePanel addTab(BibDatabaseContext databaseContext, boolean raisePanel) { Objects.requireNonNull(databaseContext); BasePanel bp = new BasePanel(this, BasePanelPreferences.from(Globals.prefs), databaseContext, ExternalFileTypes.getInstance()); addTab(bp, raisePanel); return bp; } private boolean readyForAutosave(BibDatabaseContext context) { return ((context.getLocation() == DatabaseLocation.SHARED) || ((context.getLocation() == DatabaseLocation.LOCAL) && Globals.prefs.getBoolean(JabRefPreferences.LOCAL_AUTO_SAVE))) && context.getDatabaseFile().isPresent(); } /** * Opens the import inspection dialog to let the user decide which of the given entries to import. * * @param panel The BasePanel to add to. * @param entries The entries to add. */ private void addImportedEntries(final BasePanel panel, final List<BibEntry> entries) { BackgroundTask<List<BibEntry>> task = BackgroundTask.wrap(() -> entries); ImportEntriesDialog dialog = new ImportEntriesDialog(panel.getBibDatabaseContext(), task); dialog.setTitle(Localization.lang("Import")); dialog.showAndWait(); } public FileHistoryMenu getFileHistory() { return fileHistory; } /** * Set the visibility of the progress bar in the right end of the status line at the bottom of the frame. */ public void setProgressBarVisible(final boolean visible) { progressBar.setVisible(visible); } /** * Sets the indeterminate status of the progress bar. * <p> */ public void setProgressBarIndeterminate(final boolean value) { progressBar.setProgress(ProgressBar.INDETERMINATE_PROGRESS); } /** * Return a boolean, if the selected entry have file * * @param selectEntryList A selected entries list of the current base pane * @return true, if the selected entry contains file. false, if multiple entries are selected or the selected entry * doesn't contains file */ private boolean isExistFile(List<BibEntry> selectEntryList) { if (selectEntryList.size() == 1) { BibEntry selectedEntry = selectEntryList.get(0); return selectedEntry.getField(StandardField.FILE).isPresent(); } return false; } /** * Return a boolean, if the selected entry have url or doi * * @param selectEntryList A selected entries list of the current base pane * @return true, if the selected entry contains url or doi. false, if multiple entries are selected or the selected * entry doesn't contains url or doi */ private boolean isExistURLorDOI(List<BibEntry> selectEntryList) { if (selectEntryList.size() == 1) { BibEntry selectedEntry = selectEntryList.get(0); return (selectedEntry.getField(StandardField.URL).isPresent() || selectedEntry.getField(StandardField.DOI).isPresent()); } return false; } /** * Ask if the user really wants to close the given database * * @return true if the user choose to close the database */ private boolean confirmClose(BasePanel panel) { String filename = panel.getBibDatabaseContext() .getDatabasePath() .map(Path::toAbsolutePath) .map(Path::toString) .orElse(GUIGlobals.UNTITLED_TITLE); ButtonType saveChanges = new ButtonType(Localization.lang("Save changes"), ButtonBar.ButtonData.YES); ButtonType discardChanges = new ButtonType(Localization.lang("Discard changes"), ButtonBar.ButtonData.NO); ButtonType cancel = new ButtonType(Localization.lang("Return to JabRef"), ButtonBar.ButtonData.CANCEL_CLOSE); Optional<ButtonType> response = dialogService.showCustomButtonDialogAndWait(Alert.AlertType.CONFIRMATION, Localization.lang("Save before closing"), Localization.lang("Library '%0' has changed.", filename), saveChanges, discardChanges, cancel); if (response.isPresent() && response.get().equals(saveChanges)) { // The user wants to save. try { SaveDatabaseAction saveAction = new SaveDatabaseAction(panel, Globals.prefs, Globals.entryTypesManager); if (saveAction.save()) { // Saved, now exit. return true; } // The action was either canceled or unsuccessful. dialogService.notify(Localization.lang("Unable to save library")); } catch (Throwable ex) { LOGGER.error("A problem occurred when trying to save the file", ex); dialogService.showErrorDialogAndWait(Localization.lang("Save library"), Localization.lang("Could not save file."), ex); } // Save was cancelled or an error occurred. return false; } return !response.isPresent() || !response.get().equals(cancel); } private void closeTab(BasePanel panel) { // empty tab without database if (panel == null) { return; } BibDatabaseContext context = panel.getBibDatabaseContext(); if (panel.isModified() && (context.getLocation() == DatabaseLocation.LOCAL)) { if (confirmClose(panel)) { removeTab(panel); } else { return; } } else if (context.getLocation() == DatabaseLocation.SHARED) { context.convertToLocalDatabase(); context.getDBMSSynchronizer().closeSharedDatabase(); context.clearDBMSSynchronizer(); removeTab(panel); } else { removeTab(panel); } AutosaveManager.shutdown(context); BackupManager.shutdown(context); } private void removeTab(BasePanel panel) { DefaultTaskExecutor.runInJavaFXThread(() -> { panel.cleanUp(); tabbedPane.getTabs().remove(getTab(panel)); setWindowTitle(); // update tab titles updateAllTabTitles(); }); } public void closeCurrentTab() { removeTab(getCurrentBasePanel()); } public OpenDatabaseAction getOpenDatabaseAction() { return new OpenDatabaseAction(this); } public SidePaneManager getSidePaneManager() { return sidePaneManager; } public PushToApplicationsManager getPushToApplicationsManager() { return pushToApplicationsManager; } public GlobalSearchBar getGlobalSearchBar() { return globalSearchBar; } public CountingUndoManager getUndoManager() { return undoManager; } public DialogService getDialogService() { return dialogService; } private void setDefaultTableFontSize() { GUIGlobals.setFont(Globals.prefs.getIntDefault(JabRefPreferences.FONT_SIZE)); for (BasePanel basePanel : getBasePanelList()) { basePanel.updateTableFont(); } dialogService.notify(Localization.lang("Table font size is %0", String.valueOf(GUIGlobals.currentFont.getSize()))); } private void increaseTableFontSize() { GUIGlobals.setFont(GUIGlobals.currentFont.getSize() + 1); for (BasePanel basePanel : getBasePanelList()) { basePanel.updateTableFont(); } dialogService.notify(Localization.lang("Table font size is %0", String.valueOf(GUIGlobals.currentFont.getSize()))); } private void decreaseTableFontSize() { double currentSize = GUIGlobals.currentFont.getSize(); if (currentSize < 2) { return; } GUIGlobals.setFont(currentSize - 1); for (BasePanel basePanel : getBasePanelList()) { basePanel.updateTableFont(); } dialogService.notify(Localization.lang("Table font size is %0", String.valueOf(GUIGlobals.currentFont.getSize()))); } /** * The action concerned with closing the window. */ private class CloseAction extends SimpleCommand { @Override public void execute() { quit(); } } /** * Class for handling general actions; cut, copy and paste. The focused component is kept track of by * Globals.focusListener, and we call the action stored under the relevant name in its action map. */ private class EditAction extends SimpleCommand { private final Actions command; public EditAction(Actions command) { this.command = command; } @Override public String toString() { return this.command.toString(); } @Override public void execute() { Node focusOwner = mainStage.getScene().getFocusOwner(); if (focusOwner != null) { if (focusOwner instanceof TextInputControl) { // Focus is on text field -> copy/paste/cut selected text TextInputControl textInput = (TextInputControl) focusOwner; switch (command) { case COPY: textInput.copy(); break; case CUT: textInput.cut(); break; case PASTE: // handled by FX in TextInputControl#paste break; default: throw new IllegalStateException("Only cut/copy/paste supported but got " + command); } } else { // Not sure what is selected -> copy/paste/cut selected entries switch (command) { case COPY: getCurrentBasePanel().copy(); break; case CUT: getCurrentBasePanel().cut(); break; case PASTE: // handled by FX in TextInputControl#paste break; default: throw new IllegalStateException("Only cut/copy/paste supported but got " + command); } } } } } private class CloseDatabaseAction extends SimpleCommand { @Override public void execute() { closeTab(getCurrentBasePanel()); } } private class UndoRedoEventManager { @Subscribe public void listen(UndoRedoEvent event) { updateTexts(event); JabRefFrame.this.getCurrentBasePanel().updateEntryEditorIfShowing(); } @Subscribe public void listen(AddUndoableActionEvent event) { updateTexts(event); } private void updateTexts(UndoChangeEvent event) { /* TODO SwingUtilities.invokeLater(() -> { undo.putValue(Action.SHORT_DESCRIPTION, event.getUndoDescription()); undo.setEnabled(event.isCanUndo()); redo.putValue(Action.SHORT_DESCRIPTION, event.getRedoDescription()); redo.setEnabled(event.isCanRedo()); }); */ } } }
package com.hubspot.singularity.config; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import io.dropwizard.Configuration; import io.dropwizard.db.DataSourceFactory; import javax.validation.Valid; import javax.validation.constraints.NotNull; import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true) public class SingularityConfiguration extends Configuration { @JsonProperty("mesos") private MesosConfiguration mesosConfiguration; @JsonProperty("zookeeper") private ZooKeeperConfiguration zooKeeperConfiguration; @JsonProperty("hostname") private String hostname; @Valid @NotNull private DataSourceFactory database; @NotNull private long cleanupEverySeconds = 5; public long getCleanupEverySeconds() { return cleanupEverySeconds; } public void setCleanupEverySeconds(long cleanupEverySeconds) { this.cleanupEverySeconds = cleanupEverySeconds; } @JsonProperty("database") public DataSourceFactory getDataSourceFactory() { return database; } @JsonProperty("database") public void setDataSourceFactory(DataSourceFactory dataSourceFactory) { this.database = dataSourceFactory; } public MesosConfiguration getMesosConfiguration() { return mesosConfiguration; } public void setMesosConfiguration(MesosConfiguration mesosConfiguration) { this.mesosConfiguration = mesosConfiguration; } public ZooKeeperConfiguration getZooKeeperConfiguration() { return zooKeeperConfiguration; } public void setZooKeeperConfiguration(ZooKeeperConfiguration zooKeeperConfiguration) { this.zooKeeperConfiguration = zooKeeperConfiguration; } public String getHostname() { return hostname; } public void setHostname(String hostname) { this.hostname = hostname; } }
package org.openbmp.handler; import org.openbmp.processor.ParseNullAsEmpty; import org.openbmp.processor.ParseTimestamp; import org.supercsv.cellprocessor.Optional; import org.supercsv.cellprocessor.ParseInt; import org.supercsv.cellprocessor.ParseLong; import org.supercsv.cellprocessor.constraint.NotNull; import org.supercsv.cellprocessor.ift.CellProcessor; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class Router extends Base { /** * Handle the message by parsing it and storing the data in memory. * * @param headers Generated Headers object from the headers in the message * @param data */ public Router(Headers headers, String data) { super(); headerNames = new String [] { "action", "seq", "name", "hash", "ip_address", "description", "term_code", "term_reason", "init_data", "term_data", "timestamp" }; this.headers = headers; parse(data); } /** * Processors used for each field. * * Order matters and must match the same order as defined in headerNames * * @return array of cell processors */ protected CellProcessor[] getProcessors() { final CellProcessor[] processors = new CellProcessor[] { new NotNull(), // action new ParseLong(), // seq new ParseNullAsEmpty(), // name new NotNull(), // hash new NotNull(), // IP Address new ParseNullAsEmpty(), // Description new Optional(new ParseInt()), // Term code new ParseNullAsEmpty(), // Term reason new ParseNullAsEmpty(), // Init data new ParseNullAsEmpty(), // Term data new ParseTimestamp() // Timestamp }; return processors; } /** * Generate MySQL insert/update statement, sans the values * * @return Two strings are returned * 0 = Insert statement string up to VALUES keyword * 1 = ON DUPLICATE KEY UPDATE ... or empty if not used. */ public String[] genInsertStatement() { String [] stmt = { " INSERT INTO routers (hash_id,name,ip_address,timestamp,isConnected,term_reason_code," + "term_reason_text,term_data,init_data,description,collector_hash_id) VALUES ", " ON DUPLICATE KEY UPDATE timestamp=values(timestamp),isConnected=values(isConnected)," + "name=if(isConnected = 1, values(name), name)," + "description=values(description),init_data=values(init_data)," + "term_reason_code=values(term_reason_code),term_reason_text=values(term_reason_text)," + "collector_hash_id=values(collector_hash_id)" }; return stmt; } /** * Generate bulk values statement for SQL bulk insert. * * @return String in the format of (col1, col2, ...)[,...] */ public String genValuesStatement() { StringBuilder sb = new StringBuilder(); for (int i=0; i < rowMap.size(); i++) { if (i > 0) sb.append(','); sb.append('('); sb.append("'" + rowMap.get(i).get("hash") + "',"); sb.append("'" + rowMap.get(i).get("name") + "',"); sb.append("'" + rowMap.get(i).get("ip_address") + "',"); sb.append("'" + rowMap.get(i).get("timestamp") + "',"); sb.append((((String)rowMap.get(i).get("action")).equalsIgnoreCase("term") ? 0 : 1) + ","); sb.append(rowMap.get(i).get("term_code") + ","); sb.append("'" + rowMap.get(i).get("term_reason") + "',"); sb.append("'" + rowMap.get(i).get("term_data") + "',"); sb.append("'" + rowMap.get(i).get("init_data") + "',"); sb.append("'" + rowMap.get(i).get("description") + "',"); sb.append("'" + headers.getCollector_hash_id() + "'"); sb.append(')'); } return sb.toString(); } /** * Generate MySQL update statement to update peer status * * Avoids faulty report of peer status when router gets disconnected * * @param routerConMap Hash of collectors/routers and connection counts * * @return Multi statement update is returned, such as update ...; update ...; */ public String genPeerRouterUpdate( Map<String,Map<String, Integer>> routerConMap) { StringBuilder sb = new StringBuilder(); List<Map<String, Object>> resultMap = new ArrayList<>(); resultMap.addAll(rowMap); // Add the collector entry if router is seen before collector message if (! routerConMap.containsKey(headers.getCollector_hash_id())) { routerConMap.put(headers.getCollector_hash_id(), new ConcurrentHashMap<String, Integer>()); } Map<String, Integer> routerMap = routerConMap.get(headers.getCollector_hash_id()); for (int i = 0; i < rowMap.size(); i++) { if (((String) rowMap.get(i).get("action")).equalsIgnoreCase("first") || ((String) rowMap.get(i).get("action")).equalsIgnoreCase("init")) { if (sb.length() > 0) sb.append(";"); // Upon initial router message, we set the state of all peers to down since we will get peer UP's sb.append("UPDATE bgp_peers SET state = 0 WHERE router_hash_id = '"); sb.append(rowMap.get(i).get("hash") + "'"); // Collector changed/heartbeat messages maintain the routerMap, but timing might prevent an update // so add the router if it doesn't exist already if (! routerMap.containsKey((String)rowMap.get(i).get("ip_address")) ) { routerMap.put((String)rowMap.get(i).get("ip_address"), 1); } } else if (((String) rowMap.get(i).get("action")).equalsIgnoreCase("term")) { // Update the router map to reflect the termination if (routerMap.containsKey((String)rowMap.get(i).get("ip_address")) ) { // decrement connection count or remove the router entry on term if (routerMap.get((String)rowMap.get(i).get("ip_address")) > 1) { routerMap.put((String)rowMap.get(i).get("ip_address"), routerMap.get((String)rowMap.get(i).get("ip_address")) - 1 ); // Suppress the term message since another connection exists resultMap.remove(rowMap.get(i)); } else { routerMap.remove((String)rowMap.get(i).get("ip_address")); } } } } rowMap = resultMap; return sb.toString(); } }
package org.pfaa; import java.lang.reflect.Field; import net.minecraft.block.Block; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraftforge.fluids.BlockFluidBase; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidContainerRegistry; import org.pfaa.chemica.ChemicaItems; import org.pfaa.geologica.Geologica; import org.pfaa.geologica.fluid.ColoredBucketItem; import com.google.common.base.CaseFormat; import cpw.mods.fml.common.LoaderException; import cpw.mods.fml.common.registry.GameRegistry; public class RegistrationUtils { public static void registerDeclaredBlocks(Class catalogClass, Class blockClass, Class<? extends ItemBlock> itemClass) { Field[] fields = catalogClass.getFields(); for (Field field : fields) { try { Object value = field.get(null); if (value instanceof Block && blockClass.isAssignableFrom(value.getClass())) { Block block = (Block)value; String name = fieldNameToUnlocalizedName(field.getName()); block.setBlockName(name); GameRegistry.registerBlock(block, itemClass, name); } } catch (Exception e) { Geologica.log.fatal("Failed to register field '" + field.getName() + "' as block"); throw new LoaderException(e); } } } public static void registerDeclaredItems(Class catalogClass) { Field[] fields = catalogClass.getFields(); for (Field field : fields) { try { Item item = (Item)field.get(null); String name = fieldNameToUnlocalizedName(field.getName()); item.setUnlocalizedName(name); GameRegistry.registerItem(item, name); } catch (Exception e) { Geologica.log.fatal("Failed to register field '" + field.getName() + "' as item"); throw new LoaderException(e); } } } private static String fieldNameToUnlocalizedName(String name) { return CaseFormat.UPPER_UNDERSCORE. to(CaseFormat.LOWER_CAMEL, name.replaceAll("__", ".")); } public static void registerContainersForDeclaredFluidBlocks(Class catalogClass) { Field[] fields = catalogClass.getFields(); for (Field field : fields) { try { Object value = field.get(null); if (value instanceof BlockFluidBase) { BlockFluidBase block = (BlockFluidBase)value; if (!block.getFluid().isGaseous()) { registerBucketForFluid(block); registerFlaskForFluid(block.getFluid()); } } } catch (Exception e) { Geologica.log.fatal("Failed to register bucket for fluid block '" + field.getName()); throw new LoaderException(e); } } } private static void registerBucketForFluid(BlockFluidBase block) { String name = fieldNameToUnlocalizedName(block.getFluid().getName()) + "Bucket"; Item item = new ColoredBucketItem(block); item.setUnlocalizedName(name); GameRegistry.registerItem(item, name); FluidContainerRegistry.registerFluidContainer(block.getFluid(), new ItemStack(item), FluidContainerRegistry.EMPTY_BUCKET); } private static void registerFlaskForFluid(Fluid fluid) { FluidContainerRegistry.registerFluidContainer(fluid, new ItemStack(ChemicaItems.FILLED_GLASS_BOTTLE, 1, fluid.getID()), FluidContainerRegistry.EMPTY_BOTTLE); } }
package com.continuuity.internal.app.store; import com.continuuity.api.ApplicationSpecification; import com.continuuity.api.ProgramSpecification; import com.continuuity.api.data.DataSetSpecification; import com.continuuity.api.data.OperationException; import com.continuuity.api.data.stream.StreamSpecification; import com.continuuity.api.flow.FlowSpecification; import com.continuuity.api.flow.FlowletDefinition; import com.continuuity.api.procedure.ProcedureSpecification; import com.continuuity.app.Id; import com.continuuity.app.program.Program; import com.continuuity.app.program.Programs; import com.continuuity.app.program.RunRecord; import com.continuuity.app.program.Type; import com.continuuity.app.store.Store; import com.continuuity.archive.ArchiveBundler; import com.continuuity.common.conf.CConfiguration; import com.continuuity.common.conf.Constants; import com.continuuity.data.operation.OperationContext; import com.continuuity.internal.app.ApplicationSpecificationAdapter; import com.continuuity.internal.app.ForwardingApplicationSpecification; import com.continuuity.internal.app.ForwardingFlowSpecification; import com.continuuity.internal.app.program.ProgramBundle; import com.continuuity.internal.io.ReflectionSchemaGenerator; import com.continuuity.internal.procedure.DefaultProcedureSpecification; import com.continuuity.metadata.MetaDataEntry; import com.continuuity.metadata.MetaDataTable; import com.continuuity.weave.filesystem.Location; import com.continuuity.weave.filesystem.LocationFactory; import com.google.common.base.Preconditions; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableTable; import com.google.common.collect.Lists; import com.google.common.collect.MapDifference; import com.google.common.collect.Maps; import com.google.common.collect.Table; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.google.inject.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; /** * Implementation of the Store that ultimately places data into MetaDataTable. */ public class MDTBasedStore implements Store { private static final Logger LOG = LoggerFactory.getLogger(MDTBasedStore.class); /** * Helper class. */ private final LocationFactory locationFactory; private final CConfiguration configuration; private final Gson gson = new Gson(); /** * We use metaDataTable directly to store user actions history. */ private MetaDataTable metaDataTable; @Inject public MDTBasedStore(CConfiguration configuration, MetaDataTable metaDataTable, LocationFactory locationFactory) { this.metaDataTable = metaDataTable; this.locationFactory = locationFactory; this.configuration = configuration; } /** * Loads a given program. * * @param id of the program * @param type of program * @return An instance of {@link Program} if found. * @throws IOException */ @Override public Program loadProgram(Id.Program id, Type type) throws IOException { try { MetaDataEntry entry = metaDataTable.get(new OperationContext(id.getAccountId()), id.getAccountId(), null, FieldTypes.Application.ENTRY_TYPE, id.getApplicationId()); Preconditions.checkNotNull(entry); String specTimestamp = entry.getTextField(FieldTypes.Application.TIMESTAMP); Preconditions.checkNotNull(specTimestamp); Location programLocation = getProgramLocation(id, type); Preconditions.checkArgument(Long.parseLong(specTimestamp) >= programLocation.lastModified(), "Newer program update time than the specification update time. " + "Application must be redeployed"); return Programs.create(programLocation); } catch (OperationException e){ throw new IOException(e); } } /** * @return The {@link Location} of the given program. * @throws RuntimeException if program can't be found. */ private Location getProgramLocation(Id.Program id, Type type) throws IOException { String appFabricOutputDir = configuration.get(Constants.AppFabric.OUTPUT_DIR, System.getProperty("java.io.tmpdir")); return Programs.programLocation(locationFactory, appFabricOutputDir, id, type); } /** * Logs start of program run. * * @param id Info about program * @param pid run id * @param startTime start timestamp */ @Override public void setStart(Id.Program id, final String pid, final long startTime) { // Create a temp entry that is keyed by accountId, applicationId and program run id. MetaDataEntry entry = new MetaDataEntry(id.getAccountId(), id.getApplicationId(), FieldTypes.ProgramRun.ENTRY_TYPE, pid); entry.addField(FieldTypes.ProgramRun.PROGRAM, id.getId()); entry.addField(FieldTypes.ProgramRun.START_TS, String.valueOf(startTime)); OperationContext context = new OperationContext(id.getAccountId()); // perform insert, no conflict resolution try { metaDataTable.add(context, entry, false); } catch (OperationException e) { throw Throwables.propagate(e); } } /** * Logs end of program run. * * @param id id of program * @param pid program run id * @param endTime end timestamp * @param state State of program */ @Override public void setStop(Id.Program id, final String pid, final long endTime, final String state) { Preconditions.checkArgument(state != null, "End state of program run should be defined"); OperationContext context = new OperationContext(id.getAccountId()); // During setStop the following actions are performed // 1. Read the temp entry that is keyed by accountId, applicationId and program run id. // 2. Add a new entry that is keyed by accountId, applicationId, ProgramId:ReverseTimestamp:ProgramRunId // - This is done so that the program history can be scanned by reverse chronological order. // 3. Delete the temp entry that was created during start - since we no longer read the entry that is keyed // only by runId during program history lookup. try { //Read the metadata entry that is keyed of accountId, applicationId, program run id. MetaDataEntry entry = metaDataTable.get(context, id.getAccountId(), id.getApplicationId(), FieldTypes.ProgramRun.ENTRY_TYPE, pid); Preconditions.checkNotNull(entry); String startTime = entry.getTextField(FieldTypes.ProgramRun.START_TS); Preconditions.checkNotNull(startTime); String timestampedProgramId = getTimestampedId(id.getId(), pid, Long.MAX_VALUE - Long.parseLong(startTime)); //update new entry that is ordered by time. MetaDataEntry timeStampedEntry = new MetaDataEntry(id.getAccountId(), id.getApplicationId(), FieldTypes.ProgramRun.ENTRY_TYPE, timestampedProgramId); timeStampedEntry.addField(FieldTypes.ProgramRun.START_TS, startTime); timeStampedEntry.addField(FieldTypes.ProgramRun.END_TS, String.valueOf(endTime)); timeStampedEntry.addField(FieldTypes.ProgramRun.END_STATE, state); timeStampedEntry.addField(FieldTypes.ProgramRun.RUN_ID, pid); metaDataTable.add(context, timeStampedEntry); //delete the entry with pid as one of the column values. metaDataTable.delete(context, id.getAccountId(), id.getApplicationId(), FieldTypes.ProgramRun.ENTRY_TYPE, pid); try { //delete old history data and ignore exceptions since it will be cleaned up in the next run. deleteOlderMetadataHistory(context, id); } catch (OperationException e) { LOG.warn("Operation exception while deleting older run history with pid {}", pid, e); } } catch (OperationException e) { throw Throwables.propagate(e); } } @Override public List<RunRecord> getRunHistory(final Id.Program id, final long startTime, final long endTime, int limit) throws OperationException { OperationContext context = new OperationContext(id.getAccountId()); List<MetaDataEntry> entries = metaDataTable.list(context, id.getAccountId(), id.getApplicationId(), FieldTypes.ProgramRun.ENTRY_TYPE, getTimestampedId(id.getId(), startTime), getTimestampedId(id.getId(), endTime), limit); List<RunRecord> runHistory = Lists.newArrayList(); for (MetaDataEntry entry : entries) { String endTsStr = entry.getTextField(FieldTypes.ProgramRun.END_TS); String runId = entry.getTextField(FieldTypes.ProgramRun.RUN_ID); runHistory.add(new RunRecord(runId, Long.valueOf(entry.getTextField(FieldTypes.ProgramRun.START_TS)), Long.valueOf(endTsStr), entry.getTextField(FieldTypes.ProgramRun.END_STATE))); } return runHistory; } @Override public Table<Type, Id.Program, List<RunRecord>> getAllRunHistory(Id.Account account) throws OperationException { OperationContext context = new OperationContext(account.getId()); LOG.trace("Removing all applications of account with id: {}", account.getId()); List<MetaDataEntry> applications = metaDataTable.list(context, account.getId(), null, FieldTypes.Application.ENTRY_TYPE, null); ApplicationSpecificationAdapter adapter = ApplicationSpecificationAdapter.create(); ImmutableTable.Builder<Type, Id.Program, List<RunRecord>> builder = ImmutableTable.builder(); for (MetaDataEntry entry : applications) { ApplicationSpecification appSpec = adapter.fromJson(entry.getTextField(FieldTypes.Application.SPEC_JSON)); for (FlowSpecification flowSpec : appSpec.getFlows().values()) { Id.Program programId = Id.Program.from(account.getId(), appSpec.getName(), flowSpec.getName()); List<RunRecord> runRecords = getRunRecords(programId); builder.put(Type.FLOW, programId, runRecords); } for (ProcedureSpecification procedureSpec : appSpec.getProcedures().values()) { Id.Program programId = Id.Program.from(account.getId(), appSpec.getName(), procedureSpec.getName()); List<RunRecord> runRecords = getRunRecords(programId); builder.put(Type.PROCEDURE, programId, runRecords); } } return builder.build(); } private List<RunRecord> getRunRecords(Id.Program programId) throws OperationException { return getRunRecords(programId, Integer.MAX_VALUE); } private List<RunRecord> getRunRecords(Id.Program programId, int limit) throws OperationException { List<RunRecord> runRecords = Lists.newArrayList(); for (RunRecord runRecord : getRunHistory(programId, limit)) { runRecords.add(runRecord); } return runRecords; } private List<RunRecord> getRunHistory(Id.Program programId, int limit) throws OperationException { return getRunHistory(programId, Long.MIN_VALUE, Long.MAX_VALUE, limit); } @Override public void addApplication(final Id.Application id, final ApplicationSpecification spec, Location appArchiveLocation) throws OperationException { storeAppToArchiveLocationMapping(id, appArchiveLocation); long updateTime = System.currentTimeMillis(); storeAppSpec(id, spec, updateTime); } @Override public List<ProgramSpecification> getDeletedProgramSpecifications(Id.Application id, ApplicationSpecification appSpec) throws OperationException { List<ProgramSpecification> deletedProgramSpecs = Lists.newArrayList(); OperationContext context = new OperationContext(id.getAccountId()); MetaDataEntry existing = metaDataTable.get(context, id.getAccountId(), null, FieldTypes.Application.ENTRY_TYPE, id.getId()); if (existing != null){ String json = existing.getTextField(FieldTypes.Application.SPEC_JSON); Preconditions.checkNotNull(json); ApplicationSpecificationAdapter adapter = ApplicationSpecificationAdapter.create(); ApplicationSpecification existingAppSpec = adapter.fromJson(json); ImmutableMap<String, ProgramSpecification> existingSpec = new ImmutableMap.Builder<String, ProgramSpecification>() .putAll(existingAppSpec.getMapReduces()) .putAll(existingAppSpec.getWorkflows()) .putAll(existingAppSpec.getFlows()) .putAll(existingAppSpec.getProcedures()) .build(); ImmutableMap<String, ProgramSpecification> newSpec = new ImmutableMap.Builder<String, ProgramSpecification>() .putAll(appSpec.getMapReduces()) .putAll(appSpec.getWorkflows()) .putAll(appSpec.getFlows()) .putAll(appSpec.getProcedures()) .build(); MapDifference<String, ProgramSpecification> mapDiff = Maps.difference(existingSpec, newSpec); deletedProgramSpecs.addAll(mapDiff.entriesOnlyOnLeft().values()); } return deletedProgramSpecs; } private void storeAppToArchiveLocationMapping(Id.Application id, Location appArchiveLocation) throws OperationException { // there always be an entry for application LOG.trace("Updating id to app archive location mapping: app id: {}, app location: {}", id.getId(), appArchiveLocation.toURI()); OperationContext context = new OperationContext(id.getAccountId()); MetaDataEntry existing = metaDataTable.get(context, id.getAccountId(), null, FieldTypes.Application.ENTRY_TYPE, id.getId()); if (existing == null) { MetaDataEntry entry = new MetaDataEntry(id.getAccountId(), null, FieldTypes.Application.ENTRY_TYPE, id.getId()); entry.addField(FieldTypes.Application.ARCHIVE_LOCATION, appArchiveLocation.toURI().getPath()); metaDataTable.add(context, entry); } else { metaDataTable.updateField(context, id.getAccountId(), null, FieldTypes.Application.ENTRY_TYPE, id.getId(), FieldTypes.Application.ARCHIVE_LOCATION, appArchiveLocation.toURI().getPath(), -1); } LOG.trace("Updated id to app archive location mapping: app id: {}, app location: {}", id.getId(), appArchiveLocation.toURI()); } private void storeAppSpec(Id.Application id, ApplicationSpecification spec, long timestamp) throws OperationException { ApplicationSpecificationAdapter adapter = ApplicationSpecificationAdapter.create(new ReflectionSchemaGenerator()); String jsonSpec = adapter.toJson(spec); OperationContext context = new OperationContext(id.getAccountId()); LOG.trace("Application being stored: id: {}: spec: {}", id.getId(), jsonSpec); MetaDataEntry existing = metaDataTable.get(context, id.getAccountId(), null, FieldTypes.Application.ENTRY_TYPE, id.getId()); if (existing == null) { MetaDataEntry entry = new MetaDataEntry(id.getAccountId(), null, FieldTypes.Application.ENTRY_TYPE, id.getId()); entry.addField(FieldTypes.Application.SPEC_JSON, jsonSpec); entry.addField(FieldTypes.Application.TIMESTAMP, Long.toString(timestamp)); metaDataTable.add(context, entry); LOG.trace("Added application to mds: id: {}, spec: {}", id.getId(), jsonSpec); } else { LOG.trace("Application exists in mds: id: {}, spec: {}", id.getId(), existing.getTextField(FieldTypes.Application.SPEC_JSON)); metaDataTable.updateField(context, id.getAccountId(), null, FieldTypes.Application.ENTRY_TYPE, id.getId(), FieldTypes.Application.SPEC_JSON, jsonSpec, -1); metaDataTable.updateField(context, id.getAccountId(), null, FieldTypes.Application.ENTRY_TYPE, id.getId(), FieldTypes.Application.TIMESTAMP, Long.toString(timestamp), -1); LOG.trace("Updated application in mds: id: {}, spec: {}", id.getId(), jsonSpec); } for (DataSetSpecification dsSpec : spec.getDataSets().values()) { addDataset(id.getAccount(), dsSpec); } for (StreamSpecification stream : spec.getStreams().values()) { addStream(id.getAccount(), stream); } } @Override public void addDataset(Id.Account id, DataSetSpecification dsSpec) throws OperationException { String json = new Gson().toJson(dsSpec); OperationContext context = new OperationContext(id.getId()); MetaDataEntry existing = metaDataTable.get(context, id.getId(), null, FieldTypes.DataSet.ENTRY_TYPE, dsSpec.getName()); if (existing == null) { MetaDataEntry entry = new MetaDataEntry(id.getId(), null, FieldTypes.DataSet.ENTRY_TYPE, dsSpec.getName()); entry.addField(FieldTypes.DataSet.SPEC_JSON, json); metaDataTable.add(context, entry, true); } else { metaDataTable.updateField(context, id.getId(), null, FieldTypes.DataSet.ENTRY_TYPE, dsSpec.getName(), FieldTypes.DataSet.SPEC_JSON, json, -1); } } @Override public void removeDataSet(Id.Account id, String name) throws OperationException { OperationContext context = new OperationContext(id.getId()); metaDataTable.delete(context, id.getId(), null, FieldTypes.DataSet.ENTRY_TYPE, name); } @Override public DataSetSpecification getDataSet(Id.Account id, String name) throws OperationException { OperationContext context = new OperationContext(id.getId()); MetaDataEntry entry = metaDataTable.get(context, id.getId(), null, FieldTypes.DataSet.ENTRY_TYPE, name); return entry == null ? null : new Gson().fromJson(entry.getTextField(FieldTypes.DataSet.SPEC_JSON), DataSetSpecification.class); } @Override public Collection<DataSetSpecification> getAllDataSets(Id.Account id) throws OperationException { OperationContext context = new OperationContext(id.getId()); List<MetaDataEntry> entries = metaDataTable.list(context, id.getId(), null, FieldTypes.DataSet.ENTRY_TYPE, null); List<DataSetSpecification> specs = Lists.newArrayListWithExpectedSize(entries.size()); for (MetaDataEntry entry : entries) { specs.add(new Gson().fromJson(entry.getTextField(FieldTypes.DataSet.SPEC_JSON), DataSetSpecification.class)); } return specs; } @Override public void addStream(Id.Account id, StreamSpecification streamSpec) throws OperationException { String json = new Gson().toJson(streamSpec); OperationContext context = new OperationContext(id.getId()); MetaDataEntry existing = metaDataTable.get(context, id.getId(), null, FieldTypes.Stream.ENTRY_TYPE, streamSpec.getName()); if (existing == null) { MetaDataEntry entry = new MetaDataEntry(id.getId(), null, FieldTypes.Stream.ENTRY_TYPE, streamSpec.getName()); entry.addField(FieldTypes.Stream.SPEC_JSON, json); metaDataTable.add(context, entry); } else { metaDataTable.updateField(context, id.getId(), null, FieldTypes.Stream.ENTRY_TYPE, streamSpec.getName(), FieldTypes.Stream.SPEC_JSON, json, -1); } } @Override public void removeStream(Id.Account id, String name) throws OperationException { OperationContext context = new OperationContext(id.getId()); metaDataTable.delete(context, id.getId(), null, FieldTypes.Stream.ENTRY_TYPE, name); } @Override public StreamSpecification getStream(Id.Account id, String name) throws OperationException { OperationContext context = new OperationContext(id.getId()); MetaDataEntry entry = metaDataTable.get(context, id.getId(), null, FieldTypes.Stream.ENTRY_TYPE, name); return entry == null ? null : new Gson().fromJson(entry.getTextField(FieldTypes.Stream.SPEC_JSON), StreamSpecification.class); } @Override public Collection<StreamSpecification> getAllStreams(Id.Account id) throws OperationException { OperationContext context = new OperationContext(id.getId()); List<MetaDataEntry> entries = metaDataTable.list(context, id.getId(), null, FieldTypes.Stream.ENTRY_TYPE, null); List<StreamSpecification> specs = Lists.newArrayListWithExpectedSize(entries.size()); for (MetaDataEntry entry : entries) { specs.add(new Gson().fromJson(entry.getTextField(FieldTypes.Stream.SPEC_JSON), StreamSpecification.class)); } return specs; } @Override public void setFlowletInstances(final Id.Program id, final String flowletId, int count) throws OperationException { Preconditions.checkArgument(count > 0, "cannot change number of flowlet instances to negative number: " + count); LOG.trace("Setting flowlet instances: account: {}, application: {}, flow: {}, flowlet: {}, new instances count: {}", id.getAccountId(), id.getApplicationId(), id.getId(), flowletId, count); ApplicationSpecification newAppSpec = updateFlowletInstancesInAppSpec(id, flowletId, count); replaceAppSpecInProgramJar(id, newAppSpec, Type.FLOW); long timestamp = System.currentTimeMillis(); storeAppSpec(id.getApplication(), newAppSpec, timestamp); LOG.trace("Set flowlet instances: account: {}, application: {}, flow: {}, flowlet: {}, instances now: {}", id.getAccountId(), id.getApplicationId(), id.getId(), flowletId, count); } /** * Gets number of instances of specific flowlet. * * @param id flow id * @param flowletId flowlet id * @throws com.continuuity.api.data.OperationException * */ @Override public int getFlowletInstances(Id.Program id, String flowletId) throws OperationException { ApplicationSpecification appSpec = getAppSpecSafely(id); FlowSpecification flowSpec = getFlowSpecSafely(id, appSpec); FlowletDefinition flowletDef = getFlowletDefinitionSafely(flowSpec, flowletId, id); return flowletDef.getInstances(); } private ApplicationSpecification updateFlowletInstancesInAppSpec(Id.Program id, String flowletId, int count) throws OperationException { ApplicationSpecification appSpec = getAppSpecSafely(id); FlowSpecification flowSpec = getFlowSpecSafely(id, appSpec); FlowletDefinition flowletDef = getFlowletDefinitionSafely(flowSpec, flowletId, id); final FlowletDefinition adjustedFlowletDef = new FlowletDefinition(flowletDef, count); ApplicationSpecification newAppSpec = replaceFlowletInAppSpec(appSpec, id, flowSpec, adjustedFlowletDef); return newAppSpec; } @Override public int getProcedureInstances(Id.Program id) throws OperationException { ApplicationSpecification appSpec = getAppSpecSafely(id); ProcedureSpecification specification = getProcedureSpecSafely(id, appSpec); return specification.getInstances(); } @Override public void setProcedureInstances(Id.Program id, int count) throws OperationException { Preconditions.checkArgument(count > 0, "cannot change number of program instances to negative number: " + count); long timestamp = System.currentTimeMillis(); ApplicationSpecification appSpec = getAppSpecSafely(id); ProcedureSpecification specification = getProcedureSpecSafely(id, appSpec); ProcedureSpecification newSpecification = new DefaultProcedureSpecification(specification.getClassName(), specification.getName(), specification.getDescription(), specification.getDataSets(), specification.getProperties(), specification.getResources(), count); ApplicationSpecification newAppSpec = replaceProcedureInAppSpec(appSpec, id, newSpecification); storeAppSpec(id.getApplication(), newAppSpec, timestamp); LOG.trace("Setting program instances: account: {}, application: {}, procedure: {}, new instances count: {}", id.getAccountId(), id.getApplicationId(), id.getId(), count); } private void replaceAppSpecInProgramJar(Id.Program id, ApplicationSpecification appSpec, Type type) { Location programLocation; try { programLocation = getProgramLocation(id, Type.FLOW); } catch (IOException e) { throw Throwables.propagate(e); } ArchiveBundler bundler = new ArchiveBundler(programLocation); String className = appSpec.getFlows().get(id.getId()).getClassName(); try { Location tmpProgramLocation = programLocation.getTempFile(""); try { ProgramBundle.create(id.getApplication(), bundler, tmpProgramLocation, id.getId(), className, type, appSpec); Location movedTo = tmpProgramLocation.renameTo(programLocation); if (movedTo == null) { throw new RuntimeException("Could not replace program jar with the one with updated app spec, " + "original program file: " + programLocation.toURI() + ", was trying to replace with file: " + tmpProgramLocation.toURI()); } } finally { if (tmpProgramLocation != null && tmpProgramLocation.exists()) { tmpProgramLocation.delete(); } } } catch (IOException e) { throw Throwables.propagate(e); } } private FlowletDefinition getFlowletDefinitionSafely(FlowSpecification flowSpec, String flowletId, Id.Program id) { FlowletDefinition flowletDef = flowSpec.getFlowlets().get(flowletId); if (flowletDef == null) { throw new IllegalArgumentException("no such flowlet @ account id: " + id.getAccountId() + ", app id: " + id.getApplication() + ", flow id: " + id.getId() + ", flowlet id: " + id.getId()); } return flowletDef; } private FlowSpecification getFlowSpecSafely(Id.Program id, ApplicationSpecification appSpec) { FlowSpecification flowSpec = appSpec.getFlows().get(id.getId()); if (flowSpec == null) { throw new IllegalArgumentException("no such flow @ account id: " + id.getAccountId() + ", app id: " + id.getApplication() + ", flow id: " + id.getId()); } return flowSpec; } private ProcedureSpecification getProcedureSpecSafely(Id.Program id, ApplicationSpecification appSpec) { ProcedureSpecification procedureSpecification = appSpec.getProcedures().get(id.getId()); if (procedureSpecification == null) { throw new IllegalArgumentException("no such procedure @ account id: " + id.getAccountId() + ", app id: " + id.getApplication() + ", procedure id: " + id.getId()); } return procedureSpecification; } @Override public ApplicationSpecification removeApplication(Id.Application id) throws OperationException { LOG.trace("Removing application: account: {}, application: {}", id.getAccountId(), id.getId()); ApplicationSpecification appSpec = getApplication(id); Preconditions.checkNotNull(appSpec, "No such application: %s", id.getId()); removeApplicationFromAppSpec(id.getAccount(), appSpec); return appSpec; } @Override public void removeAllApplications(Id.Account id) throws OperationException { OperationContext context = new OperationContext(id.getId()); LOG.trace("Removing all applications of account with id: {}", id.getId()); List<MetaDataEntry> applications = metaDataTable.list(context, id.getId(), null, FieldTypes.Application.ENTRY_TYPE, null); ApplicationSpecificationAdapter adapter = ApplicationSpecificationAdapter.create(); for (MetaDataEntry entry : applications) { removeApplicationFromAppSpec(id, adapter.fromJson(entry.getTextField(FieldTypes.Application.SPEC_JSON))); } } @Override public void removeAll(Id.Account id) throws OperationException { OperationContext context = new OperationContext(id.getId()); LOG.trace("Removing all metadata of account with id: {}", id.getId()); List<MetaDataEntry> applications = metaDataTable.list(context, id.getId(), null, FieldTypes.Application.ENTRY_TYPE, null); // removing apps for (MetaDataEntry entry : applications) { metaDataTable.delete(context, id.getId(), null, FieldTypes.Application.ENTRY_TYPE, entry.getId()); } } @Override public void storeRunArguments(Id.Program id, Map<String, String> arguments) throws OperationException { OperationContext context = new OperationContext(id.getId()); MetaDataEntry existing = metaDataTable.get(context, id.getAccountId(), id.getApplicationId(), FieldTypes.ProgramRun.ARGS, id.getId()); if (existing == null) { MetaDataEntry entry = new MetaDataEntry(id.getAccountId(), id.getApplicationId(), FieldTypes.ProgramRun.ARGS, id.getId()); entry.addField(FieldTypes.ProgramRun.ENTRY_TYPE, gson.toJson(arguments)); metaDataTable.add(context, entry); LOG.trace("Added run time arguments to mds: id: {}, app: {}, prog: {} ", id.getAccountId(), id.getApplicationId(), id.getId()); } else { LOG.trace("Run time args exists in mds: id: {}, app: {}, prog: {}", id.getAccountId(), id.getApplicationId(), id.getId()); metaDataTable.updateField(context, id.getAccountId(), id.getApplicationId(), FieldTypes.ProgramRun.ARGS, id.getId(), FieldTypes.ProgramRun.ENTRY_TYPE, gson.toJson(arguments), -1); LOG.trace("Updated application in mds: id: {}, app: {}, prog: {}", id.getId(), id.getApplicationId(), id.getId()); } } @Override public Map<String, String> getRunArguments(Id.Program id) throws OperationException { OperationContext context = new OperationContext(id.getId()); MetaDataEntry existing = metaDataTable.get(context, id.getAccountId(), id.getApplicationId(), FieldTypes.ProgramRun.ARGS, id.getId()); Map<String, String> args = Maps.newHashMap(); if (existing != null) { java.lang.reflect.Type type = new TypeToken<Map<String, String>>(){}.getType(); args = gson.fromJson(existing.getTextField(FieldTypes.ProgramRun.ENTRY_TYPE), type); } return args; } private void removeApplicationFromAppSpec(Id.Account id, ApplicationSpecification appSpec) throws OperationException { OperationContext context = new OperationContext(id.getId()); metaDataTable.delete(context, id.getId(), null, FieldTypes.Application.ENTRY_TYPE, appSpec.getName()); } private ApplicationSpecification getAppSpecSafely(Id.Program id) throws OperationException { ApplicationSpecification appSpec = getApplication(id.getApplication()); if (appSpec == null) { throw new IllegalArgumentException("no such application @ account id: " + id.getAccountId() + ", app id: " + id.getApplication().getId()); } return appSpec; } private ApplicationSpecification replaceFlowletInAppSpec(final ApplicationSpecification appSpec, final Id.Program id, final FlowSpecification flowSpec, final FlowletDefinition adjustedFlowletDef) { // as app spec is immutable we have to do this trick return replaceFlowInAppSpec(appSpec, id, new ForwardingFlowSpecification(flowSpec) { @Override public Map<String, FlowletDefinition> getFlowlets() { Map<String, FlowletDefinition> flowlets = Maps.newHashMap(super.getFlowlets()); flowlets.put(adjustedFlowletDef.getFlowletSpec().getName(), adjustedFlowletDef); return flowlets; } }); } private ApplicationSpecification replaceFlowInAppSpec(final ApplicationSpecification appSpec, final Id.Program id, final FlowSpecification newFlowSpec) { // as app spec is immutable we have to do this trick return new ForwardingApplicationSpecification(appSpec) { @Override public Map<String, FlowSpecification> getFlows() { Map<String, FlowSpecification> flows = Maps.newHashMap(super.getFlows()); flows.put(id.getId(), newFlowSpec); return flows; } }; } private ApplicationSpecification replaceProcedureInAppSpec(final ApplicationSpecification appSpec, final Id.Program id, final ProcedureSpecification procedureSpecification) { // replace the new procedure spec. return new ForwardingApplicationSpecification(appSpec) { @Override public Map<String, ProcedureSpecification> getProcedures() { Map<String, ProcedureSpecification> procedures = Maps.newHashMap(super.getProcedures()); procedures.put(id.getId(), procedureSpecification); return procedures; } }; } @Override public ApplicationSpecification getApplication(final Id.Application id) throws OperationException { OperationContext context = new OperationContext(id.getAccountId()); MetaDataEntry entry = metaDataTable.get(context, id.getAccountId(), null, FieldTypes.Application.ENTRY_TYPE, id.getId()); if (entry == null) { return null; } ApplicationSpecificationAdapter adapter = ApplicationSpecificationAdapter.create(); return adapter.fromJson(entry.getTextField(FieldTypes.Application.SPEC_JSON)); } @Override public Collection<ApplicationSpecification> getAllApplications(final Id.Account id) throws OperationException { OperationContext context = new OperationContext(id.getId()); List<MetaDataEntry> entries = metaDataTable.list(context, id.getId(), null, FieldTypes.Application.ENTRY_TYPE, null); if (entries == null) { return null; } ApplicationSpecificationAdapter adapter = ApplicationSpecificationAdapter.create(); List<ApplicationSpecification> specs = Lists.newArrayListWithExpectedSize(entries.size()); for (MetaDataEntry entry : entries) { specs.add(adapter.fromJson(entry.getTextField(FieldTypes.Application.SPEC_JSON))); } return specs; } @Override public Location getApplicationArchiveLocation(Id.Application id) throws OperationException { OperationContext context = new OperationContext(id.getAccountId()); MetaDataEntry entry = metaDataTable.get(context, id.getAccountId(), null, FieldTypes.Application.ENTRY_TYPE, id.getId()); if (entry == null) { return null; } return locationFactory.create(entry.getTextField(FieldTypes.Application.ARCHIVE_LOCATION)); } private String getTimestampedId(String id, long timestamp) { return String.format("%s:%d", id, timestamp); } private String getTimestampedId(String id, String pid, long timestamp) { return String.format("%s:%d:%s", id, timestamp, pid); } //delete history for older dates private void deleteOlderMetadataHistory(OperationContext context, Id.Program id) throws OperationException { //delete stale history // Delete all entries that are greater than RUN_HISTORY_KEEP_DAYS to Long.MAX_VALUE int historyKeepDays = configuration.getInt(Constants.CFG_RUN_HISTORY_KEEP_DAYS, Constants.DEFAULT_RUN_HISTORY_KEEP_DAYS); long deleteStartTime = TimeUnit.SECONDS.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS) - (historyKeepDays * 24 * 60 * 60L); String deleteStartKey = getTimestampedId(id.getId(), Long.MAX_VALUE - deleteStartTime); String deleteStopKey = getTimestampedId(id.getId(), Long.MAX_VALUE); List<MetaDataEntry> entries = metaDataTable.list(context, id.getAccountId(), id.getApplicationId(), FieldTypes.ProgramRun.ENTRY_TYPE, deleteStartKey, deleteStopKey, Integer.MAX_VALUE); if (entries.size() > 0) { metaDataTable.delete(id.getAccountId(), entries); } } }
package edu.berkeley.cs.amplab.carat.android.storage; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import org.apache.thrift.meta_data.FieldMetaData; import android.util.Log; import edu.berkeley.cs.amplab.carat.thrift.BatteryDetails; import edu.berkeley.cs.amplab.carat.thrift.CpuStatus; import edu.berkeley.cs.amplab.carat.thrift.Feature; import edu.berkeley.cs.amplab.carat.thrift.NetworkDetails; import edu.berkeley.cs.amplab.carat.thrift.ProcessInfo; import edu.berkeley.cs.amplab.carat.thrift.Sample; import edu.berkeley.cs.amplab.carat.thrift.Sample._Fields; /** * * This class reads HashMaps from the database and outputs a Sample with fields * filled in. * * TODO: FIXME: This class needs to be modified when the protocol is changed. Otherwise new fields will not be included in Samples. * * @author Eemil Lagerspetz * */ public class SampleReader { public static final String TAG = "SampleReader"; /** * Library class, instantiation prohibited. */ private SampleReader() { } /** * For simplicity, this method relies on the fact that * only the piList of Sample has any List type elements. * This will fail to record those from substructs (NetworkDetails, BatteryDetails, CpuStatus), * and will need to be changed if those are added. * * Does not record CallInfo, CellInfo, or CallMonth types. */ public static final HashMap<String, String> writeSample(Sample s) { HashMap<String, String> m = new HashMap<String, String>(); for (_Fields sf: Sample.metaDataMap.keySet()){ FieldMetaData md = Sample.metaDataMap.get(sf); switch (md.valueMetaData.type) { case org.apache.thrift.protocol.TType.STRING: case org.apache.thrift.protocol.TType.I32: case org.apache.thrift.protocol.TType.DOUBLE: m.put(sf.getFieldName(), s.getFieldValue(sf).toString().replaceAll("\n", " ").replaceAll(";", ",")); break; case org.apache.thrift.protocol.TType.STRUCT: if (md.fieldName.equals(Sample._Fields.NETWORK_DETAILS.getFieldName()) && s.networkDetails != null) { int len = NetworkDetails._Fields.values().length; StringBuilder b = new StringBuilder(); for (int i = 1; i <= len; i++){ b.append((""+s.networkDetails.getFieldValue(NetworkDetails._Fields.findByThriftId(i))).replaceAll("\n", " ").replaceAll(";", ",")); if ( i < len) b.append("\n"); } m.put(sf.getFieldName(), b.toString()); } else if (md.fieldName.equals(Sample._Fields.BATTERY_DETAILS.getFieldName()) && s.batteryDetails != null) { int len = BatteryDetails._Fields.values().length; StringBuilder b = new StringBuilder(); for (int i = 1; i <= len; i++){ b.append((""+s.batteryDetails.getFieldValue(BatteryDetails._Fields.findByThriftId(i))).replaceAll("\n", " ").replaceAll(";", ",")); if ( i < len) b.append("\n"); } m.put(sf.getFieldName(), b.toString()); } else if (md.fieldName.equals(Sample._Fields.CPU_STATUS.getFieldName()) && s.cpuStatus != null) { int len = CpuStatus._Fields.values().length; StringBuilder b = new StringBuilder(); for (int i = 1; i <= len; i++){ b.append((""+s.cpuStatus.getFieldValue(CpuStatus._Fields.findByThriftId(i))).replaceAll("\n", " ").replaceAll(";", ",")); if ( i < len) b.append("\n"); } m.put(sf.getFieldName(), b.toString()); }/* * else if (md.fieldName.equals("CallInfo")){ } */ break; case org.apache.thrift.protocol.TType.LIST: if (md.fieldName.equals(Sample._Fields.EXTRA.getFieldName()) && s.extra != null) { StringBuilder b = new StringBuilder(); for (Feature f : s.extra) { b.append(f.key.replaceAll("\n", " ").replaceAll(";", ",") + ";" + f.value.replaceAll("\n", " ").replaceAll(";", ",") + "\n"); } if (b.length() > 1) b.deleteCharAt(b.lastIndexOf("\n")); m.put(sf.getFieldName(), b.toString()); } else if (md.fieldName.equals(Sample._Fields.LOCATION_PROVIDERS.getFieldName()) && s.locationProviders != null) { StringBuilder b = new StringBuilder(); for (String lp : s.locationProviders) b.append(lp + "\n"); if (b.length() > 1) b.deleteCharAt(b.lastIndexOf("\n")); m.put(sf.getFieldName(), b.toString()); } else if (md.fieldName.equals(Sample._Fields.PI_LIST.getFieldName()) && s.piList != null) { StringBuilder b = new StringBuilder(); for (ProcessInfo pi : s.piList) { int len = ProcessInfo._Fields.values().length; for (int i = 1; i <= len; i++) { ProcessInfo._Fields pif = ProcessInfo._Fields .findByThriftId(i); FieldMetaData pmd = ProcessInfo.metaDataMap .get(pif); if (pmd.valueMetaData.type == org.apache.thrift.protocol.TType.LIST) { if (pi.appSignatures != null) { for (int j = 0; j < pi.appSignatures.size(); j++) { String sig = pi.appSignatures.get(j); b.append(sig); if (j + 1 < len) b.append(" } } } else { b.append(("" + pi.getFieldValue(pif)).replaceAll("\n", " ").replaceAll(";", ",")); } if (i < len) b.append(";"); } b.append("\n"); } if (b.length() > 1) b.deleteCharAt(b.lastIndexOf("\n")); m.put(sf.getFieldName(), b.toString()); } break; default: } } return m; } /** * Read a Sample from a HashMap stored in the Carat Sample db. * @param data * @return */ public static final Sample readSample(Object data) { Sample s = null; if (data != null && data instanceof HashMap<?, ?>) { HashMap<String, String> m = (HashMap<String, String>) data; s = new Sample(); NetworkDetails n = new NetworkDetails(); BatteryDetails bd = new BatteryDetails(); // CellInfo ci = new CellInfo(); // CallInfo calli = new CallInfo(); // CallMonth cm = new CallMonth(); CpuStatus cs = new CpuStatus(); // Set single fields automatically: for (String k : m.keySet()) { _Fields sf = Sample._Fields.findByName(k); if (sf != null) { // Top level Sample field. FieldMetaData md = Sample.metaDataMap.get(sf); String cleaned = m.get(k).replaceAll("\"", ""); switch (md.valueMetaData.type) { case org.apache.thrift.protocol.TType.STRING: s.setFieldValue(sf, cleaned); break; case org.apache.thrift.protocol.TType.I32: try { s.setFieldValue(sf, Integer.parseInt(cleaned)); } catch (NumberFormatException e) { Log.e(TAG, "Could not read " + md.fieldName + ": \"" + cleaned + "\" as an int"); } break; case org.apache.thrift.protocol.TType.DOUBLE: try { s.setFieldValue(sf, Double.parseDouble(cleaned)); } catch (NumberFormatException e) { Log.e(TAG, "Could not read " + md.fieldName + ": \"" + cleaned + "\" as a double"); } break; case org.apache.thrift.protocol.TType.STRUCT: if (md.fieldName.equals(Sample._Fields.NETWORK_DETAILS.getFieldName())) { fillNetworkDetails(m.get(k), n); s.setNetworkDetails(n); } else if (md.fieldName.equals(Sample._Fields.BATTERY_DETAILS.getFieldName())) { fillBatteryDetails(m.get(k), bd); s.setNetworkDetails(n); } else if (md.fieldName.equals(Sample._Fields.CPU_STATUS.getFieldName())) { fillCpuStatusDetails(m.get(k), cs); s.setNetworkDetails(n); }/* * else if (md.fieldName.equals("CallInfo")){ } */ break; case org.apache.thrift.protocol.TType.LIST: if (md.fieldName.equals(Sample._Fields.EXTRA.getFieldName())) { List<Feature> list = new LinkedList<Feature>(); String[] extras = m.get(k).split("\n"); for (String e : extras) { Feature f = new Feature(); String[] feat = e.split(";"); if (feat.length > 1) { f.setKey(feat[0]); f.setValue(feat[1]); } list.add(f); } s.setExtra(list); } else if (md.fieldName.equals(Sample._Fields.LOCATION_PROVIDERS.getFieldName())) { List<String> list = new LinkedList<String>(); String[] arr = m.get(k).split("\n"); for (String lp : arr) list.add(lp); s.setLocationProviders(list); }else if (md.fieldName.equals(Sample._Fields.PI_LIST.getFieldName())){ // Set piList fields automatically: LinkedList<ProcessInfo> piList = new LinkedList<ProcessInfo>(); String[] processes = m.get(md.fieldName).split("\n"); for (String process : processes) { String[] items = process.split(";"); ProcessInfo pi = new ProcessInfo(); /* * Items are in the same order as they appear in ProcessInfo * protocol class, so I can use Thrift ID for setting the fields * automatically. */ for (int i = 1; i <= items.length; i++) { if (items[i-1] == null) continue; ProcessInfo._Fields pif = ProcessInfo._Fields .findByThriftId(i); FieldMetaData pmd = ProcessInfo.metaDataMap.get(pif); cleaned = items[i - 1].replaceAll("\"", ""); switch (pmd.valueMetaData.type) { case org.apache.thrift.protocol.TType.STRING: pi.setFieldValue(pif, cleaned); break; case org.apache.thrift.protocol.TType.I32: try{ pi.setFieldValue(pif, Integer.parseInt(cleaned)); }catch (NumberFormatException e){ Log.e(TAG, "Could not read "+md.fieldName+": \""+cleaned+"\" as an int"); } break; case org.apache.thrift.protocol.TType.DOUBLE: try{ pi.setFieldValue(pif, Double.parseDouble(cleaned)); }catch (NumberFormatException e){ Log.e(TAG, "Could not read "+md.fieldName+": \""+cleaned+"\" as a double"); } break; case org.apache.thrift.protocol.TType.BOOL: try{ pi.setFieldValue(pif, Boolean.parseBoolean(cleaned)); }catch (NumberFormatException e){ Log.e(TAG, "Could not read "+md.fieldName+": \""+cleaned+"\" as a bool"); } break; case org.apache.thrift.protocol.TType.LIST: List<String> list = new LinkedList<String>(); String[] arr = cleaned.split(" for (String sig : arr) list.add(sig); pi.setFieldValue(pif, list); break; default: } } piList.add(pi); } s.setPiList(piList); } break; default: } } } } return s; } private static void fillCpuStatusDetails(String string, CpuStatus cs) { String[] items = string.split("\n"); for (int i = 1; i <= items.length; i++) { CpuStatus._Fields pif = CpuStatus._Fields.findByThriftId(i); FieldMetaData md = CpuStatus.metaDataMap.get(pif); String cleaned = items[i - 1].replaceAll("\"", ""); switch (md.valueMetaData.type) { case org.apache.thrift.protocol.TType.STRING: cs.setFieldValue(pif, cleaned); break; case org.apache.thrift.protocol.TType.I32: try{ cs.setFieldValue(pif, Integer.parseInt(cleaned)); }catch (NumberFormatException e){ Log.e(TAG, "Could not read "+md.fieldName+": \""+cleaned+"\" as an int"); } break; case org.apache.thrift.protocol.TType.DOUBLE: try{ cs.setFieldValue(pif, Double.parseDouble(cleaned)); }catch (NumberFormatException e){ Log.e(TAG, "Could not read "+md.fieldName+": \""+cleaned+"\" as a double"); } break; case org.apache.thrift.protocol.TType.BOOL: try{ cs.setFieldValue(pif, Boolean.parseBoolean(cleaned)); }catch (NumberFormatException e){ Log.e(TAG, "Could not read "+md.fieldName+": \""+cleaned+"\" as a bool"); } break; case org.apache.thrift.protocol.TType.LIST: List<String> list = new LinkedList<String>(); String[] arr = items[i - 1].split(";"); for (String sig : arr) list.add(sig); cs.setFieldValue(pif, list); break; default: } } } private static void fillBatteryDetails(String string, BatteryDetails bd) { String[] items = string.split("\n"); for (int i = 1; i <= items.length; i++) { BatteryDetails._Fields pif = BatteryDetails._Fields .findByThriftId(i); FieldMetaData md = BatteryDetails.metaDataMap.get(pif); String cleaned = items[i - 1].replaceAll("\"", ""); switch (md.valueMetaData.type) { case org.apache.thrift.protocol.TType.STRING: bd.setFieldValue(pif, cleaned); break; case org.apache.thrift.protocol.TType.I32: try { bd.setFieldValue(pif, Integer.parseInt(cleaned)); } catch (NumberFormatException e) { Log.e(TAG, "Could not read "+md.fieldName+": \"" + cleaned + "\" as an int"); } break; case org.apache.thrift.protocol.TType.DOUBLE: try { bd.setFieldValue(pif, Double.parseDouble(cleaned)); } catch (NumberFormatException e) { Log.e(TAG, "Could not read "+md.fieldName+": \"" + cleaned + "\" as a double"); } break; case org.apache.thrift.protocol.TType.BOOL: try { bd.setFieldValue(pif, Boolean.parseBoolean(cleaned)); } catch (NumberFormatException e) { Log.e(TAG, "Could not read "+md.fieldName+": \"" + cleaned + "\" as a bool"); } break; case org.apache.thrift.protocol.TType.LIST: List<String> list = new LinkedList<String>(); String[] arr = items[i - 1].split(";"); for (String sig : arr) list.add(sig); bd.setFieldValue(pif, list); break; default: } } } private static void fillNetworkDetails(String string, NetworkDetails nd) { String[] items = string.split("\n"); for (int i = 1; i <= items.length; i++) { NetworkDetails._Fields pif = NetworkDetails._Fields .findByThriftId(i); FieldMetaData md = NetworkDetails.metaDataMap.get(pif); String cleaned = items[i - 1].replaceAll("\"", ""); switch (md.valueMetaData.type) { case org.apache.thrift.protocol.TType.STRING: nd.setFieldValue(pif, cleaned); break; case org.apache.thrift.protocol.TType.I32: try { nd.setFieldValue(pif, Integer.parseInt(cleaned)); } catch (NumberFormatException e) { Log.e(TAG, "Could not read " + md.fieldName + ": \"" + cleaned + "\" as an int"); } break; case org.apache.thrift.protocol.TType.DOUBLE: try { nd.setFieldValue(pif, Double.parseDouble(cleaned)); } catch (NumberFormatException e) { Log.e(TAG, "Could not read " + md.fieldName + ": \"" + cleaned + "\" as a double"); } break; case org.apache.thrift.protocol.TType.BOOL: try { nd.setFieldValue(pif, Boolean.parseBoolean(cleaned)); } catch (NumberFormatException e) { Log.e(TAG, "Could not read " + md.fieldName + ": \"" + cleaned + "\" as a bool"); } break; case org.apache.thrift.protocol.TType.LIST: List<String> list = new LinkedList<String>(); String[] arr = items[i - 1].split(";"); for (String sig : arr) list.add(sig); nd.setFieldValue(pif, list); break; default: } } } }
package org.lenskit.results; import com.google.common.base.MoreObjects; import org.lenskit.api.Result; import javax.annotation.concurrent.Immutable; import java.io.*; /** * A basic {@link Result} implementation with no details. * * @see Results */ @Immutable public final class BasicResult extends AbstractResult implements Serializable { private static final long serialVersionUID = 1L; /** * Create a new basic result. * @param id The result ID. * @param score The result score. * @see Results#create(long, double) */ public BasicResult(long id, double score) { super(id, score); } //region Serialization support private void writeObject(ObjectOutputStream out) throws IOException { out.writeLong(id); out.writeDouble(score); } private void readObject(ObjectInputStream in) throws IOException { id = in.readLong(); score = in.readDouble(); } private void readObjectNoData() throws ObjectStreamException { throw new InvalidObjectException("basic result must have data"); } //endregion //region Value object behavior /** * Compare this result with another for equality. Instance of this result type are only equal with other basic * result instances; to compare general results for equality, first convert them to basic results with * {@link Results#basicCopy(Result)}. * * @param o The object to compare with. * @return `true` if the objects are equivalent. */ @Override public boolean equals(Object o) { if (o == this) { return true; } else if (o != null && o.getClass().equals(BasicResult.class)) { BasicResult or = (BasicResult) o; return startEquality(or).isEquals(); } else { return false; } } @Override public int hashCode() { return startHashCode().toHashCode(); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("id", id) .add("score", score) .toString(); } //endregion }
package org.springframework.roo.addon.web.mvc.jsp; import static org.springframework.roo.model.JavaType.BOOLEAN_OBJECT; import static org.springframework.roo.model.JavaType.BOOLEAN_PRIMITIVE; import static org.springframework.roo.model.JavaType.DOUBLE_OBJECT; import static org.springframework.roo.model.JavaType.FLOAT_OBJECT; import static org.springframework.roo.model.JavaType.INT_OBJECT; import static org.springframework.roo.model.JavaType.LONG_OBJECT; import static org.springframework.roo.model.JavaType.SHORT_OBJECT; import static org.springframework.roo.model.JavaType.STRING; import static org.springframework.roo.model.JdkJavaType.BIG_DECIMAL; import static org.springframework.roo.model.JdkJavaType.BIG_INTEGER; import static org.springframework.roo.model.JdkJavaType.CALENDAR; import static org.springframework.roo.model.JdkJavaType.DATE; import static org.springframework.roo.model.Jsr303JavaType.DECIMAL_MAX; import static org.springframework.roo.model.Jsr303JavaType.DECIMAL_MIN; import static org.springframework.roo.model.Jsr303JavaType.FUTURE; import static org.springframework.roo.model.Jsr303JavaType.MAX; import static org.springframework.roo.model.Jsr303JavaType.MIN; import static org.springframework.roo.model.Jsr303JavaType.NOT_NULL; import static org.springframework.roo.model.Jsr303JavaType.PAST; import static org.springframework.roo.model.Jsr303JavaType.PATTERN; import static org.springframework.roo.model.Jsr303JavaType.SIZE; import java.beans.Introspector; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import javax.xml.parsers.DocumentBuilder; import org.springframework.roo.addon.web.mvc.controller.details.FinderMetadataDetails; import org.springframework.roo.addon.web.mvc.controller.details.JavaTypeMetadataDetails; import org.springframework.roo.addon.web.mvc.controller.details.JavaTypePersistenceMetadataDetails; import org.springframework.roo.addon.web.mvc.controller.scaffold.WebScaffoldAnnotationValues; import org.springframework.roo.classpath.customdata.CustomDataKeys; import org.springframework.roo.classpath.details.FieldMetadata; import org.springframework.roo.classpath.details.FieldMetadataBuilder; import org.springframework.roo.classpath.details.MemberFindingUtils; import org.springframework.roo.classpath.details.MethodMetadata; import org.springframework.roo.classpath.details.annotations.AnnotationAttributeValue; import org.springframework.roo.classpath.details.annotations.AnnotationMetadata; import org.springframework.roo.model.JavaSymbolName; import org.springframework.roo.model.JavaType; import org.springframework.roo.support.util.Assert; import org.springframework.roo.support.util.DomUtils; import org.springframework.roo.support.util.StringUtils; import org.springframework.roo.support.util.XmlElementBuilder; import org.springframework.roo.support.util.XmlRoundTripUtils; import org.springframework.roo.support.util.XmlUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * Helper class which generates the contents of the various jsp documents * * @author Stefan Schmidt * @since 1.1 */ public class JspViewManager { // Constants private static final JavaSymbolName VALUE = new JavaSymbolName("value"); // Fields private final JavaType formBackingType; private final JavaTypeMetadataDetails formBackingTypeMetadata; private final JavaTypePersistenceMetadataDetails formBackingTypePersistenceMetadata; private final List<FieldMetadata> fields; private final Map<JavaType, JavaTypeMetadataDetails> relatedDomainTypes; private final String entityName; private final String controllerPath; private final WebScaffoldAnnotationValues webScaffoldAnnotationValues; /** * Constructor * * @param fields can't be <code>null</code> * @param webScaffoldAnnotationValues can't be <code>null</code> * @param relatedDomainTypes can't be <code>null</code> */ public JspViewManager(final List<FieldMetadata> fields, final WebScaffoldAnnotationValues webScaffoldAnnotationValues, final Map<JavaType, JavaTypeMetadataDetails> relatedDomainTypes) { Assert.notNull(fields, "List of fields required"); Assert.notNull(webScaffoldAnnotationValues, "Web scaffold annotation values required"); Assert.notNull(relatedDomainTypes, "Related domain types required"); this.fields = Collections.unmodifiableList(fields); this.webScaffoldAnnotationValues = webScaffoldAnnotationValues; this.formBackingType = webScaffoldAnnotationValues.getFormBackingObject(); this.relatedDomainTypes = relatedDomainTypes; entityName = uncapitalize(formBackingType.getSimpleTypeName()); formBackingTypeMetadata = relatedDomainTypes.get(formBackingType); Assert.notNull(formBackingTypeMetadata, "Form backing type metadata required"); formBackingTypePersistenceMetadata = formBackingTypeMetadata.getPersistenceDetails(); Assert.notNull(formBackingTypePersistenceMetadata, "Persistence metadata required for form backing type"); Assert.notNull(webScaffoldAnnotationValues.getPath(), "Path is not specified in the @RooWebScaffold annotation for '" + webScaffoldAnnotationValues.getGovernorTypeDetails().getName() + "'"); if (webScaffoldAnnotationValues.getPath().startsWith("/")) { controllerPath = webScaffoldAnnotationValues.getPath(); } else { controllerPath = "/" + webScaffoldAnnotationValues.getPath(); } } public Document getListDocument() { DocumentBuilder builder = XmlUtils.getDocumentBuilder(); Document document = builder.newDocument(); // Add document namespaces Element div = new XmlElementBuilder("div", document).addAttribute("xmlns:page", "urn:jsptagdir:/WEB-INF/tags/form").addAttribute("xmlns:table", "urn:jsptagdir:/WEB-INF/tags/form/fields").addAttribute("xmlns:jsp", "http://java.sun.com/JSP/Page").addAttribute("version", "2.0").addChild(new XmlElementBuilder("jsp:directive.page", document).addAttribute("contentType", "text/html;charset=UTF-8").build()).addChild(new XmlElementBuilder("jsp:output", document).addAttribute("omit-xml-declaration", "yes").build()).build(); document.appendChild(div); Element fieldTable = new XmlElementBuilder("table:table", document).addAttribute("id", XmlUtils.convertId("l:" + formBackingType.getFullyQualifiedTypeName())).addAttribute("data", "${" + formBackingTypeMetadata.getPlural().toLowerCase() + "}").addAttribute("path", controllerPath).build(); if (!webScaffoldAnnotationValues.isUpdate()) { fieldTable.setAttribute("update", "false"); } if (!webScaffoldAnnotationValues.isDelete()) { fieldTable.setAttribute("delete", "false"); } if (!formBackingTypePersistenceMetadata.getIdentifierField().getFieldName().getSymbolName().equals("id")) { fieldTable.setAttribute("typeIdFieldName", formBackingTypePersistenceMetadata.getIdentifierField().getFieldName().getSymbolName()); } fieldTable.setAttribute("z", XmlRoundTripUtils.calculateUniqueKeyFor(fieldTable)); int fieldCounter = 0; for (FieldMetadata field : fields) { if (++fieldCounter < 7) { Element columnElement = new XmlElementBuilder("table:column", document).addAttribute("id", XmlUtils.convertId("c:" + formBackingType.getFullyQualifiedTypeName() + "." + field.getFieldName().getSymbolName())).addAttribute("property", uncapitalize(field.getFieldName().getSymbolName())).build(); String fieldName = uncapitalize(field.getFieldName().getSymbolName()); if (field.getFieldType().equals(DATE)) { columnElement.setAttribute("date", "true"); columnElement.setAttribute("dateTimePattern", "${" + entityName + "_" + fieldName.toLowerCase() + "_date_format}"); } else if (field.getFieldType().equals(CALENDAR)) { columnElement.setAttribute("calendar", "true"); columnElement.setAttribute("dateTimePattern", "${" + entityName + "_" + fieldName.toLowerCase() + "_date_format}"); } else if (field.getFieldType().isCommonCollectionType() && field.getCustomData().get(CustomDataKeys.ONE_TO_MANY_FIELD) != null) { continue; } columnElement.setAttribute("z", XmlRoundTripUtils.calculateUniqueKeyFor(columnElement)); fieldTable.appendChild(columnElement); } } // Create page:list element Element pageList = new XmlElementBuilder("page:list", document).addAttribute("id", XmlUtils.convertId("pl:" + formBackingType.getFullyQualifiedTypeName())).addAttribute("items", "${" + formBackingTypeMetadata.getPlural().toLowerCase() + "}").addChild(fieldTable).build(); pageList.setAttribute("z", XmlRoundTripUtils.calculateUniqueKeyFor(pageList)); div.appendChild(pageList); return document; } public Document getShowDocument() { DocumentBuilder builder = XmlUtils.getDocumentBuilder(); Document document = builder.newDocument(); // Add document namespaces Element div = (Element) document.appendChild(new XmlElementBuilder("div", document).addAttribute("xmlns:page", "urn:jsptagdir:/WEB-INF/tags/form").addAttribute("xmlns:field", "urn:jsptagdir:/WEB-INF/tags/form/fields").addAttribute("xmlns:jsp", "http://java.sun.com/JSP/Page").addAttribute("version", "2.0").addChild(new XmlElementBuilder("jsp:directive.page", document).addAttribute("contentType", "text/html;charset=UTF-8").build()).addChild(new XmlElementBuilder("jsp:output", document).addAttribute("omit-xml-declaration", "yes").build()).build()); Element pageShow = new XmlElementBuilder("page:show", document).addAttribute("id", XmlUtils.convertId("ps:" + formBackingType.getFullyQualifiedTypeName())).addAttribute("object", "${" + entityName.toLowerCase() + "}").addAttribute("path", controllerPath).build(); if (!webScaffoldAnnotationValues.isCreate()) { pageShow.setAttribute("create", "false"); } if (!webScaffoldAnnotationValues.isUpdate()) { pageShow.setAttribute("update", "false"); } if (!webScaffoldAnnotationValues.isDelete()) { pageShow.setAttribute("delete", "false"); } pageShow.setAttribute("z", XmlRoundTripUtils.calculateUniqueKeyFor(pageShow)); // Add field:display elements for each field for (FieldMetadata field : fields) { // Ignoring java.util.Map field types (see ROO-194) if (field.getFieldType().equals(new JavaType(Map.class.getName()))) { continue; } String fieldName = uncapitalize(field.getFieldName().getSymbolName()); Element fieldDisplay = new XmlElementBuilder("field:display", document).addAttribute("id", XmlUtils.convertId("s:" + formBackingType.getFullyQualifiedTypeName() + "." + field.getFieldName().getSymbolName())).addAttribute("object", "${" + entityName.toLowerCase() + "}").addAttribute("field", fieldName).build(); if (field.getFieldType().equals(DATE)) { fieldDisplay.setAttribute("date", "true"); fieldDisplay.setAttribute("dateTimePattern", "${" + entityName + "_" + fieldName.toLowerCase() + "_date_format}"); } else if (field.getFieldType().equals(CALENDAR)) { fieldDisplay.setAttribute("calendar", "true"); fieldDisplay.setAttribute("dateTimePattern", "${" + entityName + "_" + fieldName.toLowerCase() + "_date_format}"); } else if (field.getFieldType().isCommonCollectionType() && field.getCustomData().get(CustomDataKeys.ONE_TO_MANY_FIELD) != null) { continue; } fieldDisplay.setAttribute("z", XmlRoundTripUtils.calculateUniqueKeyFor(fieldDisplay)); pageShow.appendChild(fieldDisplay); } div.appendChild(pageShow); return document; } public Document getCreateDocument() { DocumentBuilder builder = XmlUtils.getDocumentBuilder(); Document document = builder.newDocument(); // Add document namespaces Element div = (Element) document.appendChild(new XmlElementBuilder("div", document).addAttribute("xmlns:form", "urn:jsptagdir:/WEB-INF/tags/form").addAttribute("xmlns:field", "urn:jsptagdir:/WEB-INF/tags/form/fields").addAttribute("xmlns:jsp", "http: // Add form create element Element formCreate = new XmlElementBuilder("form:create", document).addAttribute("id", XmlUtils.convertId("fc:" + formBackingType.getFullyQualifiedTypeName())).addAttribute("modelAttribute", entityName).addAttribute("path", controllerPath).addAttribute("render", "${empty dependencies}").build(); if (!controllerPath.equalsIgnoreCase(formBackingType.getSimpleTypeName())) { formCreate.setAttribute("path", controllerPath); } final List<FieldMetadata> formFields = new ArrayList<FieldMetadata>(); final List<FieldMetadata> fieldCopy = new ArrayList<FieldMetadata>(fields); // Handle Roo identifiers if (!formBackingTypePersistenceMetadata.getRooIdentifierFields().isEmpty()) { final String identifierFieldName = formBackingTypePersistenceMetadata.getIdentifierField().getFieldName().getSymbolName(); formCreate.setAttribute("compositePkField", identifierFieldName); for (FieldMetadata embeddedField : formBackingTypePersistenceMetadata.getRooIdentifierFields()) { FieldMetadataBuilder fieldBuilder = new FieldMetadataBuilder(embeddedField); fieldBuilder.setFieldName(new JavaSymbolName(identifierFieldName + "." + embeddedField.getFieldName().getSymbolName())); for (int i = 0; i < fieldCopy.size(); i++) { // Make sure form fields are not presented twice. if (fieldCopy.get(i).getFieldName().equals(embeddedField.getFieldName())) { fieldCopy.remove(i); break; } } formFields.add(fieldBuilder.build()); } } formFields.addAll(fieldCopy); createFieldsForCreateAndUpdate(formFields, document, formCreate, true); formCreate.setAttribute("z", XmlRoundTripUtils.calculateUniqueKeyFor(formCreate)); Element dependency = new XmlElementBuilder("form:dependency", document).addAttribute("id", XmlUtils.convertId("d:" + formBackingType.getFullyQualifiedTypeName())).addAttribute("render", "${not empty dependencies}").addAttribute("dependencies", "${dependencies}").build(); dependency.setAttribute("z", XmlRoundTripUtils.calculateUniqueKeyFor(dependency)); div.appendChild(formCreate); div.appendChild(dependency); return document; } public Document getUpdateDocument() { DocumentBuilder builder = XmlUtils.getDocumentBuilder(); Document document = builder.newDocument(); // Add document namespaces Element div = (Element) document.appendChild(new XmlElementBuilder("div", document).addAttribute("xmlns:form", "urn:jsptagdir:/WEB-INF/tags/form").addAttribute("xmlns:field", "urn:jsptagdir:/WEB-INF/tags/form/fields").addAttribute("xmlns:jsp", "http://java.sun.com/JSP/Page").addAttribute("version", "2.0").addChild(new XmlElementBuilder("jsp:directive.page", document).addAttribute("contentType", "text/html;charset=UTF-8").build()).addChild(new XmlElementBuilder("jsp:output", document).addAttribute("omit-xml-declaration", "yes").build()).build()); // Add form update element Element formUpdate = new XmlElementBuilder("form:update", document).addAttribute("id", XmlUtils.convertId("fu:" + formBackingType.getFullyQualifiedTypeName())).addAttribute("modelAttribute", entityName).build(); if (!controllerPath.equalsIgnoreCase(formBackingType.getSimpleTypeName())) { formUpdate.setAttribute("path", controllerPath); } if (!"id".equals(formBackingTypePersistenceMetadata.getIdentifierField().getFieldName().getSymbolName())) { formUpdate.setAttribute("idField", formBackingTypePersistenceMetadata.getIdentifierField().getFieldName().getSymbolName()); } final MethodMetadata versionAccessorMethod = formBackingTypePersistenceMetadata.getVersionAccessorMethod(); if (versionAccessorMethod == null) { formUpdate.setAttribute("versionField", "none"); } else { final String methodName = versionAccessorMethod.getMethodName().getSymbolName(); formUpdate.setAttribute("versionField", methodName.substring("get".length())); } // Filter out embedded ID fields as they represent the composite PK which is not to be updated. final List<FieldMetadata> fieldCopy = new ArrayList<FieldMetadata>(fields); for (FieldMetadata embeddedField : formBackingTypePersistenceMetadata.getRooIdentifierFields()) { for (int i = 0; i < fieldCopy.size(); i++) { // Make sure form fields are not presented twice. if (fieldCopy.get(i).getFieldName().equals(embeddedField.getFieldName())) { fieldCopy.remove(i); } } } createFieldsForCreateAndUpdate(fieldCopy, document, formUpdate, false); formUpdate.setAttribute("z", XmlRoundTripUtils.calculateUniqueKeyFor(formUpdate)); div.appendChild(formUpdate); return document; } public Document getFinderDocument(final FinderMetadataDetails finderMetadataDetails) { DocumentBuilder builder = XmlUtils.getDocumentBuilder(); Document document = builder.newDocument(); // Add document namespaces Element div = (Element) document.appendChild(new XmlElementBuilder("div", document).addAttribute("xmlns:form", "urn:jsptagdir:/WEB-INF/tags/form").addAttribute("xmlns:field", "urn:jsptagdir:/WEB-INF/tags/form/fields").addAttribute("xmlns:jsp", "http://java.sun.com/JSP/Page").addAttribute("version", "2.0").addChild(new XmlElementBuilder("jsp:directive.page", document).addAttribute("contentType", "text/html;charset=UTF-8").build()).addChild(new XmlElementBuilder("jsp:output", document).addAttribute("omit-xml-declaration", "yes").build()).build()); Element formFind = new XmlElementBuilder("form:find", document).addAttribute("id", XmlUtils.convertId("ff:" + formBackingType.getFullyQualifiedTypeName())).addAttribute("path", controllerPath).addAttribute("finderName", finderMetadataDetails.getFinderMethodMetadata().getMethodName().getSymbolName().replace("find" + formBackingTypeMetadata.getPlural(), "")).build(); formFind.setAttribute("z", XmlRoundTripUtils.calculateUniqueKeyFor(formFind)); div.appendChild(formFind); for (FieldMetadata field: finderMetadataDetails.getFinderMethodParamFields()) { JavaType type = field.getFieldType(); JavaSymbolName paramName = field.getFieldName(); // Ignoring java.util.Map field types (see ROO-194) if (type.equals(new JavaType(Map.class.getName()))) { continue; } Assert.notNull(paramName, "Could not find field '" + paramName + "' in '" + type.getFullyQualifiedTypeName() + "'"); Element fieldElement = null; JavaTypeMetadataDetails typeMetadataHolder = relatedDomainTypes.get(getJavaTypeForField(field)); if (type.isCommonCollectionType() && relatedDomainTypes.containsKey(getJavaTypeForField(field))) { JavaTypeMetadataDetails collectionTypeMetadataHolder = relatedDomainTypes.get(getJavaTypeForField(field)); JavaTypePersistenceMetadataDetails typePersistenceMetadataHolder = collectionTypeMetadataHolder.getPersistenceDetails(); if (typePersistenceMetadataHolder != null) { fieldElement = new XmlElementBuilder("field:select", document).addAttribute("required", "true").addAttribute("items", "${" + collectionTypeMetadataHolder.getPlural().toLowerCase() + "}").addAttribute("itemValue", typePersistenceMetadataHolder.getIdentifierField().getFieldName().getSymbolName()).addAttribute("path", "/" + getPathForType(getJavaTypeForField(field))).build(); if (field.getCustomData().keySet().contains(CustomDataKeys.MANY_TO_MANY_FIELD)) { fieldElement.setAttribute("multiple", "true"); } } } else if (typeMetadataHolder != null && typeMetadataHolder.isEnumType() && field.getCustomData().keySet().contains(CustomDataKeys.ENUMERATED_FIELD)) { fieldElement = new XmlElementBuilder("field:select", document).addAttribute("required", "true").addAttribute("items", "${" + typeMetadataHolder.getPlural().toLowerCase() + "}").addAttribute("path", "/" + getPathForType(type)).build(); } else if (type.equals(BOOLEAN_OBJECT) || type.equals(BOOLEAN_PRIMITIVE)) { fieldElement = document.createElement("field:checkbox"); } else if (typeMetadataHolder != null && typeMetadataHolder.isApplicationType()) { JavaTypePersistenceMetadataDetails typePersistenceMetadataHolder = typeMetadataHolder.getPersistenceDetails(); if (typePersistenceMetadataHolder != null) { fieldElement = new XmlElementBuilder("field:select", document).addAttribute("required", "true").addAttribute("items", "${" + typeMetadataHolder.getPlural().toLowerCase() + "}").addAttribute("itemValue", typePersistenceMetadataHolder.getIdentifierField().getFieldName().getSymbolName()).addAttribute("path", "/" + getPathForType(type)).build(); } } else if (type.equals(DATE) || type.equals(CALENDAR)) { fieldElement = new XmlElementBuilder("field:datetime", document).addAttribute("required", "true").addAttribute("dateTimePattern", "${" + entityName + "_" + paramName.getSymbolName().toLowerCase() + "_date_format}").build(); } if (fieldElement == null) { fieldElement = new XmlElementBuilder("field:input", document).addAttribute("required", "true").build(); } addCommonAttributes(field, fieldElement); fieldElement.setAttribute("disableFormBinding", "true"); fieldElement.setAttribute("field", paramName.getSymbolName()); fieldElement.setAttribute("id", XmlUtils.convertId("f:" + formBackingType.getFullyQualifiedTypeName() + "." + paramName)); fieldElement.setAttribute("z", XmlRoundTripUtils.calculateUniqueKeyFor(fieldElement)); formFind.appendChild(fieldElement); } DomUtils.removeTextNodes(document); return document; } private void createFieldsForCreateAndUpdate(final List<FieldMetadata> formFields, final Document document, final Element root, final boolean isCreate) { for (FieldMetadata field : formFields) { String fieldName = field.getFieldName().getSymbolName(); JavaType fieldType = field.getFieldType(); AnnotationMetadata annotationMetadata; // Ignoring java.util.Map field types (see ROO-194) if (fieldType.equals(new JavaType(Map.class.getName()))) { continue; } // Fields contained in the embedded Id type have been added separately to the field list if (field.getCustomData().keySet().contains(CustomDataKeys.EMBEDDED_ID_FIELD)) { continue; } fieldType = getJavaTypeForField(field); JavaTypeMetadataDetails typeMetadataHolder = relatedDomainTypes.get(fieldType); JavaTypePersistenceMetadataDetails typePersistenceMetadataHolder = null; if (typeMetadataHolder != null) { typePersistenceMetadataHolder = typeMetadataHolder.getPersistenceDetails(); } Element fieldElement = null; if (fieldType.getFullyQualifiedTypeName().equals(Boolean.class.getName()) || fieldType.getFullyQualifiedTypeName().equals(boolean.class.getName())) { fieldElement = document.createElement("field:checkbox"); // Handle enum fields } else if (typeMetadataHolder != null && typeMetadataHolder.isEnumType()) { fieldElement = new XmlElementBuilder("field:select", document).addAttribute("items", "${" + typeMetadataHolder.getPlural().toLowerCase() + "}").addAttribute("path", getPathForType(fieldType)).build(); } else if (field.getCustomData().keySet().contains(CustomDataKeys.ONE_TO_MANY_FIELD)) { // OneToMany relationships are managed from the 'many' side of the relationship, therefore we provide a link to the relevant form // the link URL is determined as a best effort attempt following Roo REST conventions, this link might be wrong if custom paths are used // if custom paths are used the developer can adjust the path attribute in the field:reference tag accordingly if (typePersistenceMetadataHolder != null) { fieldElement = new XmlElementBuilder("field:simple", document).addAttribute("messageCode", "entity_reference_not_managed").addAttribute("messageCodeAttribute", new JavaSymbolName(fieldType.getSimpleTypeName()).getReadableSymbolName()).build(); } else { continue; } } else if (field.getCustomData().keySet().contains(CustomDataKeys.MANY_TO_ONE_FIELD) || field.getCustomData().keySet().contains(CustomDataKeys.MANY_TO_MANY_FIELD) || field.getCustomData().keySet().contains(CustomDataKeys.ONE_TO_ONE_FIELD)) { JavaType referenceType = getJavaTypeForField(field); JavaTypeMetadataDetails referenceTypeMetadata = relatedDomainTypes.get(referenceType); if (referenceType != null/** fix for ROO-1888 --> **/ && referenceTypeMetadata != null && referenceTypeMetadata.isApplicationType() && typePersistenceMetadataHolder != null) { fieldElement = new XmlElementBuilder("field:select", document).addAttribute("items", "${" + referenceTypeMetadata.getPlural().toLowerCase() + "}").addAttribute("itemValue", typePersistenceMetadataHolder.getIdentifierField().getFieldName().getSymbolName()).addAttribute("path", "/" + getPathForType(getJavaTypeForField(field))).build(); if (field.getCustomData().keySet().contains(CustomDataKeys.MANY_TO_MANY_FIELD)) { fieldElement.setAttribute("multiple", "true"); } } } else if (fieldType.equals(DATE) || fieldType.equals(CALENDAR)) { // Only include the date picker for styles supported by Dojo (SMALL & MEDIUM) fieldElement = new XmlElementBuilder("field:datetime", document).addAttribute("dateTimePattern", "${" + entityName + "_" + fieldName.toLowerCase() + "_date_format}").build(); if (null != MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), FUTURE)) { fieldElement.setAttribute("future", "true"); } else if (null != MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), PAST)) { fieldElement.setAttribute("past", "true"); } } else if (field.getCustomData().keySet().contains(CustomDataKeys.LOB_FIELD)) { fieldElement = new XmlElementBuilder("field:textarea", document).build(); } if ((annotationMetadata = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), SIZE)) != null) { AnnotationAttributeValue<?> max = annotationMetadata.getAttribute(new JavaSymbolName("max")); if (max != null) { int maxValue = (Integer) max.getValue(); if (fieldElement == null && maxValue > 30) { fieldElement = new XmlElementBuilder("field:textarea", document).build(); } } } // Use a default input field if no other criteria apply if (fieldElement == null) { fieldElement = document.createElement("field:input"); } addCommonAttributes(field, fieldElement); fieldElement.setAttribute("field", fieldName); fieldElement.setAttribute("id", XmlUtils.convertId("c:" + formBackingType.getFullyQualifiedTypeName() + "." + field.getFieldName().getSymbolName())); fieldElement.setAttribute("z", XmlRoundTripUtils.calculateUniqueKeyFor(fieldElement)); root.appendChild(fieldElement); } } private JavaType getJavaTypeForField(final FieldMetadata field) { if (field.getFieldType().isCommonCollectionType()) { // Currently there is no scaffolding available for Maps (see ROO-194) if (field.getFieldType().equals(new JavaType(Map.class.getName()))) { return null; } List<JavaType> parameters = field.getFieldType().getParameters(); if (parameters.isEmpty()) { throw new IllegalStateException("Unable to determine the parameter type for the " + field.getFieldName().getSymbolName() + " field in " + formBackingType.getSimpleTypeName()); } return parameters.get(0); } return field.getFieldType(); } private String getPathForType(final JavaType type) { JavaTypeMetadataDetails javaTypeMetadataHolder = relatedDomainTypes.get(type); Assert.notNull(javaTypeMetadataHolder, "Unable to obtain metadata for type " + type.getFullyQualifiedTypeName()); return javaTypeMetadataHolder.getControllerPath(); } private void addCommonAttributes(final FieldMetadata field, final Element fieldElement) { AnnotationMetadata annotationMetadata; if (field.getFieldType().equals(INT_OBJECT) || field.getFieldType().getFullyQualifiedTypeName().equals(int.class.getName()) || field.getFieldType().equals(SHORT_OBJECT) || field.getFieldType().getFullyQualifiedTypeName().equals(short.class.getName()) || field.getFieldType().equals(LONG_OBJECT) || field.getFieldType().getFullyQualifiedTypeName().equals(long.class.getName()) || field.getFieldType().equals(BIG_INTEGER)) { fieldElement.setAttribute("validationMessageCode", "field_invalid_integer"); } else if (isEmailField(field)) { fieldElement.setAttribute("validationMessageCode", "field_invalid_email"); } else if (field.getFieldType().equals(DOUBLE_OBJECT) || field.getFieldType().getFullyQualifiedTypeName().equals(double.class.getName()) || field.getFieldType().equals(FLOAT_OBJECT) || field.getFieldType().getFullyQualifiedTypeName().equals(float.class.getName()) || field.getFieldType().equals(BIG_DECIMAL)) { fieldElement.setAttribute("validationMessageCode", "field_invalid_number"); } if ("field:input".equals(fieldElement.getTagName()) && null != (annotationMetadata = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), MIN))) { AnnotationAttributeValue<?> min = annotationMetadata.getAttribute(VALUE); if (min != null) { fieldElement.setAttribute("min", min.getValue().toString()); fieldElement.setAttribute("required", "true"); } } if ("field:input".equals(fieldElement.getTagName()) && null != (annotationMetadata = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), MAX)) && !"field:textarea".equals(fieldElement.getTagName())) { AnnotationAttributeValue<?> maxA = annotationMetadata.getAttribute(VALUE); if (maxA != null) { fieldElement.setAttribute("max", maxA.getValue().toString()); } } if ("field:input".equals(fieldElement.getTagName()) && null != (annotationMetadata = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), DECIMAL_MIN)) && !"field:textarea".equals(fieldElement.getTagName())) { AnnotationAttributeValue<?> decimalMin = annotationMetadata.getAttribute(VALUE); if (decimalMin != null) { fieldElement.setAttribute("decimalMin", decimalMin.getValue().toString()); fieldElement.setAttribute("required", "true"); } } if ("field:input".equals(fieldElement.getTagName()) && null != (annotationMetadata = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), DECIMAL_MAX))) { AnnotationAttributeValue<?> decimalMax = annotationMetadata.getAttribute(VALUE); if (decimalMax != null) { fieldElement.setAttribute("decimalMax", decimalMax.getValue().toString()); } } if (null != (annotationMetadata = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), PATTERN))) { AnnotationAttributeValue<?> regexp = annotationMetadata.getAttribute(new JavaSymbolName("regexp")); if (regexp != null) { fieldElement.setAttribute("validationRegex", regexp.getValue().toString()); } } if ("field:input".equals(fieldElement.getTagName()) && null != (annotationMetadata = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), SIZE))) { AnnotationAttributeValue<?> max = annotationMetadata.getAttribute(new JavaSymbolName("max")); if (max != null) { fieldElement.setAttribute("max", max.getValue().toString()); } AnnotationAttributeValue<?> min = annotationMetadata.getAttribute(new JavaSymbolName("min")); if (min != null) { fieldElement.setAttribute("min", min.getValue().toString()); fieldElement.setAttribute("required", "true"); } } if (null != (annotationMetadata = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), NOT_NULL))) { String tagName = fieldElement.getTagName(); if (tagName.endsWith("textarea") || tagName.endsWith("input") || tagName.endsWith("datetime") || tagName.endsWith("textarea") || tagName.endsWith("select") || tagName.endsWith("reference")) { fieldElement.setAttribute("required", "true"); } } if (field.getCustomData().keySet().contains(CustomDataKeys.COLUMN_FIELD)) { @SuppressWarnings("unchecked") Map<String, Object> values = (Map<String, Object>) field.getCustomData().get(CustomDataKeys.COLUMN_FIELD); if (values.keySet().contains("nullable") && ((Boolean) values.get("nullable")) == false) { fieldElement.setAttribute("required", "true"); } } // Disable form binding for nested fields (mainly PKs) if (field.getFieldName().getSymbolName().contains(".")) { fieldElement.setAttribute("disableFormBinding", "true"); } } private boolean isEmailField(final FieldMetadata field) { return STRING.equals(field.getFieldType()) && uncapitalize(field.getFieldName().getSymbolName()).contains("email"); } private String uncapitalize(final String term) { // [ROO-1790] this is needed to adhere to the JavaBean naming // conventions (see JavaBean spec section 8.8) return Introspector.decapitalize(StringUtils.capitalize(term)); } }
// File path shortening code adapted from: package org.scijava.util; import java.io.File; import java.io.FileInputStream; import java.io.FilenameFilter; import java.io.IOException; import java.net.JarURLConnection; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Useful methods for working with file paths. * * @author Johannes Schindelin * @author Grant Harris */ public final class FileUtils { public static final int DEFAULT_SHORTENER_THRESHOLD = 4; public static final String SHORTENER_BACKSLASH_REGEX = "\\\\"; public static final String SHORTENER_SLASH_REGEX = "/"; public static final String SHORTENER_BACKSLASH = "\\"; public static final String SHORTENER_SLASH = "/"; public static final String SHORTENER_ELLIPSE = "..."; private FileUtils() { // prevent instantiation of utility class } /** * Gets the absolute path to the given file, with the directory separator * standardized to forward slash, like most platforms use. * * @param file The file whose path will be obtained and standardized. * @return The file's standardized absolute path. */ public static String getPath(final File file) { final String path = file.getAbsolutePath(); final String slash = System.getProperty("file.separator"); return getPath(path, slash); } /** * Gets a standardized path based on the given one, with the directory * separator standardized from the specific separator to forward slash, like * most platforms use. * * @param path The path to standardize. * @param separator The directory separator to be standardized. * @return The standardized path. */ public static String getPath(final String path, final String separator) { // NB: Standardize directory separator (i.e., avoid Windows nonsense!). return path.replaceAll(Pattern.quote(separator), "/"); } /** * Extracts the file extension from a file. * * @param file the file object * @return the file extension (excluding the dot), or the empty string when * the file name does not contain dots */ public static String getExtension(final File file) { final String name = file.getName(); final int dot = name.lastIndexOf('.'); if (dot < 0) return ""; return name.substring(dot + 1); } /** * Extracts the file extension from a file path. * * @param path the path to the file (relative or absolute) * @return the file extension (excluding the dot), or the empty string when * the file name does not contain dots */ public static String getExtension(final String path) { return getExtension(new File(path)); } /** * A regular expression to match filenames containing version information. * <p> * This is kept synchronized with {@code imagej.updater.core.FileObject}. * </p> */ private final static Pattern versionPattern = Pattern.compile("(.+?)(-\\d+(\\.\\d+|\\d{7})+[a-z]?\\d?(-[A-Za-z0-9.]+|\\.GA)*)?(\\.jar(-[a-z]*)?)"); /** * Returns the {@link Matcher} object dissecting a versioned file name. * * @param filename the file name * @return the {@link Matcher} object */ public static Matcher matchVersionedFilename(String filename) { return versionPattern.matcher(filename); } /** * Lists all versions of a given (possibly versioned) file name. * * @param directory the directory to scan * @param filename the file name to use * @return the list of matches */ public static File[] getAllVersions(final File directory, final String filename) { final Matcher matcher = matchVersionedFilename(filename); if (!matcher.matches()) { final File file = new File(directory, filename); return file.exists() ? new File[] { file } : null; } final String baseName = matcher.group(1); return directory.listFiles(new FilenameFilter() { @Override public boolean accept(final File dir, final String name) { if (!name.startsWith(baseName)) return false; final Matcher matcher2 = matchVersionedFilename(name); return matcher2.matches() && baseName.equals(matcher2.group(1)); } }); } public static File urlToFile(final URL url) { return urlToFile(url.toString()); } public static File urlToFile(final String url) { String path = url; if (path.startsWith("jar:")) { // remove "jar:" prefix and "!/" suffix final int index = path.indexOf("!/"); path = path.substring(4, index); } try { return new File(new URL(path).toURI()); } catch (final MalformedURLException e) { // NB: URL is not completely well-formed. } catch (final URISyntaxException e) { // NB: URL is not completely well-formed. } if (path.startsWith("file:")) { // pass through the URL as-is, minus "file:" prefix path = path.substring(5); return new File(path); } throw new IllegalArgumentException("Invalid URL: " + url); } /** * Shortens the path to a maximum of 4 path elements. * * @param path the path to the file (relative or absolute) * @return shortened path */ public static String shortenPath(final String path) { return shortenPath(path, DEFAULT_SHORTENER_THRESHOLD); } /** * Shortens the path based on the given maximum number of path elements. E.g., * "C:/1/2/test.txt" returns "C:/1/.../test.txt" if threshold is 1. * * @param path the path to the file (relative or absolute) * @param threshold the number of directories to keep unshortened * @return shortened path */ public static String shortenPath(final String path, final int threshold) { String regex = SHORTENER_BACKSLASH_REGEX; String sep = SHORTENER_BACKSLASH; if (path.indexOf("/") > 0) { regex = SHORTENER_SLASH_REGEX; sep = SHORTENER_SLASH; } String pathtemp[] = path.split(regex); // remove empty elements int elem = 0; { final String newtemp[] = new String[pathtemp.length]; int j = 0; for (int i = 0; i < pathtemp.length; i++) { if (!pathtemp[i].equals("")) { newtemp[j++] = pathtemp[i]; elem++; } } pathtemp = newtemp; } if (elem > threshold) { final StringBuilder sb = new StringBuilder(); int index = 0; // drive or protocol final int pos2dots = path.indexOf(":"); if (pos2dots > 0) { // case c:\ c:/ etc. sb.append(path.substring(0, pos2dots + 2)); index++; if (path.indexOf(":/") > 0 && pathtemp[0].length() > 2) { sb.append(SHORTENER_SLASH); } } else { final boolean isUNC = path.substring(0, 2).equals(SHORTENER_BACKSLASH_REGEX); if (isUNC) { sb.append(SHORTENER_BACKSLASH).append(SHORTENER_BACKSLASH); } } for (; index <= threshold; index++) { sb.append(pathtemp[index]).append(sep); } if (index == (elem - 1)) { sb.append(pathtemp[elem - 1]); } else { sb.append(SHORTENER_ELLIPSE).append(sep).append(pathtemp[elem - 1]); } return sb.toString(); } return path; } /** * Compacts a path into a given number of characters. The result is similar to * the Win32 API PathCompactPathExA. * * @param path the path to the file (relative or absolute) * @param limit the number of characters to which the path should be limited * @return shortened path */ public static String limitPath(final String path, final int limit) { if (path.length() <= limit) return path; final char shortPathArray[] = new char[limit]; final char pathArray[] = path.toCharArray(); final char ellipseArray[] = SHORTENER_ELLIPSE.toCharArray(); final int pathindex = pathArray.length - 1; final int shortpathindex = limit - 1; // fill the array from the end int i = 0; for (; i < limit; i++) { if (pathArray[pathindex - i] != '/' && pathArray[pathindex - i] != '\\') { shortPathArray[shortpathindex - i] = pathArray[pathindex - i]; } else { break; } } // check how much space is left final int free = limit - i; if (free < SHORTENER_ELLIPSE.length()) { // fill the beginning with ellipse for (int j = 0; j < ellipseArray.length; j++) { shortPathArray[j] = ellipseArray[j]; } } else { // fill the beginning with path and leave room for the ellipse int j = 0; for (; j + ellipseArray.length < free; j++) { shortPathArray[j] = pathArray[j]; } // ... add the ellipse for (int k = 0; j + k < free; k++) { shortPathArray[j + k] = ellipseArray[k]; } } return new String(shortPathArray); } /** * Creates a temporary directory. * <p> * Since there is no atomic operation to do that, we create a temporary file, * delete it and create a directory in its place. To avoid race conditions, we * use the optimistic approach: if the directory cannot be created, we try to * obtain a new temporary file rather than erroring out. * </p> * <p> * It is the caller's responsibility to make sure that the directory is * deleted. * </p> * * @param prefix The prefix string to be used in generating the file's name; * see {@link File#createTempFile(String, String, File)} * @param suffix The suffix string to be used in generating the file's name; * see {@link File#createTempFile(String, String, File)} * @return An abstract pathname denoting a newly-created empty directory * @throws IOException */ public static File createTemporaryDirectory(final String prefix, final String suffix) throws IOException { return createTemporaryDirectory(prefix, suffix, null); } /** * Creates a temporary directory. * <p> * Since there is no atomic operation to do that, we create a temporary file, * delete it and create a directory in its place. To avoid race conditions, we * use the optimistic approach: if the directory cannot be created, we try to * obtain a new temporary file rather than erroring out. * </p> * <p> * It is the caller's responsibility to make sure that the directory is * deleted. * </p> * * @param prefix The prefix string to be used in generating the file's name; * see {@link File#createTempFile(String, String, File)} * @param suffix The suffix string to be used in generating the file's name; * see {@link File#createTempFile(String, String, File)} * @param directory The directory in which the file is to be created, or null * if the default temporary-file directory is to be used * @return: An abstract pathname denoting a newly-created empty directory * @throws IOException */ public static File createTemporaryDirectory(final String prefix, final String suffix, final File directory) throws IOException { for (int counter = 0; counter < 10; counter++) { final File file = File.createTempFile(prefix, suffix, directory); if (!file.delete()) { throw new IOException("Could not delete file " + file); } // in case of a race condition, just try again if (file.mkdir()) return file; } throw new IOException( "Could not create temporary directory (too many race conditions?)"); } /** * Delete a directory recursively * * @param directory * @return whether it succeeded (see also {@link File#delete()}) */ public static boolean deleteRecursively(final File directory) { if (directory == null) { return true; } final File[] list = directory.listFiles(); if (list == null) { return true; } for (final File file : list) { if (file.isFile()) { if (!file.delete()) { return false; } } else if (file.isDirectory()) { if (!deleteRecursively(file)) { return false; } } } return directory.delete(); } /** * Lists all contents of the referenced directory. * * @author Johannes Schindelin */ public static Collection<URL> listContents(final URL directory) { final Collection<URL> result = new ArrayList<URL>(); return appendContents(result, directory); } /** * Add contents from the referenced directory to an existing collection. * * @author Johannes Schindelin */ public static Collection<URL> appendContents(final Collection<URL> result, final URL directory) { if (directory == null) return result; // nothing to append final String protocol = directory.getProtocol(); if (protocol.equals("file")) { File dir; try { dir = new File(directory.toURI()); } catch (Exception e) { dir = new File(directory.getPath()); } final File[] list = dir.listFiles(); if (list != null) { for (final File file : list) { try { if (file.isFile()) { result.add(file.toURI().toURL()); } else if (file.isDirectory()) { appendContents(result, file.toURI().toURL()); } } catch (MalformedURLException e) { e.printStackTrace(); } } } } else if (protocol.equals("jar")) { try { final String url = directory.toString(); final int bang = url.indexOf("!/"); if (bang < 0) return result; final String prefix = url.substring(bang + 2); final JarURLConnection connection = (JarURLConnection) new URL(url.substring(0, bang + 2)).openConnection(); final JarFile jar = connection.getJarFile(); for (final JarEntry entry : new IteratorPlus<JarEntry>(jar.entries())) { if (entry.getName().startsWith(prefix)) { result.add(new URL(url.substring(0, bang + 2) + entry.getName())); } } jar.close(); } catch (IOException e) { e.printStackTrace(); } } return result; } }
// File path shortening code adapted from: package org.scijava.util; import java.io.File; import java.io.FileInputStream; import java.io.FilenameFilter; import java.io.IOException; import java.net.JarURLConnection; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Useful methods for working with file paths. * * @author Johannes Schindelin * @author Curtis Rueden * @author Grant Harris */ public final class FileUtils { public static final int DEFAULT_SHORTENER_THRESHOLD = 4; public static final String SHORTENER_BACKSLASH_REGEX = "\\\\"; public static final String SHORTENER_SLASH_REGEX = "/"; public static final String SHORTENER_BACKSLASH = "\\"; public static final String SHORTENER_SLASH = "/"; public static final String SHORTENER_ELLIPSE = "..."; private FileUtils() { // prevent instantiation of utility class } /** * Gets the absolute path to the given file, with the directory separator * standardized to forward slash, like most platforms use. * * @param file The file whose path will be obtained and standardized. * @return The file's standardized absolute path. */ public static String getPath(final File file) { final String path = file.getAbsolutePath(); final String slash = System.getProperty("file.separator"); return getPath(path, slash); } /** * Gets a standardized path based on the given one, with the directory * separator standardized from the specific separator to forward slash, like * most platforms use. * * @param path The path to standardize. * @param separator The directory separator to be standardized. * @return The standardized path. */ public static String getPath(final String path, final String separator) { // NB: Standardize directory separator (i.e., avoid Windows nonsense!). return path.replaceAll(Pattern.quote(separator), "/"); } /** * Extracts the file extension from a file. * * @param file the file object * @return the file extension (excluding the dot), or the empty string when * the file name does not contain dots */ public static String getExtension(final File file) { final String name = file.getName(); final int dot = name.lastIndexOf('.'); if (dot < 0) return ""; return name.substring(dot + 1); } /** * Extracts the file extension from a file path. * * @param path the path to the file (relative or absolute) * @return the file extension (excluding the dot), or the empty string when * the file name does not contain dots */ public static String getExtension(final String path) { return getExtension(new File(path)); } /** * A regular expression to match filenames containing version information. * <p> * This is kept synchronized with {@code imagej.updater.core.FileObject}. * </p> */ private final static Pattern versionPattern = Pattern .compile("(.+?)(-\\d+(\\.\\d+|\\d{7})+[a-z]?\\d?(-[A-Za-z0-9.]+?|\\.GA)*?)?((-(swing|swt|sources|javadoc))?(\\.jar(-[a-z]*)?))"); public static String stripFilenameVersion(final String filename) { final Matcher matcher = versionPattern.matcher(filename); if (!matcher.matches()) return filename; return matcher.group(1) + matcher.group(5); } /** * Lists all versions of a given (possibly versioned) file name. * * @param directory the directory to scan * @param filename the file name to use * @return the list of matches */ public static File[] getAllVersions(final File directory, final String filename) { final Matcher matcher = versionPattern.matcher(filename); if (!matcher.matches()) { final File file = new File(directory, filename); return file.exists() ? new File[] { file } : null; } final String baseName = matcher.group(1); return directory.listFiles(new FilenameFilter() { @Override public boolean accept(final File dir, final String name) { if (!name.startsWith(baseName)) return false; final Matcher matcher2 = versionPattern.matcher(name); return matcher2.matches() && baseName.equals(matcher2.group(1)); } }); } public static File urlToFile(final URL url) { return url == null ? null : urlToFile(url.toString()); } public static File urlToFile(final String url) { String path = url; if (path.startsWith("jar:")) { // remove "jar:" prefix and "!/" suffix final int index = path.indexOf("!/"); path = path.substring(4, index); } try { return new File(new URL(path).toURI()); } catch (final MalformedURLException e) { // NB: URL is not completely well-formed. } catch (final URISyntaxException e) { // NB: URL is not completely well-formed. } if (path.startsWith("file:")) { // pass through the URL as-is, minus "file:" prefix path = path.substring(5); return new File(path); } throw new IllegalArgumentException("Invalid URL: " + url); } /** * Shortens the path to a maximum of 4 path elements. * * @param path the path to the file (relative or absolute) * @return shortened path */ public static String shortenPath(final String path) { return shortenPath(path, DEFAULT_SHORTENER_THRESHOLD); } /** * Shortens the path based on the given maximum number of path elements. E.g., * "C:/1/2/test.txt" returns "C:/1/.../test.txt" if threshold is 1. * * @param path the path to the file (relative or absolute) * @param threshold the number of directories to keep unshortened * @return shortened path */ public static String shortenPath(final String path, final int threshold) { String regex = SHORTENER_BACKSLASH_REGEX; String sep = SHORTENER_BACKSLASH; if (path.indexOf("/") > 0) { regex = SHORTENER_SLASH_REGEX; sep = SHORTENER_SLASH; } String pathtemp[] = path.split(regex); // remove empty elements int elem = 0; { final String newtemp[] = new String[pathtemp.length]; int j = 0; for (int i = 0; i < pathtemp.length; i++) { if (!pathtemp[i].equals("")) { newtemp[j++] = pathtemp[i]; elem++; } } pathtemp = newtemp; } if (elem > threshold) { final StringBuilder sb = new StringBuilder(); int index = 0; // drive or protocol final int pos2dots = path.indexOf(":"); if (pos2dots > 0) { // case c:\ c:/ etc. sb.append(path.substring(0, pos2dots + 2)); index++; if (path.indexOf(":/") > 0 && pathtemp[0].length() > 2) { sb.append(SHORTENER_SLASH); } } else { final boolean isUNC = path.substring(0, 2).equals(SHORTENER_BACKSLASH_REGEX); if (isUNC) { sb.append(SHORTENER_BACKSLASH).append(SHORTENER_BACKSLASH); } } for (; index <= threshold; index++) { sb.append(pathtemp[index]).append(sep); } if (index == (elem - 1)) { sb.append(pathtemp[elem - 1]); } else { sb.append(SHORTENER_ELLIPSE).append(sep).append(pathtemp[elem - 1]); } return sb.toString(); } return path; } /** * Compacts a path into a given number of characters. The result is similar to * the Win32 API PathCompactPathExA. * * @param path the path to the file (relative or absolute) * @param limit the number of characters to which the path should be limited * @return shortened path */ public static String limitPath(final String path, final int limit) { if (path.length() <= limit) return path; final char shortPathArray[] = new char[limit]; final char pathArray[] = path.toCharArray(); final char ellipseArray[] = SHORTENER_ELLIPSE.toCharArray(); final int pathindex = pathArray.length - 1; final int shortpathindex = limit - 1; // fill the array from the end int i = 0; for (; i < limit; i++) { if (pathArray[pathindex - i] != '/' && pathArray[pathindex - i] != '\\') { shortPathArray[shortpathindex - i] = pathArray[pathindex - i]; } else { break; } } // check how much space is left final int free = limit - i; if (free < SHORTENER_ELLIPSE.length()) { // fill the beginning with ellipse for (int j = 0; j < ellipseArray.length; j++) { shortPathArray[j] = ellipseArray[j]; } } else { // fill the beginning with path and leave room for the ellipse int j = 0; for (; j + ellipseArray.length < free; j++) { shortPathArray[j] = pathArray[j]; } // ... add the ellipse for (int k = 0; j + k < free; k++) { shortPathArray[j + k] = ellipseArray[k]; } } return new String(shortPathArray); } /** * Creates a temporary directory. * <p> * Since there is no atomic operation to do that, we create a temporary file, * delete it and create a directory in its place. To avoid race conditions, we * use the optimistic approach: if the directory cannot be created, we try to * obtain a new temporary file rather than erroring out. * </p> * <p> * It is the caller's responsibility to make sure that the directory is * deleted. * </p> * * @param prefix The prefix string to be used in generating the file's name; * see {@link File#createTempFile(String, String, File)} * @param suffix The suffix string to be used in generating the file's name; * see {@link File#createTempFile(String, String, File)} * @return An abstract pathname denoting a newly-created empty directory * @throws IOException */ public static File createTemporaryDirectory(final String prefix, final String suffix) throws IOException { return createTemporaryDirectory(prefix, suffix, null); } /** * Creates a temporary directory. * <p> * Since there is no atomic operation to do that, we create a temporary file, * delete it and create a directory in its place. To avoid race conditions, we * use the optimistic approach: if the directory cannot be created, we try to * obtain a new temporary file rather than erroring out. * </p> * <p> * It is the caller's responsibility to make sure that the directory is * deleted. * </p> * * @param prefix The prefix string to be used in generating the file's name; * see {@link File#createTempFile(String, String, File)} * @param suffix The suffix string to be used in generating the file's name; * see {@link File#createTempFile(String, String, File)} * @param directory The directory in which the file is to be created, or null * if the default temporary-file directory is to be used * @return: An abstract pathname denoting a newly-created empty directory * @throws IOException */ public static File createTemporaryDirectory(final String prefix, final String suffix, final File directory) throws IOException { for (int counter = 0; counter < 10; counter++) { final File file = File.createTempFile(prefix, suffix, directory); if (!file.delete()) { throw new IOException("Could not delete file " + file); } // in case of a race condition, just try again if (file.mkdir()) return file; } throw new IOException( "Could not create temporary directory (too many race conditions?)"); } /** * Deletes a directory recursively. * * @param directory The directory to delete. * @return whether it succeeded (see also {@link File#delete()}) */ public static boolean deleteRecursively(final File directory) { if (directory == null) return true; final File[] list = directory.listFiles(); if (list == null) return true; for (final File file : list) { if (file.isFile()) { if (!file.delete()) return false; } else if (file.isDirectory()) { if (!deleteRecursively(file)) return false; } } return directory.delete(); } /** * Recursively lists the contents of the referenced directory. Directories are * excluded from the result. Supported protocols include {@code file} and * {@code jar}. * * @param directory The directory whose contents should be listed. * @return A collection of {@link URL}s representing the directory's contents. * @see #listContents(URL, boolean, boolean) */ public static Collection<URL> listContents(final URL directory) { return listContents(directory, true, true); } /** * Lists all contents of the referenced directory. Supported protocols include * {@code file} and {@code jar}. * * @param directory The directory whose contents should be listed. * @param recurse Whether to list contents recursively, as opposed to only the * directory's direct contents. * @param filesOnly Whether to exclude directories in the resulting collection * of contents. * @return A collection of {@link URL}s representing the directory's contents. */ public static Collection<URL> listContents(final URL directory, final boolean recurse, final boolean filesOnly) { return appendContents(new ArrayList<URL>(), directory, recurse, filesOnly); } /** * Recursively adds contents from the referenced directory to an existing * collection. Directories are excluded from the result. Supported protocols * include {@code file} and {@code jar}. * * @param result The collection to which contents should be added. * @param directory The directory whose contents should be listed. * @return A collection of {@link URL}s representing the directory's contents. * @see #appendContents(Collection, URL, boolean, boolean) */ public static Collection<URL> appendContents(final Collection<URL> result, final URL directory) { return appendContents(result, directory, true, true); } /** * Add contents from the referenced directory to an existing collection. * Supported protocols include {@code file} and {@code jar}. * * @param result The collection to which contents should be added. * @param directory The directory whose contents should be listed. * @param recurse Whether to append contents recursively, as opposed to only * the directory's direct contents. * @param filesOnly Whether to exclude directories in the resulting collection * of contents. * @return A collection of {@link URL}s representing the directory's contents. */ public static Collection<URL> appendContents(final Collection<URL> result, final URL directory, final boolean recurse, final boolean filesOnly) { if (directory == null) return result; // nothing to append final String protocol = directory.getProtocol(); if (protocol.equals("file")) { final File dir = urlToFile(directory); final File[] list = dir.listFiles(); if (list != null) { for (final File file : list) { try { if (!filesOnly || file.isFile()) { result.add(file.toURI().toURL()); } if (recurse && file.isDirectory()) { appendContents(result, file.toURI().toURL()); } } catch (final MalformedURLException e) { e.printStackTrace(); } } } } else if (protocol.equals("jar")) { try { final String url = directory.toString(); final int bang = url.indexOf("!/"); if (bang < 0) return result; final String prefix = url.substring(bang + 2); final String baseURL = url.substring(0, bang + 2); final JarURLConnection connection = (JarURLConnection) new URL(baseURL).openConnection(); final JarFile jar = connection.getJarFile(); for (final JarEntry entry : new IteratorPlus<JarEntry>(jar.entries())) { final String urlEncoded = new URI(null, null, entry.getName(), null).toString(); if (urlEncoded.length() > prefix.length() && // omit directory itself urlEncoded.startsWith(prefix)) { if (filesOnly && urlEncoded.endsWith("/")) { // URL is directory; exclude it continue; } if (!recurse) { // check whether this URL is a *direct* child of the directory final int slash = urlEncoded.indexOf("/", prefix.length()); if (slash >= 0 && slash != urlEncoded.length() - 1) { // not a direct child continue; } } result.add(new URL(baseURL + urlEncoded)); } } jar.close(); } catch (final IOException e) { e.printStackTrace(); } catch (final URISyntaxException e) { throw new IllegalArgumentException(e); } } return result; } // -- Deprecated methods -- /** * Returns the {@link Matcher} object dissecting a versioned file name. * * @param filename the file name * @return the {@link Matcher} object * @deprecated see {@link #stripFilenameVersion(String)} */ @Deprecated public static Matcher matchVersionedFilename(final String filename) { return versionPattern.matcher(filename); } }
package at.irian.ankorman.sample1.fxclient; import at.irian.ankor.fx.controller.FXControllerChangeListener; import at.irian.ankor.http.ClientHttpMessageLoop; import at.irian.ankor.http.ServerHost; import at.irian.ankor.ref.Ref; import at.irian.ankor.ref.RefContext; import at.irian.ankor.ref.RefFactory; import at.irian.ankor.session.ModelRootFactory; import at.irian.ankor.session.SingletonSessionManager; import at.irian.ankor.socket.SocketAnkorSystemStarter; import at.irian.ankor.socket.SocketMessageLoop; import at.irian.ankor.system.AnkorSystem; import at.irian.ankor.system.AnkorSystemBuilder; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.layout.Pane; import javafx.stage.Stage; import java.io.IOException; import java.util.Map; import static java.util.regex.Matcher.quoteReplacement; /** * @author Thomas Spiegl */ public class App extends javafx.application.Application { //private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(App.class); private static final String DEFAULT_SERVER = "server@localhost:8080"; private static final String DEFAULT_CLIENT = "client@localhost:9090"; private static final int NUMBER_OF_CLIENTS = 3; private static RefFactory refFactory; private enum Mode { clientServer, client, server, manyClients, httpClient } public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) throws Exception { Map<String,String> params = getParameters().getNamed(); Mode mode = Mode.clientServer; String modeParam = params.get("mode"); if (modeParam != null) { mode = Mode.valueOf(modeParam); } if (mode == Mode.manyClients) { String[] command = {replaceVars("${java.home}/bin/java"), "-classpath", '"' + System.getProperty("java.class.path") + replaceVars( ":${project.home}/ankor-sample/ankorman-javafx-client/target/classes" + ":${project.home}/ankor-fx/target/classes" + ":${project.home}/ankor-core/target/classes" + ":${maven.repo}/org/slf4j/slf4j-api/1.7.1/slf4j-api-1.7.1.jar" + ":${maven.repo}/com/typesafe/config/0.3.1/config-0.3.1.jar" + ":${project.home}/ankor-actor/target/classes" + ":${maven.repo}/com/typesafe/akka/akka-actor_2.10/2.2.0/akka-actor_2.10-2.2.0.jar" + ":${maven.repo}/org/scala-lang/scala-library/2.10.2/scala-library-2.10.2.jar" + ":${project.home}/ankor-service/target/classes:${project.home}/ankor-el/target/classes" + ":${maven.repo}/javax/el/el-api/2.2/el-api-2.2.jar" + ":${maven.repo}/org/glassfish/web/el-impl/2.2/el-impl-2.2.jar" + ":${project.home}/ankor-json/target/classes" + ":${maven.repo}/com/fasterxml/jackson/core/jackson-databind/2.2.2/jackson-databind-2.2.2.jar" + ":${maven.repo}/com/fasterxml/jackson/core/jackson-annotations/2.2.2/jackson-annotations-2.2.2.jar" + ":${maven.repo}/com/fasterxml/jackson/core/jackson-core/2.2.2/jackson-core-2.2.2.jar" + ":${project.home}/ankor-annotation/target/classes" + ":${project.home}/ankor-sample/ankorman-server/target/classes" + ":${maven.repo}/ch/qos/logback/logback-classic/1.0.7/logback-classic-1.0.7.jar" + ":${maven.repo}/ch/qos/logback/logback-core/1.0.7/logback-core-1.0.7.jar") + '"', App.class.getName(), "--mode=client", "--client=c1@localhost:9090"}; Process lastProcess = null; for (int i = 0; i < NUMBER_OF_CLIENTS; i++) { String[] c = new String[6]; System.arraycopy(command, 0, c, 0, 5); c[5] = String.format("--client=c%03d@localhost:9%03d", i, i); lastProcess = new ProcessBuilder().command(c) .inheritIO() .start(); } if (lastProcess != null) { lastProcess.waitFor(); } System.exit(0); } String server = params.get("server"); if (server == null) { server = DEFAULT_SERVER; } if (mode == Mode.clientServer || mode == Mode.server) { createServerSystem(server, mode == Mode.clientServer); } if (mode == Mode.clientServer || mode == Mode.client) { String client = params.get("client"); if (client == null) { client = DEFAULT_CLIENT; } createClientSystem(client, server); startFXClient(primaryStage); } else if (mode == Mode.httpClient) { String client = params.get("client"); if (client == null) { client = DEFAULT_CLIENT; } createHttpClientSystem(client, server); startFXClient(primaryStage); } else { stop(); } } private void startFXClient(Stage primaryStage) throws IOException { primaryStage.setTitle("Ankor FX Sample"); Pane myPane = FXMLLoader.load(getClass().getClassLoader().getResource("main.fxml")); Scene myScene = new Scene(myPane); myScene.getStylesheets().add("style.css"); primaryStage.setScene(myScene); primaryStage.show(); } private String replaceVars(String s) { s = s.replaceAll(":", quoteReplacement(System.getProperty("path.separator"))); s = s.replaceAll("\\$\\{java\\.home\\}", quoteReplacement(System.getProperty("java.home"))); s = s.replaceAll("\\$\\{project\\.home\\}", quoteReplacement(System.getProperty("user.dir"))); s = s.replaceAll("\\$\\{maven\\.repo\\}", quoteReplacement(System.getProperty("user.home") + "/.m2/repository")); return s; } private void createServerSystem(String server, boolean daemon) { SocketAnkorSystemStarter appBuilder = new SocketAnkorSystemStarter() .withModelRootFactory(new MyModelRootFactory()) .withLocalHost(parseHost(server)); appBuilder.createAndStartServerSystem(daemon); } private SocketMessageLoop.Host parseHost(String systemIdAndHost) { String name = systemIdAndHost.split("@")[0]; String hostAndPort = systemIdAndHost.split("@")[1]; String hostname = hostAndPort.split(":")[0]; int port = Integer.parseInt(hostAndPort.split(":")[1]); return new SocketMessageLoop.Host(name, hostname, port); } private void createClientSystem(String client, String server) { SocketMessageLoop.Host clientHost = parseHost(client); SocketAnkorSystemStarter appBuilder = new SocketAnkorSystemStarter() .withModelRootFactory(new MyModelRootFactory()) .withLocalHost(clientHost) .withGlobalEventListener(new FXControllerChangeListener()) .withServerHost(parseHost(server)); refFactory = appBuilder.createAndStartClientSystem(); } public static RefFactory refFactory() { return refFactory; } private static class MyModelRootFactory implements ModelRootFactory { @Override public Object createModelRoot(Ref rootRef) { try { Class<?> modelRootType = Class.forName("at.irian.ankorman.sample1.viewmodel.ModelRoot"); Class<?> repoType = Class.forName("at.irian.ankorman.sample1.server.AnimalRepository"); Object repo = repoType.newInstance(); return modelRootType.getConstructor(Ref.class, repoType).newInstance(rootRef, repo); } catch (Exception e) { throw new RuntimeException("Unable to create model root", e); } } } private void createHttpClientSystem(String client, String server) { String clientId = client.indexOf('@') >= 0 ? client.split("@")[0] : client; String serverId = server.split("@")[0]; String serverUrl = server.split("@")[1]; ClientHttpMessageLoop clientMessageLoop = new ClientHttpMessageLoop(client, new ServerHost(serverId, serverUrl)); AnkorSystem clientSystem = new AnkorSystemBuilder() .withName(clientId) .withGlobalEventListener(new FXControllerChangeListener()) .withMessageBus(clientMessageLoop.getMessageBus()) .withModelContextId("collabTest") .createClient(); // start clientSystem.start(); clientMessageLoop.start(true); RefContext clientRefContext = ((SingletonSessionManager)clientSystem.getSessionManager()).getSession().getRefContext(); refFactory = clientRefContext.refFactory(); } }
package scrum.server.sprint; import ilarkesto.base.Str; import ilarkesto.base.Utl; import ilarkesto.base.time.Date; import ilarkesto.core.logging.Log; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Set; import scrum.server.admin.User; import scrum.server.common.Numbered; import scrum.server.project.Project; import scrum.server.project.Requirement; import scrum.server.release.Release; public class Sprint extends GSprint implements Numbered { private static final Log LOG = Log.get(Sprint.class); private static TaskDao taskDao; public static void setTaskDao(TaskDao taskDao) { Sprint.taskDao = taskDao; } public Release getRelease() { Set<Release> releases = getReleases(); return releases.isEmpty() ? null : Utl.getElement(releases, 0); } public void close() { float velocity = 0; Collection<Requirement> completedRequirements = new ArrayList<Requirement>(); Collection<Requirement> incompletedRequirements = new ArrayList<Requirement>(); List<Requirement> requirements = new ArrayList<Requirement>(getRequirements()); Collections.sort(requirements, getProject().getRequirementsOrderComparator()); for (Requirement requirement : requirements) { List<Task> tasks = new ArrayList<Task>(requirement.getTasks()); Collections.sort(tasks, requirement.getTasksOrderComparator()); if (requirement.isClosed()) { completedRequirements.add(requirement); } else { incompletedRequirements.add(requirement); } } setCompletedRequirementsData(SprintReportHelper.encodeRequirementsAndTasks(completedRequirements)); setIncompletedRequirementsData(SprintReportHelper.encodeRequirementsAndTasks(incompletedRequirements)); for (Requirement requirement : requirements) { List<Task> tasks = new ArrayList<Task>(requirement.getTasks()); if (requirement.isClosed()) { Float work = requirement.getEstimatedWork(); if (work != null) velocity += work; for (Task task : tasks) { taskDao.deleteEntity(task); } } else { for (Task task : tasks) { if (task.isClosed()) { taskDao.deleteEntity(task); } else { task.reset(); } } } requirement.setSprint(null); } setVelocity(velocity); Project project = getProject(); setProductOwners(project.getProductOwners()); setScrumMasters(project.getScrumMasters()); setTeamMembers(project.getTeamMembers()); project.setVelocity(Math.round(velocity)); } public String getProductOwnersAsString() { return Str.concat(User.getNames(getProductOwners()), ", "); } public String getScrumMastersAsString() { return Str.concat(User.getNames(getScrumMasters()), ", "); } public String getTeamMembersAsString() { return Str.concat(User.getNames(getTeamMembers()), ", "); } public List<SprintDaySnapshot> getDaySnapshots() { return sprintDaySnapshotDao.getSprintDaySnapshots(this); } public Set<SprintDaySnapshot> getExistingDaySnapshots() { return sprintDaySnapshotDao.getSprintDaySnapshotsBySprint(this); } public Integer getLengthInDays() { if (!isBeginSet() || !isEndSet()) return null; return getBegin().getPeriodTo(getEnd()).toDays(); } public SprintDaySnapshot getDaySnapshot(Date date) { return sprintDaySnapshotDao.getSprintDaySnapshot(this, date, true); } public int getRemainingWork() { int sum = 0; for (Task task : getTasks()) { Integer effort = task.getRemainingWork(); if (effort != null) sum += effort; } return sum; } public int getBurnedWork() { int sum = 0; for (Task task : getTasks()) { sum += task.getBurnedWork(); } return sum; } public Set<Task> getTasks() { return taskDao.getTasksBySprint(this); } public String getReference() { return scrum.client.sprint.Sprint.REFERENCE_PREFIX + getNumber(); } @Override public void updateNumber() { if (getNumber() == 0) setNumber(getProject().generateSprintNumber()); } @Override public void ensureIntegrity() { super.ensureIntegrity(); updateNumber(); if (getProject().isCurrentSprint(this)) { if (!isBeginSet()) setBegin(Date.today()); if (!isEndSet()) setEnd(getBegin().addDays(14)); } if (isBeginSet() && isEndSet() && getBegin().isAfter(getEnd())) setEnd(getBegin()); // delete when not current and end date older than 4 weeks // if (isEndSet() && !getProject().isCurrentSprint(this) && getEnd().isPast() // && getEnd().getPeriodToNow().toWeeks() > 4) { // LOG.info("Deleting sprint, which ended on", getEnd(), "->", toString()); // getDao().deleteEntity(this); } @Override public boolean isVisibleFor(User user) { return getProject().isVisibleFor(user); } public String getReferenceAndLabel() { return getReference() + " " + getLabel(); } @Override public String toString() { return getReferenceAndLabel(); } public void burndownTasksRandomly(Date begin, Date end) { int days = getBegin().getPeriodTo(getEnd()).toDays(); days -= (days / 7) * 2; int defaultWorkPerDay = getRemainingWork() / days; getDaySnapshot(begin).updateWithCurrentSprint(); begin = begin.nextDay(); while (begin.isBefore(end)) { if (!begin.isWeekend()) { int toBurn = Utl.randomInt(0, defaultWorkPerDay + (defaultWorkPerDay * 2)); int totalRemaining = getRemainingWork(); for (Task task : getTasks()) { if (toBurn == 0) break; int remaining = task.getRemainingWork(); int burn = Math.min(toBurn, remaining); remaining -= burn; toBurn -= burn; task.setBurnedWork(task.getBurnedWork() + burn); if (Utl.randomInt(1, 10) == 1) { remaining += Utl.randomInt(-defaultWorkPerDay * 2, defaultWorkPerDay * 3); } if (totalRemaining == 0) { remaining += Utl.randomInt(defaultWorkPerDay * 3, defaultWorkPerDay * 5); totalRemaining = remaining; } task.setRemainingWork(remaining); } } getDaySnapshot(begin).updateWithCurrentSprint(); begin = begin.nextDay(); } } }
//@@author A0164212U package seedu.task.model.task; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Comparator; import java.util.Objects; import seedu.task.commons.exceptions.IllegalValueException; import seedu.task.commons.util.CollectionUtil; import seedu.task.model.tag.UniqueTagList; /** * Represents a Task in the ToDo List. Guarantees: details are present and not * null, field values are validated. */ public class Task implements ReadOnlyTask, Comparable<Task> { private Description description; private Priority priority; private ArrayList<RecurringTaskOccurrence> occurrences; private boolean recurring; private UniqueTagList tags; private RecurringFrequency frequency; private ArrayList<Integer> occurrenceIndexList = new ArrayList<Integer>(); /** * Every field must be present and not null. */ public Task(Description description, Priority priority, Timing startTiming, Timing endTiming, UniqueTagList tags, boolean recurring, RecurringFrequency frequency) { assert !CollectionUtil.isAnyNull(description, priority, startTiming, tags); this.description = description; this.priority = priority; this.occurrences = new ArrayList<RecurringTaskOccurrence>(); this.tags = new UniqueTagList(tags); // protect internal tags from // changes in the arg list this.recurring = recurring; this.frequency = frequency; setOccurrences(startTiming, endTiming); occurrenceIndexList.add(0); } public Task(Description description, Priority priority, ArrayList<RecurringTaskOccurrence> occurrences, UniqueTagList tags, boolean recurring, RecurringFrequency frequency) { assert !CollectionUtil.isAnyNull(description, priority, occurrences, tags, recurring, frequency); this.description = description; this.priority = priority; this.occurrences = occurrences; this.tags = new UniqueTagList(tags); this.recurring = recurring; this.frequency = frequency; } /** * Creates a copy of the given ReadOnlyTask. */ public Task(ReadOnlyTask source) { this(source.getDescription(), source.getPriority(), source.getOccurrences(), source.getTags(), source.isRecurring(), source.getFrequency()); } @Override public ArrayList<Integer> getOccurrenceIndexList() { return occurrenceIndexList; }; @Override public void setOccurrenceIndexList(ArrayList<Integer> list) { occurrenceIndexList = list; }; public void setDescription(Description description) { assert description != null; this.description = description; } @Override public Description getDescription() { return description; } public void setPriority(Priority priority) { assert priority != null; this.priority = priority; } @Override public Priority getPriority() { return priority; } @Override public void setStartTiming(Timing startTiming) { assert startTiming != null; this.occurrences.get(0).setStartTiming(startTiming); } @Override public Timing getStartTiming(int i) { //add parameter to index into correct endTime return this.occurrences.get(i).getStartTiming(); } @Override public Timing getStartTiming() { return getStartTiming(0); } @Override public void setEndTiming(Timing endTiming) { //add parameter to index into correct endTime assert endTiming != null; this.occurrences.get(0).setEndTiming(endTiming); } @Override public Timing getEndTiming() { return this.occurrences.get(0).getEndTiming(); } public void setComplete() { //add parameter to index into correct endTime this.occurrences.get(0).setComplete(true); } @Override public boolean isComplete() { //add parameter to index into correct endTime return this.occurrences.get(0).isComplete(); } @Override public UniqueTagList getTags() { return new UniqueTagList(tags); } /** * Replaces this task's tags with the tags in the argument tag list. */ public void setTags(UniqueTagList replacement) { tags.setTags(replacement); } /** * Updates this task with the details of {@code replacement}. */ public void resetData(ReadOnlyTask replacement) { assert replacement != null; this.setDescription(replacement.getDescription()); this.setPriority(replacement.getPriority()); // this.setStartTiming(replacement.getStartTiming()); // this.setEndTiming(replacement.getEndTiming()); this.setOccurrences(replacement.getOccurrences()); this.setTags(replacement.getTags()); } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof ReadOnlyTask // instanceof handles nulls && this.isSameStateAs((ReadOnlyTask) other)); } @Override public int hashCode() { // use this method for custom fields hashing instead of implementing // your own return Objects.hash(description, priority, occurrences.get(0).getStartTiming(), occurrences.get(0).getEndTiming(), tags, recurring, frequency); } @Override public RecurringFrequency getFrequency() { return frequency; } @Override public String toString() { return getAsText(); } @Override public boolean isRecurring() { return recurring; } public void setRecurring(boolean recurring) { this.recurring = recurring; } @Override public ArrayList<RecurringTaskOccurrence> getOccurrences() { return occurrences; } public SimpleDateFormat retriveFormat(String s) { SimpleDateFormat format; if (s.length() <= 10) { format = new SimpleDateFormat("dd/MM/yyyy"); } else { format = new SimpleDateFormat("HH:mm dd/MM/yyyy"); } return format; } public void setOccurrences(ArrayList<RecurringTaskOccurrence> occurrences) { this.occurrences = occurrences; } /** If frequency is in hours - support up to 168 hours (1 week) * If frequency is in weeks - support up to 24 weeks * If frequency is in months - support up to 12 months * @param startTime * @param endTime */ public void setOccurrences(Timing initialStartTime, Timing initialEndTime) { this.occurrences.add(new RecurringTaskOccurrence(initialStartTime, initialEndTime)); if (isRecurring()) { int freqNumber = frequency.getFrequencyNumber(); String freqCharacter = frequency.getFrequencyCharacter(); Calendar cal1 = Calendar.getInstance(); Calendar cal2 = Calendar.getInstance(); cal1.setTime(initialStartTime.getTiming()); cal2.setTime(initialEndTime.getTiming()); SimpleDateFormat startTimeFormat = retriveFormat(initialStartTime.toString()); SimpleDateFormat endTimeFormat = retriveFormat(initialEndTime.toString()); String tempStartTime; String tempEndTime; Timing tempStart = null; Timing tempEnd = null; RecurringTaskOccurrence occurrenceToAdd; switch (freqCharacter) { case "h": for (int i = 1; i < RecurringFrequency.HOUR_LIMIT; i += freqNumber) { cal1.add(Calendar.HOUR_OF_DAY, freqNumber); cal2.add(Calendar.HOUR_OF_DAY, freqNumber); tempStartTime = startTimeFormat.format(cal1.getTime()); tempEndTime = endTimeFormat.format(cal2.getTime()); try { tempStart = new Timing(tempStartTime); } catch (IllegalValueException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { tempEnd = new Timing(tempEndTime); } catch (IllegalValueException e) { // TODO Auto-generated catch block e.printStackTrace(); } occurrenceToAdd = new RecurringTaskOccurrence(tempStart, tempEnd); occurrences.add(occurrenceToAdd); } break; case "d": for (int i = 1; i < RecurringFrequency.DAY_LIMIT; i += freqNumber) { cal1.add(Calendar.DATE, freqNumber); cal2.add(Calendar.DATE, freqNumber); tempStartTime = startTimeFormat.format(cal1.getTime()); tempEndTime = endTimeFormat.format(cal2.getTime()); try { tempStart = new Timing(tempStartTime); } catch (IllegalValueException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { tempEnd = new Timing(tempEndTime); } catch (IllegalValueException e) { // TODO Auto-generated catch block e.printStackTrace(); } occurrenceToAdd = new RecurringTaskOccurrence(tempStart, tempEnd); occurrences.add(occurrenceToAdd); } break; case "m": for (int i = 1; i < RecurringFrequency.MONTH_LIMIT; i += freqNumber) { cal1.add(Calendar.MONTH, freqNumber); cal2.add(Calendar.MONTH, freqNumber); tempStartTime = startTimeFormat.format(cal1.getTime()); tempEndTime = endTimeFormat.format(cal2.getTime()); try { tempStart = new Timing(tempStartTime); } catch (IllegalValueException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { tempEnd = new Timing(tempEndTime); } catch (IllegalValueException e) { // TODO Auto-generated catch block e.printStackTrace(); } occurrenceToAdd = new RecurringTaskOccurrence(tempStart, tempEnd); occurrences.add(occurrenceToAdd); } break; default: break; } } } //@@author /** * Results in Tasks sorted by completed state, followed by priority, endTiming, startTiming * and lastly by frequency. * Note: If a and b are tasks and a.compareTo(b) == 0, that does not imply * a.equals(b). */ @Override public int compareTo(Task compareTask) { int compareToResult = 0; if (this.isComplete() && compareTask.isComplete()) { compareToResult = 0; } else if (this.isComplete()) { compareToResult = 1; } else if (compareTask.isComplete()) { compareToResult = -1; } if (compareToResult == 0) { compareToResult = this.priority.compareTo(compareTask.priority); } if (compareToResult == 0) { compareToResult = this.occurrences.get(0).getEndTiming() .compareTo(compareTask.occurrences.get(0).getEndTiming()); } if (compareToResult == 0) { compareToResult = this.occurrences.get(0).getStartTiming() .compareTo(compareTask.occurrences.get(0).getStartTiming()); } if (compareToResult == 0) { compareToResult = this.getDescription().compareTo(compareTask.getDescription()); } return compareToResult; } public static Comparator<Task> TaskComparator = new Comparator<Task>() { @Override public int compare(Task task1, Task task2) { return task1.compareTo(task2); } }; }
package ui.listpanel; import backend.resource.*; import filter.expression.FilterExpression; import filter.expression.Qualifier; import github.TurboIssueEvent; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.control.Label; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.FlowPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import org.eclipse.egit.github.core.Comment; import ui.issuepanel.FilterPanel; import util.Utility; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; import java.util.HashSet; import java.util.List; import java.util.stream.Collectors; public class ListPanelCard extends VBox { private static final String OCTICON_PULL_REQUEST = "\uf009"; private static final int CARD_WIDTH = 350; private static final String OCTICON_COMMENT = "\uf02b"; /** * A card that is constructed with an issue as argument. Its components * are bound to the issue's fields and will update automatically. */ private final TurboIssue issue; private final Model model; private FlowPane issueDetails = new FlowPane(); private FilterPanel parentPanel; private final HashSet<Integer> issuesWithNewComments; /** * The constructor is the only method called from ListPanelCard. The rest of the methods in this class * are auxiliary methods called from the constructor so that the code is easier to understand. * * @param model * @param issue * @param parentPanel * @param issuesWithNewComments */ public ListPanelCard(Model model, TurboIssue issue, FilterPanel parentPanel, HashSet<Integer> issuesWithNewComments) { this.model = model; this.issue = issue; this.parentPanel = parentPanel; this.issuesWithNewComments = issuesWithNewComments; setup(); } private void setup() { Label issueTitle = new Label("#" + issue.getId() + " " + issue.getTitle()); issueTitle.setMaxWidth(CARD_WIDTH); issueTitle.setWrapText(true); issueTitle.getStyleClass().add("issue-panel-name"); if (issue.isCurrentlyRead()) { issueTitle.getStyleClass().add("issue-panel-name-read"); } if (!issue.isOpen()) { issueTitle.getStyleClass().add("issue-panel-closed"); } setupIssueDetailsBox(); setPadding(new Insets(0, 0, 3, 0)); setSpacing(1); getChildren().addAll(issueTitle, issueDetails); if (parentPanel.getCurrentFilterExpression().getQualifierNames().contains(Qualifier.UPDATED)) { getChildren().add(getEventDisplay(issue, getUpdateFilterHours(parentPanel.getCurrentFilterExpression()))); } } /** * Creates a JavaFX node containing a graphical display of this issue's events. * @param withinHours the number of hours to bound the returned events by * @return the node */ private Node getEventDisplay(TurboIssue issue, final int withinHours) { final LocalDateTime now = LocalDateTime.now(); List<TurboIssueEvent> eventsWithinDuration = issue.getMetadata().getEvents().stream() .filter(event -> { LocalDateTime eventTime = Utility.longToLocalDateTime(event.getDate().getTime()); int hours = Utility.safeLongToInt(eventTime.until(now, ChronoUnit.HOURS)); return hours < withinHours; }) .collect(Collectors.toList()); List<Comment> commentsWithinDuration = issue.getMetadata().getComments().stream() .filter(comment -> { LocalDateTime created = Utility.longToLocalDateTime(comment.getCreatedAt().getTime()); int hours = Utility.safeLongToInt(created.until(now, ChronoUnit.HOURS)); return hours < withinHours; }) .collect(Collectors.toList()); return layoutEvents(model, issue, eventsWithinDuration, commentsWithinDuration); } /** * Given a list of issue events, returns a JavaFX node laying them out properly. * @param events * @param comments * @return */ private static Node layoutEvents(Model model, TurboIssue issue, List<TurboIssueEvent> events, List<Comment> comments) { VBox result = new VBox(); result.setSpacing(3); VBox.setMargin(result, new Insets(3, 0, 0, 0)); // Events events.stream() .map(e -> e.display(model, issue)) .forEach(e -> result.getChildren().add(e)); // Comments if (comments.size() > 0) { String names = comments.stream() .map(comment -> comment.getUser().getLogin()) .distinct() .collect(Collectors.joining(", ")); HBox commentDisplay = new HBox(); commentDisplay.getChildren().addAll( TurboIssueEvent.octicon(TurboIssueEvent.OCTICON_QUOTE), new javafx.scene.control.Label( String.format("%d comments since, involving %s.", comments.size(), names)) ); result.getChildren().add(commentDisplay); } return result; } private int getUpdateFilterHours(FilterExpression currentFilterExpression) { List<Qualifier> filters = currentFilterExpression.find(q -> q.getName().equals("updated")); assert filters.size() > 0 : "Problem with isUpdateFilter"; // Return the first of the updated qualifiers, if there are multiple Qualifier qualifier = filters.get(0); if (qualifier.getNumber().isPresent()) { return qualifier.getNumber().get(); } else { // TODO support ranges properly. getEventDisplay only supports < assert qualifier.getNumberRange().isPresent(); if (qualifier.getNumberRange().get().getStart() != null) { // TODO semantics are not exactly right return qualifier.getNumberRange().get().getStart(); } else { assert qualifier.getNumberRange().get().getEnd() != null; // TODO semantics are not exactly right return qualifier.getNumberRange().get().getEnd(); } } } private void setupIssueDetailsBox() { issueDetails.setMaxWidth(CARD_WIDTH); issueDetails.setPrefWrapLength(CARD_WIDTH); issueDetails.setHgap(3); issueDetails.setVgap(3); updateDetails(); } private void updateDetails() { issueDetails.getChildren().clear(); if (issue.isPullRequest()) { Label icon = new Label(OCTICON_PULL_REQUEST); icon.getStyleClass().addAll("octicon", "issue-pull-request-icon"); issueDetails.getChildren().add(icon); } if (issue.getCommentCount() > 0){ Label commentIcon = new Label(OCTICON_COMMENT); commentIcon.getStyleClass().addAll("octicon", "comments-label-button"); Label commentCount = new Label(Integer.toString(issue.getCommentCount())); if (issuesWithNewComments.contains(issue.getId())) { commentIcon.getStyleClass().add("has-comments"); commentCount.getStyleClass().add("has-comments"); } issueDetails.getChildren().add(commentIcon); issueDetails.getChildren().add(commentCount); } for (TurboLabel label : model.getLabelsOfIssue(issue)) { issueDetails.getChildren().add(label.getNode()); } if (issue.getMilestone().isPresent() && model.getMilestoneOfIssue(issue).isPresent()) { TurboMilestone milestone = model.getMilestoneOfIssue(issue).get(); issueDetails.getChildren().add(new Label(milestone.getTitle())); } if (issue.getAssignee().isPresent() && model.getAssigneeOfIssue(issue).isPresent()) { TurboUser assignee = model.getAssigneeOfIssue(issue).get(); Label assigneeNameLabel = new Label(issue.getAssignee().get()); assigneeNameLabel.getStyleClass().add("display-box-padding"); ImageView avatar = new ImageView(); if (assignee.getAvatarURL().length() != 0) { Image image = assignee.getAvatar(); assert image != null; avatar.setImage(image); } HBox assigneeBox = new HBox(); assigneeBox.setAlignment(Pos.BASELINE_CENTER); assigneeBox.getChildren().addAll(avatar, assigneeNameLabel); issueDetails.getChildren().add(assigneeBox); } } }
package com.algar.ifuckforwind.fragment; import android.content.Context; import android.graphics.Color; import android.graphics.Typeface; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.algar.ifuckforwind.R; import com.github.mikephil.charting.animation.Easing; import com.github.mikephil.charting.charts.RadarChart; import com.github.mikephil.charting.components.AxisBase; import com.github.mikephil.charting.components.MarkerView; import com.github.mikephil.charting.components.XAxis; import com.github.mikephil.charting.components.YAxis; import com.github.mikephil.charting.data.Entry; import com.github.mikephil.charting.data.RadarData; import com.github.mikephil.charting.data.RadarDataSet; import com.github.mikephil.charting.data.RadarEntry; import com.github.mikephil.charting.formatter.IAxisValueFormatter; import com.github.mikephil.charting.highlight.Highlight; import com.github.mikephil.charting.interfaces.datasets.IRadarDataSet; import com.github.mikephil.charting.utils.MPPointF; import java.text.DecimalFormat; import java.util.ArrayList; public class SpotPreferredWindDirRadarChartFragment extends Fragment { private RadarChart mChart; Typeface mTfLight; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View rootView = inflater.inflate(R.layout.fragment_spot_pref_wind_dir_radar_chart, container, false); mChart = (RadarChart) rootView.findViewById(R.id.radar_chart); mChart.setBackgroundColor(Color.rgb(60, 65, 82)); mChart.getDescription().setEnabled(false); mChart.setWebLineWidth(1f); mChart.setWebColor(Color.LTGRAY); mChart.setWebLineWidthInner(1f); mChart.setWebColorInner(Color.LTGRAY); mChart.setWebAlpha(100); mChart.getLegend().setEnabled(false); mChart.setRotationEnabled(false); // create a custom MarkerView (extend MarkerView) and specify the layout // to use for it MarkerView mv = new RadarMarkerView(getActivity().getApplicationContext(), R.layout.radar_markerview); mv.setChartView(mChart); // For bounds control mChart.setMarker(mv); // Set the marker to the chart setData(); mChart.animateXY( 1400, 1400, Easing.EasingOption.EaseInOutQuad, Easing.EasingOption.EaseInOutQuad); mTfLight = Typeface.createFromAsset(getActivity().getAssets(), "OpenSans-Light.ttf");; XAxis xAxis = mChart.getXAxis(); xAxis.setTypeface(mTfLight); xAxis.setTextSize(9f); xAxis.setYOffset(0f); xAxis.setXOffset(0f); xAxis.setValueFormatter(new IAxisValueFormatter() { private String[] mActivities = new String[]{"North", "NE", "East", "SE", "South", "SW", "West", "NW"}; @Override public String getFormattedValue(float value, AxisBase axis) { return mActivities[(int) value % mActivities.length]; } }); xAxis.setTextColor(Color.WHITE); YAxis yAxis = mChart.getYAxis(); yAxis.setTypeface(mTfLight); yAxis.setLabelCount(5, false); yAxis.setTextSize(9f); yAxis.setAxisMinimum(0f); yAxis.setAxisMaximum(80f); yAxis.setDrawLabels(false); return rootView; } public void setData() { float scaleFactor = 100; int nrOfWeatherDirections = 8; ArrayList<RadarEntry> entries = new ArrayList<RadarEntry>(); // NOTE: The order of the entries when being added to the entries array determines their // position around the center of the chart. for (int i = 0; i < nrOfWeatherDirections; i++) { float val1 = (float) (Math.random() * scaleFactor); entries.add(new RadarEntry(val1)); } RadarDataSet dataSet = new RadarDataSet(entries, null); dataSet.setColor(Color.rgb(103, 110, 129)); dataSet.setFillColor(Color.rgb(103, 110, 129)); dataSet.setDrawFilled(true); dataSet.setFillAlpha(180); dataSet.setLineWidth(2f); dataSet.setDrawHighlightCircleEnabled(true); dataSet.setDrawHighlightIndicators(false); ArrayList<IRadarDataSet> sets = new ArrayList<IRadarDataSet>(); sets.add(dataSet); RadarData data = new RadarData(sets); data.setValueTypeface(mTfLight); data.setValueTextSize(8f); data.setDrawValues(false); data.setValueTextColor(Color.WHITE); mChart.setData(data); mChart.invalidate(); } public static class RadarMarkerView extends MarkerView { private TextView tvContent; private DecimalFormat format = new DecimalFormat(" public RadarMarkerView(Context context, int layoutResource) { super(context, layoutResource); tvContent = (TextView) findViewById(R.id.tvContent); tvContent.setTypeface(Typeface.createFromAsset(context.getAssets(), "OpenSans-Light.ttf")); } // callbacks every time the MarkerView is redrawn, can be used to update the // content (user-interface) @Override public void refreshContent(Entry e, Highlight highlight) { tvContent.setText(format.format(e.getY()) + " %"); super.refreshContent(e, highlight); } @Override public MPPointF getOffset() { return new MPPointF(-(getWidth() / 2), -getHeight() - 10); } } }
package com.team980.thunderscout.analytics.rankings.breakdown; import com.team980.thunderscout.schema.ScoutData; import com.team980.thunderscout.schema.enumeration.ClimbingStats; import com.team980.thunderscout.schema.enumeration.FuelDumpAmount; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import java.util.List; //TODO for 2018: Find a way to standardize how this class functions... public class AverageScoutData implements Serializable { private List<ScoutData> dataList; public AverageScoutData(List<ScoutData> d) { dataList = d; } //INIT public String getTeam() { return dataList.get(0).getTeam(); } public Date getLastUpdated() { return dataList.get(0).getDate(); //dateAdded of newest match } public int getNumberOfMatches() { return dataList.size(); } public List<ScoutData> getDataList() { //convenience method for hax return dataList; } //AUTO public double getCrossedBaselinePercentage() { double i = 0; for (ScoutData data : dataList) { if (data.getAutonomous().getCrossedBaseline()) { i++; } } return (i / dataList.size()) * 100; } public float getAverageAutoGearsDelivered() { float i = 0; for (ScoutData data : dataList) { i += data.getAutonomous().getGearsDelivered(); } return i / dataList.size(); } public float getAverageAutoGearsDropped() { float i = 0; for (ScoutData data : dataList) { i += data.getAutonomous().getGearsDropped(); } return i / dataList.size(); } //Averages the ordinal public FuelDumpAmount getAverageAutoLowGoalDumpAmount() { float i = 0; for (ScoutData data : dataList) { i += data.getAutonomous().getLowGoalDumpAmount().ordinal(); } int average = (int) (i / dataList.size()); return FuelDumpAmount.values()[average]; } public float getAverageAutoHighGoals() { float i = 0; for (ScoutData data : dataList) { i += data.getAutonomous().getHighGoals(); } return i / dataList.size(); } public float getAverageAutoMissedHighGoals() { float i = 0; for (ScoutData data : dataList) { i += data.getAutonomous().getMissedHighGoals(); } return i / dataList.size(); } //TELEOP public float getAverageTeleopGearsDelivered() { float i = 0; for (ScoutData data : dataList) { i += data.getTeleop().getGearsDelivered(); } return i / dataList.size(); } public float getAverageTeleopGearsDropped() { float i = 0; for (ScoutData data : dataList) { i += data.getTeleop().getGearsDelivered(); } return i / dataList.size(); } public float getAverageTeleopDumpFrequency() { float i = 0; for (ScoutData data : dataList) { i += data.getTeleop().getLowGoalDumps().size(); } return i / dataList.size(); } //Uses ordinal public FuelDumpAmount getAverageTeleopLowGoalDumpAmount() { float i = 0; for (ScoutData data : dataList) { for (FuelDumpAmount amount : data.getTeleop().getLowGoalDumps()) { i += amount.ordinal(); } } int average = (int) (i / dataList.size()); if (average >= FuelDumpAmount.values().length) { average = FuelDumpAmount.values().length - 1; } return FuelDumpAmount.values()[average]; } public float getAverageTeleopHighGoals() { float i = 0; for (ScoutData data : dataList) { i += data.getTeleop().getHighGoals(); } return i / dataList.size(); } public float getAverageTeleopMissedHighGoals() { float i = 0; for (ScoutData data : dataList) { i += data.getTeleop().getMissedHighGoals(); } return i / dataList.size(); } public double getClimbingStatsPercentage(ClimbingStats stat) { double i = 0; for (ScoutData data : dataList) { if (data.getTeleop().getClimbingStats() == stat) { i++; } } return (i / dataList.size()) * 100; } //SUMMARY public List<String> getTroublesList() { List<String> troublesList = new ArrayList<>(); for (ScoutData data : dataList) { if (data.getTroubleWith() != null && !data.getTroubleWith().isEmpty()) { troublesList.add("[" + data.getMatchNumber() + "] " + data.getTroubleWith()); //Prefix match number on comment } } return troublesList; } public List<String> getCommentsList() { List<String> commentsList = new ArrayList<>(); for (ScoutData data : dataList) { if (data.getComments() != null && !data.getComments().isEmpty()) { commentsList.add("[" + data.getMatchNumber() + "] " + data.getComments()); //Prefix match number on comment } } return commentsList; } }
package com.appleframework.web.springmvc.interceptor; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import com.appleframework.context.invoke.InvokeContext; import com.appleframework.model.Operator; import com.appleframework.model.OperatorType; /** * @author Cruise.Xu */ public class OperatorInterceptor extends HandlerInterceptorAdapter { private static String SESSION_USER_KEY = "CAS_USER"; @Resource private InvokeContext invokeContext; @Override public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception { Object user = httpServletRequest.getSession().getAttribute(SESSION_USER_KEY); if (null != user) { Operator operator = Operator.creat(OperatorType.OSS, user.toString()); invokeContext.setOperator(operator); } return true; } public void setInvokeContext(InvokeContext invokeContext) { this.invokeContext = invokeContext; } }
package org.csstudio.graphene; import static org.epics.pvmanager.formula.ExpressionLanguage.formula; import static org.epics.pvmanager.formula.ExpressionLanguage.formulaArg; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.Arrays; import java.util.logging.Level; import java.util.logging.Logger; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseMoveListener; import org.eclipse.swt.widgets.Composite; import org.eclipse.ui.IMemento; import org.epics.graphene.AxisRange; import org.epics.graphene.AxisRanges; import org.epics.graphene.BubbleGraph2DRendererUpdate; import org.epics.pvmanager.PVManager; import org.epics.pvmanager.PVWriter; import org.epics.pvmanager.PVWriterEvent; import org.epics.pvmanager.PVWriterListener; import org.epics.pvmanager.graphene.BubbleGraph2DExpression; import org.epics.pvmanager.graphene.ExpressionLanguage; import org.epics.pvmanager.graphene.Graph2DResult; import org.epics.util.array.ArrayDouble; import org.epics.vtype.VNumberArray; import org.epics.vtype.VTable; import org.epics.vtype.ValueFactory; import org.epics.vtype.table.VTableFactory; /** * @author shroffk * */ public class BubbleGraph2DWidget extends AbstractPointDatasetGraph2DWidget<BubbleGraph2DRendererUpdate, BubbleGraph2DExpression> implements ISelectionProvider { private PVWriter<Object> selectionValueWriter; public BubbleGraph2DWidget(Composite parent, int style) { super(parent, style); addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { if (evt.getPropertyName().equals("highlightSelectionValue") && getGraph() != null) { updateGraph(); } } }); getImageDisplay().addMouseMoveListener(new MouseMoveListener() { @Override public void mouseMove(MouseEvent e) { if (isHighlightSelectionValue() && getGraph() != null) { getGraph().update(getGraph().newUpdate().focusPixel(e.x, e.y)); } } }); addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { if (evt.getPropertyName().equals("selectionValuePv") && getGraph() != null) { if (selectionValueWriter != null) { selectionValueWriter.close(); selectionValueWriter = null; } if (getSelectionValuePv() == null || getSelectionValuePv().trim().isEmpty()) { return; } selectionValueWriter = PVManager.write(formula(getSelectionValuePv())) .writeListener(new PVWriterListener<Object>() { @Override public void pvChanged( PVWriterEvent<Object> event) { if (event.isWriteFailed()) { Logger.getLogger(BubbleGraph2DWidget.class.getName()) .log(Level.WARNING, "Line graph selection notification failed", event.getPvWriter().lastWriteException()); } } }) .async(); if (getSelectionValue() != null) { selectionValueWriter.write(getSelectionValue()); } } } }); addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { if (evt.getPropertyName().equals("selectionValue") && selectionValueWriter != null) { if (getSelectionValue() != null) { selectionValueWriter.write(getSelectionValue()); } } } }); addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent event) { if (event.getPropertyName().equals("sizeColumnFormula") || event.getPropertyName().equals("colorColumnFormula")) { reconnect(); } } }); } @Override protected BubbleGraph2DExpression createGraph() { BubbleGraph2DExpression graph = ExpressionLanguage.bubbleGraphOf(formula(getDataFormula()), formulaArg(getXColumnFormula()), formulaArg(getYColumnFormula()), formulaArg(getSizeColumnFormula()), formulaArg(getColorColumnFormula())); return graph; } @Override protected BubbleGraph2DRendererUpdate createUpdate() { return getGraph().newUpdate().highlightFocusValue(isHighlightSelectionValue()) .xAxisRange(getXAxisRange()).yAxisRange(getYAxisRange()); } // private void updateGraph() { // getGraph().update(getGraph().newUpdate().highlightFocusValue(isHighlightSelectionValue()) // .xAxisRange(getXAxisRange()).yAxisRange(getYAxisRange())); private String sizeColumnFormula; private String colorColumnFormula; private boolean highlightSelectionValue = false; private AxisRange xAxisRange = AxisRanges.display(); private AxisRange yAxisRange = AxisRanges.display(); private static final String MEMENTO_SIZE_COLUMN_FORMULA = "sizeColumnFormula"; //$NON-NLS-1$ private static final String MEMENTO_COLOR_COLUMN_FORMULA = "sizeColumnFormula"; //$NON-NLS-1$ private static final String MEMENTO_HIGHLIGHT_SELECTION_VALUE = "highlightSelectionValue"; //$NON-NLS-1$ public String getSizeColumnFormula() { return this.sizeColumnFormula; } public void setSizeColumnFormula(String sizeColumnFormula) { String oldValue = this.sizeColumnFormula; this.sizeColumnFormula = sizeColumnFormula; changeSupport.firePropertyChange("sizeColumnFormula", oldValue, this.sizeColumnFormula); } public String getColorColumnFormula() { return this.colorColumnFormula; } public void setColorColumnFormula(String colorColumnFormula) { String oldValue = this.colorColumnFormula; this.colorColumnFormula = colorColumnFormula; changeSupport.firePropertyChange("colorColumnFormula", oldValue, this.colorColumnFormula); } public AxisRange getXAxisRange() { return xAxisRange; } public void setXAxisRange(AxisRange xAxisRange) { AxisRange oldValue = this.xAxisRange; this.xAxisRange = xAxisRange; changeSupport.firePropertyChange("xAxisRange", oldValue, this.xAxisRange); } public AxisRange getYAxisRange() { return yAxisRange; } public void setYAxisRange(AxisRange yAxisRange) { AxisRange oldValue = this.yAxisRange; this.yAxisRange = yAxisRange; changeSupport.firePropertyChange("yAxisRange", oldValue, this.yAxisRange); } public boolean isHighlightSelectionValue() { return highlightSelectionValue; } public void setHighlightSelectionValue(boolean highlightSelectionValue) { boolean oldValue = this.highlightSelectionValue; this.highlightSelectionValue = highlightSelectionValue; changeSupport.firePropertyChange("highlightSelectionValue", oldValue, this.highlightSelectionValue); } public void saveState(IMemento memento) { super.saveState(memento); if (getSizeColumnFormula() != null) { memento.putString(MEMENTO_SIZE_COLUMN_FORMULA, getSizeColumnFormula()); } if (getColorColumnFormula() != null) { memento.putString(MEMENTO_COLOR_COLUMN_FORMULA, getColorColumnFormula()); } memento.putBoolean(MEMENTO_HIGHLIGHT_SELECTION_VALUE, isHighlightSelectionValue()); } public void loadState(IMemento memento) { super.loadState(memento); if (memento != null) { if (memento.getString(MEMENTO_SIZE_COLUMN_FORMULA) != null) { setSizeColumnFormula(memento.getString(MEMENTO_SIZE_COLUMN_FORMULA)); } if (memento.getString(MEMENTO_COLOR_COLUMN_FORMULA) != null) { setColorColumnFormula(memento.getString(MEMENTO_COLOR_COLUMN_FORMULA)); } if (memento.getBoolean(MEMENTO_HIGHLIGHT_SELECTION_VALUE) != null) { setHighlightSelectionValue(memento.getBoolean(MEMENTO_HIGHLIGHT_SELECTION_VALUE)); } } } private VTable selectionValue; private String selectionValuePv; public String getSelectionValuePv() { return selectionValuePv; } public void setSelectionValuePv(String selectionValuePv) { String oldValue = this.selectionValuePv; this.selectionValuePv = selectionValuePv; changeSupport.firePropertyChange("selectionValuePv", oldValue, this.selectionValuePv); } public VTable getSelectionValue() { return selectionValue; } private void setSelectionValue(VTable selectionValue) { VTable oldValue = this.selectionValue; this.selectionValue = selectionValue; changeSupport.firePropertyChange("selectionValue", oldValue, this.selectionValue); } @Override protected void processInit() { super.processInit(); processValue(); } @Override protected void processValue() { Graph2DResult result = getCurrentResult(); if (result == null || result.getData() == null) { setSelectionValue(null); } else { int index = result.focusDataIndex(); if (index == -1) { setSelectionValue(null); } else { if (result.getData() instanceof VTable) { VTable data = (VTable) result.getData(); setSelectionValue(VTableFactory.extractRow(data, index)); return; } if (result.getData() instanceof VNumberArray) { VNumberArray data = (VNumberArray) result.getData(); VTable selection = ValueFactory.newVTable(Arrays.<Class<?>>asList(double.class, double.class), Arrays.asList("X", "Y"), Arrays.<Object>asList(new ArrayDouble(index), new ArrayDouble(data.getData().getDouble(index)))); setSelectionValue(selection); return; } setSelectionValue(null); } } } @Override public ISelection getSelection() { if (getDataFormula() != null) { return new StructuredSelection(new BubbleGraph2DSelection(this)); } return null; } @Override public void addSelectionChangedListener( final ISelectionChangedListener listener) { } @Override public void removeSelectionChangedListener( ISelectionChangedListener listener) { } @Override public void setSelection(ISelection selection) { throw new UnsupportedOperationException("Not implemented yet"); } private boolean configurable = true; private BubbleGraph2DConfigurationDialog dialog; @Override public boolean isConfigurable() { return this.configurable; } @Override public void setConfigurable(boolean configurable) { boolean oldValue = this.configurable; this.configurable = configurable; changeSupport.firePropertyChange("configurable", oldValue, this.configurable); } @Override public void openConfigurationDialog() { if (dialog != null) return; dialog = new BubbleGraph2DConfigurationDialog(this, "Configure Bubble Graph"); dialog.open(); } @Override public boolean isConfigurationDialogOpen() { return dialog != null; } @Override public void configurationDialogClosed() { dialog = null; } }
package im.actor.messenger.app.fragment.chat.adapter; import android.text.Editable; import android.text.Layout; import android.text.Spannable; import android.text.SpannableString; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.method.LinkMovementMethod; import android.text.style.CharacterStyle; import android.text.style.ClickableSpan; import android.text.style.ForegroundColorSpan; import android.text.style.URLSpan; import android.text.util.Linkify; import android.util.Patterns; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.TextView; import java.util.regex.Matcher; import java.util.regex.Pattern; import im.actor.messenger.R; import im.actor.messenger.app.emoji.SmileProcessor; import im.actor.messenger.app.fragment.chat.MessagesAdapter; import im.actor.messenger.app.keyboard.emoji.smiles.SmilesListener; import im.actor.messenger.app.util.TextUtils; import im.actor.messenger.app.view.Fonts; import im.actor.messenger.app.view.TintImageView; import im.actor.model.entity.Message; import im.actor.model.entity.PeerType; import im.actor.model.entity.content.TextContent; import im.actor.model.viewmodel.UserVM; import in.uncod.android.bypass.Bypass; import in.uncod.android.bypass.MentionSpan; import static im.actor.messenger.app.Core.myUid; import static im.actor.messenger.app.Core.users; import static im.actor.messenger.app.emoji.SmileProcessor.emoji; public class TextHolder extends MessageHolder { private ViewGroup mainContainer; private FrameLayout messageBubble; private TextView text; private TextView time; private TintImageView status; private int[] colors; private int waitColor; private int sentColor; private int deliveredColor; private int readColor; private int errorColor; private boolean isMarkdownEnabled; private SmilesListener smilesListener; Bypass bypass; public TextHolder(MessagesAdapter fragment, final View itemView, boolean isMarkdownEnabled) { super(fragment, itemView, false); bypass = new Bypass(); this.isMarkdownEnabled = isMarkdownEnabled; mainContainer = (ViewGroup) itemView.findViewById(R.id.mainContainer); messageBubble = (FrameLayout) itemView.findViewById(R.id.fl_bubble); text = (TextView) itemView.findViewById(R.id.tv_text); text.setTypeface(Fonts.regular()); time = (TextView) itemView.findViewById(R.id.tv_time); time.setTypeface(Fonts.regular()); status = (TintImageView) itemView.findViewById(R.id.stateIcon); colors = new int[]{ itemView.getResources().getColor(R.color.placeholder_0), itemView.getResources().getColor(R.color.placeholder_1), itemView.getResources().getColor(R.color.placeholder_2), itemView.getResources().getColor(R.color.placeholder_3), itemView.getResources().getColor(R.color.placeholder_4), itemView.getResources().getColor(R.color.placeholder_5), itemView.getResources().getColor(R.color.placeholder_6), }; waitColor = itemView.getResources().getColor(R.color.conv_state_pending); sentColor = itemView.getResources().getColor(R.color.conv_state_sent); deliveredColor = itemView.getResources().getColor(R.color.conv_state_delivered); readColor = itemView.getResources().getColor(R.color.conv_state_read); errorColor = itemView.getResources().getColor(R.color.conv_state_error); } @Override protected void bindData(final Message message, boolean isUpdated) { CharSequence spannedText; if(isMarkdownEnabled){ spannedText = new SpannableStringBuilder(bypass.markdownToSpannable(((TextContent) message.getContent()).getText(), false)); Editable spannedTextEditable = new SpannableStringBuilder(spannedText); URLSpan[] urlSpans = spannedTextEditable.getSpans(0, spannedTextEditable.length(), URLSpan.class); if(urlSpans.length>0){ int start; int end; int prevEnd = 0; Spannable toLinkyfy; for (int i = 0; i < urlSpans.length; i++) { start = spannedTextEditable.getSpanStart(urlSpans[i]); end = spannedTextEditable.getSpanEnd(urlSpans[i]); if(start>spannedText.length()-1)continue; toLinkyfy = (Spannable) spannedText.subSequence(prevEnd , start); Linkify.addLinks(toLinkyfy, Linkify.EMAIL_ADDRESSES | Linkify.PHONE_NUMBERS | Linkify.WEB_URLS); spannedTextEditable.replace(prevEnd, start, toLinkyfy); prevEnd = end; } toLinkyfy = (Spannable) spannedText.subSequence(prevEnd, spannedTextEditable.length()); Linkify.addLinks(toLinkyfy, Linkify.EMAIL_ADDRESSES | Linkify.PHONE_NUMBERS | Linkify.WEB_URLS); spannedTextEditable.replace(prevEnd, spannedTextEditable.length(), toLinkyfy); spannedText = spannedTextEditable; }else{ spannedText = spannedTextEditable; Linkify.addLinks((Spannable) spannedText, Linkify.EMAIL_ADDRESSES | Linkify.PHONE_NUMBERS | Linkify.WEB_URLS); } }else{ spannedText = new SpannableStringBuilder(((TextContent) message.getContent()).getText()); } if (getPeer().getPeerType() == PeerType.GROUP && message.getSenderId() != myUid()) { String name; UserVM userModel = users().get(message.getSenderId()); if (userModel != null) { name = userModel.getName().get(); } else { name = "???"; } SpannableStringBuilder builder = new SpannableStringBuilder(); builder.append(name); builder.setSpan(new ForegroundColorSpan(colors[Math.abs(message.getSenderId()) % colors.length]), 0, name.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE); builder.append("\n"); spannedText = builder.append(spannedText); } if (emoji().containsEmoji(spannedText)) { if (emoji().isLoaded()) { spannedText = emoji().processEmojiCompatMutable(spannedText, SmileProcessor.CONFIGURATION_BUBBLES); } else { final CharSequence finalSpannedText = spannedText; if (smilesListener != null) { emoji().unregisterListener(smilesListener); } smilesListener = new SmilesListener() { @Override public void onSmilesUpdated(boolean completed) { text.setText(emoji().processEmojiCompatMutable(finalSpannedText, SmileProcessor.CONFIGURATION_BUBBLES)); emoji().unregisterListener(this); } }; emoji().registerListener(smilesListener); } } bindRawText(spannedText, message, false); } public void bindRawText(CharSequence spannedText, Message message, boolean isItalic) { if (message.getSenderId() == myUid()) { messageBubble.setBackgroundResource(R.drawable.bubble_text_out); } else { messageBubble.setBackgroundResource(R.drawable.bubble_text_in); } if (isItalic) { text.setTypeface(Fonts.italic()); } else { text.setTypeface(Fonts.regular()); } text.setText(spannedText); text.setMovementMethod(new CustomLinkMovementMethod()); if(!isMarkdownEnabled){ Linkify.addLinks(text, Linkify.EMAIL_ADDRESSES | Linkify.PHONE_NUMBERS | Linkify.WEB_URLS); //Linkify can't custom shames :'( String regex = "(people:\\/\\/)([0-9]{1,20})"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(text.getText().toString()); SpannableString s = SpannableString.valueOf(text.getText()); while (m.find()){ MentionSpan span = new MentionSpan(m.group(), false); s.setSpan(span, m.start(), m.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } text.setText(s); //Linkify can't ".email" regex = "(https:\\/\\/)(quit\\.email\\/join\\/)([0-9-a-z]{1,64})"; p = Pattern.compile(regex); m = p.matcher(text.getText().toString()); s = SpannableString.valueOf(text.getText()); while (m.find()){ URLSpan span = new URLSpan(m.group()); s.setSpan(span, m.start(), m.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } text.setText(s); } if (message.getSenderId() == myUid()) { status.setVisibility(View.VISIBLE); switch (message.getMessageState()) { case SENT: status.setResource(R.drawable.msg_check_1); status.setTint(sentColor); break; case RECEIVED: status.setResource(R.drawable.msg_check_2); status.setTint(deliveredColor); break; case READ: status.setResource(R.drawable.msg_check_2); status.setTint(readColor); break; default: case PENDING: status.setResource(R.drawable.msg_clock); status.setTint(waitColor); break; case ERROR: status.setResource(R.drawable.msg_error); status.setTint(errorColor); break; } } else { status.setVisibility(View.GONE); } time.setText(TextUtils.formatTime(message.getDate())); } @Override public void unbind() { super.unbind(); emoji().unregisterListener(smilesListener); } class CustomLinkMovementMethod extends LinkMovementMethod{ private CharacterStyle mPressedSpan; @Override public boolean onTouchEvent(TextView textView, Spannable spannable, MotionEvent event) { mPressedSpan = getPressedSpan(textView, spannable, event); super.onTouchEvent(textView, spannable, event); mainContainer.onTouchEvent(event); return true; } private CharacterStyle getPressedSpan(TextView textView, Spannable spannable, MotionEvent event) { int x = (int) event.getX(); int y = (int) event.getY(); x -= textView.getTotalPaddingLeft(); y -= textView.getTotalPaddingTop(); x += textView.getScrollX(); y += textView.getScrollY(); Layout layout = textView.getLayout(); int line = layout.getLineForVertical(y); int off = layout.getOffsetForHorizontal(line, x); CharacterStyle[] link = spannable.getSpans(off, off, CharacterStyle.class); CharacterStyle touchedSpan = null; if (link.length > 0) { touchedSpan = link[0]; } return touchedSpan; } } }
package us.myles.ViaVersion.bukkit.listeners.protocol1_9to1_8; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.scheduler.BukkitRunnable; import us.myles.ViaVersion.api.minecraft.item.Item; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; public class HandItemCache extends BukkitRunnable { public static boolean CACHE = false; private static Map<UUID, Item> handCache = new ConcurrentHashMap<>(); public static Item getHandItem(UUID player) { return handCache.get(player); } @Override public void run() { List<UUID> players = new ArrayList<>(handCache.keySet()); for (Player p : Bukkit.getOnlinePlayers()) { handCache.put(p.getUniqueId(), convert(p.getItemInHand())); players.remove(p.getUniqueId()); } // Remove offline players for (UUID uuid : players) { handCache.remove(uuid); } } public static Item convert(ItemStack itemInHand) { if (itemInHand == null) return new Item((short) 0, (byte) 0, (short) 0, null); return new Item((short) itemInHand.getTypeId(), (byte) itemInHand.getAmount(), itemInHand.getDurability(), null); } }
package ch.elexis.core.ui.preferences; import java.util.List; import org.eclipse.core.databinding.DataBindingContext; import org.eclipse.core.databinding.UpdateValueStrategy; import org.eclipse.core.databinding.beans.PojoProperties; import org.eclipse.core.databinding.observable.value.IObservableValue; import org.eclipse.core.databinding.observable.value.IValueChangeListener; import org.eclipse.core.databinding.observable.value.ValueChangeEvent; import org.eclipse.core.databinding.observable.value.WritableValue; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.databinding.swt.WidgetProperties; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IInputValidator; import org.eclipse.jface.dialogs.InputDialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.layout.TableColumnLayout; import org.eclipse.jface.preference.PreferencePage; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.CellLabelProvider; import org.eclipse.jface.viewers.CheckboxTableViewer; import org.eclipse.jface.viewers.ColumnWeightData; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.TableViewerColumn; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerCell; import org.eclipse.jface.viewers.ViewerComparator; import org.eclipse.jface.window.Window; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.ColorDialog; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Link; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import org.eclipse.wb.swt.SWTResourceManager; import ch.elexis.admin.AccessControlDefaults; import ch.elexis.core.constants.StringConstants; import ch.elexis.core.data.activator.CoreHub; import ch.elexis.core.data.interfaces.IPersistentObject; import ch.elexis.core.data.service.LocalLockServiceHolder; import ch.elexis.core.lock.types.LockResponse; import ch.elexis.core.model.IUser; import ch.elexis.core.services.IElexisServerService.ConnectionStatus; import ch.elexis.core.services.holder.ContextServiceHolder; import ch.elexis.core.services.holder.ElexisServerServiceHolder; import ch.elexis.core.ui.Hub; import ch.elexis.core.ui.UiDesk; import ch.elexis.core.ui.actions.RestrictedAction; import ch.elexis.core.ui.coolbar.MandantSelectionContributionItem; import ch.elexis.core.ui.data.UiMandant; import ch.elexis.core.ui.dialogs.ChangePasswordDialog; import ch.elexis.core.ui.dialogs.KontaktSelektor; import ch.elexis.core.ui.dialogs.TotpDialog; import ch.elexis.core.ui.icons.Images; import ch.elexis.core.ui.locks.IUnlockable; import ch.elexis.core.ui.locks.LockedRestrictedAction; import ch.elexis.core.ui.preferences.inputs.PrefAccessDenied; import ch.elexis.core.ui.util.BooleanNotConverter; import ch.elexis.core.ui.util.SWTHelper; import ch.elexis.core.ui.util.viewers.DefaultLabelProvider; import ch.elexis.data.Anwender; import ch.elexis.data.Kontakt; import ch.elexis.data.Mandant; import ch.elexis.data.Person; import ch.elexis.data.Query; import ch.elexis.data.Rechnungssteller; import ch.elexis.data.Role; import ch.elexis.data.User; public class UserManagementPreferencePage extends PreferencePage implements IWorkbenchPreferencePage, IUnlockable { private TableViewer tableViewerUsers; private WritableValue<User> wvUser = new WritableValue<User>(null, User.class); private WritableValue<Anwender> wvAnwender = new WritableValue<Anwender>(null, Anwender.class); private Button btnIsExecutiveDoctor; private Label lblRespPhysColor; private Group grpAccounting; public static final String CHANGE_LINK = "<a>ändern</a>"; private Link linkContact; private CheckboxTableViewer checkboxTableViewerAssociation; private CheckboxTableViewer checkboxTableViewerRoles; private Link linkChangePassword; private Button btnUserIsAdmin; private Button btnMandatorIsInactive; private Color lblRespPhysColorDefColor; private Link linkRechnungssteller; private RestrictedAction addUserAction, deleteUserAction, lockUserAction; private Button btnUserIsLocked; private Link linkTotp; private Button btnAllowExternalAccess; private Label userInfoLabel; /** * Create the preference page. */ public UserManagementPreferencePage(){ setTitle("Benutzerverwaltung"); noDefaultAndApplyButton(); } /** * Create contents of the preference page. * * @param parent */ @Override public Control createContents(Composite parent){ if (!CoreHub.acl.request(AccessControlDefaults.ACL_USERS)) { return new PrefAccessDenied(parent); } Composite container = new Composite(parent, SWT.NULL); container.setLayout(new GridLayout(2, false)); MenuManager popManager = new MenuManager(); addUserAction = new RestrictedAction(AccessControlDefaults.USER_CREATE, Messages.LabGroupPrefs_add) { { setImageDescriptor(Images.IMG_NEW.getImageDescriptor()); } @Override public void doRun(){ IInputValidator iiv = new IInputValidator() { @Override public String isValid(String newText){ if (newText.length() < 3) { return "Mindestens 3 Zeichen"; } boolean allLettersOrDigits = newText.chars().allMatch(x -> Character.isLetterOrDigit(x)); if (!allLettersOrDigits) { return "Nur Buchstaben und Zahlen erlaubt"; } boolean isFree = User.verifyUsernameNotTaken(newText); if (!isFree) { return "Benuterzname vergeben (evtl. für gelöschten Benutzer)"; } return null; } }; InputDialog id = new InputDialog(Hub.getActiveShell(), "Benutzernamen festlegen", "Benutzernamen festlegen - dieser kann nicht mehr geändert, sowie zukünftig anderweitig verwendet werden.", null, iiv); int retVal = id.open(); if (retVal == Dialog.OK) { User newUser = new User(null, id.getValue(), ""); updateUserList(); tableViewerUsers.setSelection(new StructuredSelection(newUser)); } } }; popManager.add(addUserAction); deleteUserAction = new LockedRestrictedAction<User>(AccessControlDefaults.USER_DELETE, Messages.LabGroupPrefs_delete) { @Override public User getTargetedObject(){ if (tableViewerUsers == null) { return null; } StructuredSelection ss = (StructuredSelection) tableViewerUsers.getSelection(); return (ss != null) ? (User) ss.getFirstElement() : null; } @Override public void doRun(User user){ IUser currentUser = ContextServiceHolder.get().getActiveUser().orElse(null); if (currentUser != null) { if (currentUser.getId().equals(user.getId())) { MessageDialog.openWarning(getShell(), "Warnung", "Dieser Benutzer ist gerade eingeloggt und kann daher nicht entfernt werden!"); } else { user.delete(); updateUserList(); wvUser.setValue(null); wvAnwender.setValue(null); } } } }; popManager.add(deleteUserAction); if (!(ConnectionStatus.STANDALONE == ElexisServerServiceHolder.get() .getConnectionStatus())) { lockUserAction = new RestrictedAction(AccessControlDefaults.USER_CREATE, Messages.Leistungscodes_editItem) { @Override public void doRun(){ StructuredSelection ss = (StructuredSelection) tableViewerUsers.getSelection(); User u = (User) ss.getFirstElement(); LockResponse acquireLock = LocalLockServiceHolder.get().acquireLock(u); if (acquireLock.isOk()) { setUnlocked(true); } } @Override public ImageDescriptor getImageDescriptor(){ return Images.IMG_LOCK_OPEN.getImageDescriptor(); } }; popManager.add(lockUserAction); } popManager.addMenuListener(new IMenuListener() { @Override public void menuAboutToShow(IMenuManager manager){ addUserAction.reflectRight(); deleteUserAction.reflectRight(); if (lockUserAction != null) { lockUserAction.reflectRight(); } } }); SashForm sash = new SashForm(container, SWT.HORIZONTAL); sash.setLayout(new GridLayout(2, false)); sash.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1)); Composite compositeLeft = new Composite(sash, SWT.NONE); compositeLeft.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1)); GridLayout gl_compositeLeft = new GridLayout(1, false); gl_compositeLeft.marginWidth = 0; gl_compositeLeft.marginHeight = 0; compositeLeft.setLayout(gl_compositeLeft); Composite compositeButtons = new Composite(compositeLeft, SWT.None); compositeButtons.setLayout(new FillLayout(SWT.HORIZONTAL)); compositeButtons.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); Button btnAdd = new Button(compositeButtons, SWT.FLAT); btnAdd.setImage(Images.IMG_NEW.getImage()); btnAdd.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e){ addUserAction.doRun(); } }); if (!(ConnectionStatus.STANDALONE == ElexisServerServiceHolder.get() .getConnectionStatus())) { Button btnLock = new Button(compositeButtons, SWT.FLAT | SWT.TOGGLE); btnLock.setSelection( LocalLockServiceHolder.get().isLocked((IPersistentObject) wvUser.getValue())); btnLock.setImage(Images.IMG_LOCK_OPEN.getImage()); btnLock.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e){ IPersistentObject user = (IPersistentObject) wvUser.getValue(); if (LocalLockServiceHolder.get().isLocked(user)) { LocalLockServiceHolder.get().releaseLock(user); } else { lockUserAction.doRun(); } boolean locked = LocalLockServiceHolder.get() .isLocked((IPersistentObject) wvUser.getValue()); btnLock.setSelection(locked); setUnlocked(locked); } }); } Composite compositeSelectorTable = new Composite(compositeLeft, SWT.NONE); compositeSelectorTable.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); TableColumnLayout tcl_compositeSelectorTable = new TableColumnLayout(); compositeSelectorTable.setLayout(tcl_compositeSelectorTable); Composite compositeEdit = new Composite(sash, SWT.NONE); GridLayout gl_compositeEdit = new GridLayout(2, false); gl_compositeEdit.horizontalSpacing = 0; gl_compositeEdit.verticalSpacing = 0; gl_compositeEdit.marginWidth = 0; gl_compositeEdit.marginHeight = 0; compositeEdit.setLayout(gl_compositeEdit); compositeEdit.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); userInfoLabel = new Label(compositeEdit, SWT.NONE); userInfoLabel.setForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE)); userInfoLabel.setBackground(SWTResourceManager.getColor(SWT.COLOR_WIDGET_BORDER)); userInfoLabel.setFont(SWTResourceManager.getFont(".AppleSystemUIFont", 14, SWT.BOLD)); userInfoLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); new Label(compositeEdit, SWT.None); tableViewerUsers = new TableViewer(compositeSelectorTable, SWT.BORDER | SWT.FULL_SELECTION); tableViewerUsers.setContentProvider(ArrayContentProvider.getInstance()); Table tableUsers = tableViewerUsers.getTable(); tableUsers.setLinesVisible(true); tableViewerUsers.addSelectionChangedListener(e -> { releaseLockIfRequired(); StructuredSelection ss = (StructuredSelection) e.getSelection(); wvUser.setValue(ss == null ? null : (User) ss.getFirstElement()); setUnlocked(ConnectionStatus.STANDALONE == ElexisServerServiceHolder.get() .getConnectionStatus()); compositeEdit.layout(true, true); }); TableViewerColumn tableViewerColumnName = new TableViewerColumn(tableViewerUsers, SWT.NONE); TableColumn tblclmnName = tableViewerColumnName.getColumn(); tcl_compositeSelectorTable.setColumnData(tblclmnName, new ColumnWeightData(100)); tableViewerColumnName.setLabelProvider(new AnwenderCellLabelProvider()); Menu menu = popManager.createContextMenu(tableUsers); tableUsers.setMenu(menu); new Label(compositeEdit, SWT.NONE); new Label(compositeEdit, SWT.NONE); Group grpSysAccess = new Group(compositeEdit, SWT.NONE); grpSysAccess.setText("Systemzugang"); grpSysAccess.setLayout(new GridLayout(3, true)); grpSysAccess.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1)); linkChangePassword = new Link(grpSysAccess, SWT.NONE); linkChangePassword.setText("<a>Passwort ändern</a>"); linkChangePassword.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); linkChangePassword.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e){ User user = wvUser.getValue(); if (user == null) { return; } new ChangePasswordDialog(UiDesk.getTopShell(), user).open(); } }); btnUserIsAdmin = new Button(grpSysAccess, SWT.CHECK); btnUserIsAdmin.setToolTipText("Administratoren unterliegen keinerlei Beschränkungen."); btnUserIsAdmin.setText("Administrator"); btnUserIsLocked = new Button(grpSysAccess, SWT.CHECK); btnUserIsLocked.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false, 1, 1)); btnUserIsLocked.setToolTipText("Sperrt die Möglichkeit sich am System anzumelden."); btnUserIsLocked.setText("Zugang sperren"); linkTotp = new Link(grpSysAccess, SWT.NONE); linkTotp.setText("<a>Einmalkennwort</a>"); linkTotp.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e){ User user = wvUser.getValue(); if (user == null) { return; } new TotpDialog(UiDesk.getTopShell(), user).open(); } }); btnAllowExternalAccess = new Button(grpSysAccess, SWT.CHECK); btnAllowExternalAccess.setToolTipText( "Diese Option aktiviert den Zugriff über die Schnittstellen des Elexis-Servers"); btnAllowExternalAccess.setText("Externer Zugriff"); new Label(grpSysAccess, SWT.NONE); btnAllowExternalAccess.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e){ User user = wvUser.getValue(); if (user == null) { return; } if (((Button) e.getSource()).getSelection()) { MessageDialog.openInformation(UiDesk.getTopShell(), "Aktivierung des externen Zugangs", "Um den externen Zugang zu aktivieren, muss ein starkes Passwort gesetzt, sowie das Einmalkennwort konfiguriert sein. Dies geschieht in den folgenden Dialogen."); int password = new ChangePasswordDialog(UiDesk.getTopShell(), user).open(); if (password != Dialog.OK) { MessageDialog.openError(UiDesk.getTopShell(), "Starkes Passwort benötigt", "Für den externen Zugriff wird ein starkes Passwort benötigt."); } else { new TotpDialog(UiDesk.getTopShell(), user).open(); user.set(User.FLD_ALLOW_EXTERNAL, StringConstants.ONE); } } else { user.set(User.FLD_ALLOW_EXTERNAL, StringConstants.ZERO); } btnAllowExternalAccess .setSelection(user.get(User.FLD_ALLOW_EXTERNAL).equals(StringConstants.ONE)); }; }); grpAccounting = new Group(compositeEdit, SWT.NONE); grpAccounting.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, true, 2, 1)); grpAccounting.setText("Verrechnung"); GridLayout gl_grpAccounting = new GridLayout(1, false); gl_grpAccounting.marginHeight = 5; grpAccounting.setLayout(gl_grpAccounting); Composite compositeContact = new Composite(grpAccounting, SWT.NONE); GridLayout gl_compositeContact = new GridLayout(2, false); gl_compositeContact.horizontalSpacing = 0; gl_compositeContact.verticalSpacing = 0; gl_compositeContact.marginWidth = 0; gl_compositeContact.marginHeight = 0; compositeContact.setLayout(gl_compositeContact); compositeContact.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1)); Label lblKontakt = new Label(compositeContact, SWT.NONE); lblKontakt.setText("Kontakt: "); linkContact = new Link(compositeContact, SWT.NONE); linkContact.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); linkContact.setText("nicht gesetzt " + CHANGE_LINK); linkContact.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e){ User user = (User) wvUser.getValue(); if (user == null) { return; } KontaktSelektor ks = new KontaktSelektor(UiDesk.getTopShell(), Person.class, "Kontakt auswählen", "Bitte selektieren Sie den zugeordneten Kontakt", new String[] {}); int ret = ks.open(); if (ret == Window.OK) { Person p = (Person) ks.getSelection(); p.set(Anwender.FLD_IS_USER, StringConstants.ONE); user.setAssignedContact(p); linkContact.setText(p.getPersonalia() + " " + CHANGE_LINK); } } }); Composite compositeIsRespPhys = new Composite(grpAccounting, SWT.BORDER); compositeIsRespPhys.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1)); GridLayout gl_compositeIsRespPhys = new GridLayout(2, false); gl_compositeIsRespPhys.marginHeight = 0; compositeIsRespPhys.setLayout(gl_compositeIsRespPhys); lblRespPhysColor = new Label(compositeIsRespPhys, SWT.NONE); lblRespPhysColor.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1)); lblRespPhysColor.setText("zugeordnete Farbe"); lblRespPhysColorDefColor = lblRespPhysColor.getBackground(); lblRespPhysColor.addMouseListener(new MouseAdapter() { @Override public void mouseDown(MouseEvent e){ if (!btnIsExecutiveDoctor.getSelection()) { return; } ColorDialog cd = new ColorDialog(UiDesk.getTopShell()); cd.setRGB(lblRespPhysColor.getBackground().getRGB()); cd.setText(Messages.UserManagementPreferencePage_MandatorColorSelectTitle); RGB rgb = cd.open(); User user = (User) wvUser.getValue(); Mandant m = Mandant.load(user.getAssignedContactId()); UiMandant.setColorForMandator(m, rgb); lblRespPhysColor.setBackground(UiMandant.getColorForMandator(m)); updateUserList(); } }); Label lblRechnungssteller = new Label(compositeIsRespPhys, SWT.NONE); lblRechnungssteller.setText("Rechnungssteller:"); linkRechnungssteller = new Link(compositeIsRespPhys, SWT.NONE); linkRechnungssteller.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1)); linkRechnungssteller.setText("nicht gesetzt " + CHANGE_LINK); linkRechnungssteller.setToolTipText("Set the invoice contact for this mandator"); linkRechnungssteller.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e){ User user = (User) wvUser.getValue(); if (user == null) { return; } Anwender ac = user.getAssignedContact(); if (ac == null || !ac.isExecutiveDoctor()) { MessageDialog.openWarning(UiDesk.getTopShell(), "Fehler", "Der selektierte Kontakt ist kein Mandant."); return; } KontaktSelektor ks = new KontaktSelektor(UiDesk.getTopShell(), Kontakt.class, "Rechnungs-Kontakt auswählen", "Bitte selektieren Sie den dem Mandant zugeordneten Rechnungs-Kontakt", new String[] {}); int ret = ks.open(); if (ret == Window.OK) { Kontakt kontakt = (Kontakt) ks.getSelection(); if (kontakt == null) return; Mandant mand = Mandant.load(ac.getId()); mand.setRechnungssteller(kontakt); linkRechnungssteller .setText(mand.getRechnungssteller().getLabel() + " " + CHANGE_LINK); } } }); Composite compositeMandator = new Composite(grpAccounting, SWT.NONE); GridLayout gl_compositeMandator = new GridLayout(2, true); gl_compositeMandator.verticalSpacing = 0; gl_compositeMandator.horizontalSpacing = 0; gl_compositeMandator.marginHeight = 0; gl_compositeMandator.marginWidth = 0; compositeMandator.setLayout(gl_compositeMandator); compositeMandator.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1)); btnIsExecutiveDoctor = new Button(compositeMandator, SWT.CHECK); btnIsExecutiveDoctor.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false, 1, 1)); btnIsExecutiveDoctor.setText("ist verantwortlicher Arzt"); btnIsExecutiveDoctor.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e){ if (btnIsExecutiveDoctor.getSelection()) { User user = (User) wvUser.getValue(); if (user == null) { return; } Anwender ac = user.getAssignedContact(); if (ac == null) { return; } if (!ac.isExecutiveDoctor()) { boolean changeIt = MessageDialog.openQuestion(UiDesk.getTopShell(), "Kontakt ist kein Mandant", "Der selektierte Kontakt ist kein Mandant. Wollen Sie diesen Kontakt in einen Mandanten ändern?"); if (changeIt) { ac.setExecutiveDoctor(true); } else { btnIsExecutiveDoctor.setSelection(false); } } } }; }); btnMandatorIsInactive = new Button(compositeMandator, SWT.CHECK); btnMandatorIsInactive.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); btnMandatorIsInactive.setText("ehemalig (Verrechn. sperren)"); btnMandatorIsInactive.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e){ User user = (User) wvUser.getValue(); if (user == null) { return; } Mandant mandant = Mandant.load(user.getAssignedContactId()); if (!mandant.exists() || !mandant.isValid()) { return; } mandant.setInactive(btnMandatorIsInactive.getSelection()); } }); Composite compositeAccounting = new Composite(grpAccounting, SWT.NONE); compositeAccounting.setLayout(new GridLayout(2, true)); compositeAccounting.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1)); Group grpAssociation = new Group(compositeAccounting, SWT.NONE); grpAssociation.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); grpAssociation.setText("tätig für"); GridLayout gl_grp = new GridLayout(2, false); gl_grp.marginHeight = 0; grpAssociation.setLayout(gl_grp); Composite compositeAssociation = new Composite(grpAssociation, SWT.NONE); compositeAssociation.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1)); TableColumnLayout tcl_compositeAssociation = new TableColumnLayout(); compositeAssociation.setLayout(tcl_compositeAssociation); checkboxTableViewerAssociation = CheckboxTableViewer.newCheckList(compositeAssociation, SWT.BORDER | SWT.FULL_SELECTION); checkboxTableViewerAssociation.addCheckStateListener((e) -> { Mandant m = (Mandant) e.getElement(); if (m == null) return; User user = (User) wvUser.getValue(); Anwender anw = user.getAssignedContact(); if (anw != null) { anw.addOrRemoveExecutiveDoctorWorkingFor(m, e.getChecked()); } else { SWTHelper.showError("No contact assigned", "There is no contact assigned to user " + user.getLabel()); } }); MenuManager menuManager = new MenuManager(); menuManager.setRemoveAllWhenShown(true); menuManager.addMenuListener(new IMenuListener() { @Override public void menuAboutToShow(IMenuManager manager){ IStructuredSelection selection = checkboxTableViewerAssociation.getStructuredSelection(); if (!selection.isEmpty()) { Object selected = selection.getFirstElement(); if (selected instanceof Mandant) { User user = (User) wvUser.getValue(); if (user != null) { Anwender anw = user.getAssignedContact(); if (anw != null) { Mandant stdWorkingFor = anw.getStdExecutiveDoctorWorkingFor(); if (stdWorkingFor != null && stdWorkingFor.equals(selected)) { manager.add(new Action() { public String getText(){ return "Std. Mandant entfernen"; }; public void run(){ anw.setStdExecutiveDoctorWorkingFor(null); checkboxTableViewerAssociation.refresh(); }; }); } else { manager.add(new Action() { public String getText(){ return "Std. Mandant setzen"; }; public void run(){ anw.setStdExecutiveDoctorWorkingFor((Mandant) selected); checkboxTableViewerAssociation.refresh(); }; }); } } } } } } }); Menu contextMenu = menuManager.createContextMenu(checkboxTableViewerAssociation.getTable()); checkboxTableViewerAssociation.getTable().setMenu(contextMenu); Group grpRoles = new Group(compositeAccounting, SWT.NONE); grpRoles.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); grpRoles.setText("Rollenzuordnung"); GridLayout gl_grpRoles = new GridLayout(2, false); gl_grpRoles.marginHeight = 0; grpRoles.setLayout(gl_grpRoles); Composite compositeRoles = new Composite(grpRoles, SWT.NONE); compositeRoles.setLayout(new FillLayout(SWT.HORIZONTAL)); compositeRoles.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1)); checkboxTableViewerRoles = CheckboxTableViewer.newCheckList(compositeRoles, SWT.BORDER | SWT.FULL_SELECTION); new Label(compositeEdit, SWT.NONE); new Label(compositeEdit, SWT.NONE); checkboxTableViewerRoles.setContentProvider(ArrayContentProvider.getInstance()); checkboxTableViewerRoles.setLabelProvider(new DefaultLabelProvider() { @Override public String getColumnText(Object element, int columnIndex){ Role r = (Role) element; return r.getTranslatedLabel() != null ? r.getTranslatedLabel() : r.getId(); } }); checkboxTableViewerRoles.addCheckStateListener((e) -> { Role r = (Role) e.getElement(); if (r == null) return; User user = (User) wvUser.getValue(); user.setAssignedRole(r, e.getChecked()); }); checkboxTableViewerAssociation.setContentProvider(ArrayContentProvider.getInstance()); checkboxTableViewerAssociation.setLabelProvider(new DefaultLabelProvider() { @Override public String getColumnText(Object element, int columnIndex){ Mandant stdWorkingFor = null; User user = (User) wvUser.getValue(); if (user != null) { Anwender anw = user.getAssignedContact(); if (anw != null) { stdWorkingFor = anw.getStdExecutiveDoctorWorkingFor(); } } Mandant m = (Mandant) element; return (m.equals(stdWorkingFor) ? "* " : "") + m.getName() + " " + m.getVorname(); } }); checkboxTableViewerAssociation.setComparator(new MandantViewerComparator(checkboxTableViewerAssociation)); updateRoles(); updateAssociations(); initDataBindings(); wvUser.addValueChangeListener(new ValueChangedAdapter()); updateUserList(); setUnlocked( ConnectionStatus.STANDALONE == ElexisServerServiceHolder.get().getConnectionStatus()); sash.setWeights(new int[] { 1, 5 }); return container; } /** * Initialize the preference page. */ @Override public void init(IWorkbench workbench){ // Initialize the preference page } private void updateUserList(){ List<User> query = new Query<User>(User.class).execute(); query.sort((u1, u2) -> u1.getLabel().compareTo(u2.getLabel())); tableViewerUsers.setInput(query); } private class ValueChangedAdapter implements IValueChangeListener<User> { @Override public void handleValueChange(ValueChangeEvent event){ User user = (User) wvUser.getValue(); if (user == null) { wvAnwender.setValue(null); return; } setErrorMessage(null); Anwender anw = user.getAssignedContact(); wvAnwender.setValue(anw); String text = (anw != null) ? anw.getPersonalia() : "Nicht gesetzt"; linkContact.setText(text + " " + CHANGE_LINK); userInfoLabel.setText(text + " [" + user.getId() + "]"); updateRoles(); Object[] assignedRoles = user.getAssignedRoles().toArray(); checkboxTableViewerRoles.setCheckedElements(assignedRoles); updateAssociations(); btnAllowExternalAccess .setSelection(user.get(User.FLD_ALLOW_EXTERNAL).equals(StringConstants.ONE)); if (anw != null) { Mandant mandator = Mandant.load(anw.getId()); if (mandator.exists() && mandator.isValid()) { btnMandatorIsInactive.setSelection(mandator.isInactive()); } } linkRechnungssteller.setText("- " + CHANGE_LINK); lblRespPhysColor.setBackground(lblRespPhysColorDefColor); if (anw != null) { checkboxTableViewerAssociation .setCheckedElements(anw.getExecutiveDoctorsWorkingFor().toArray()); if (anw.isExecutiveDoctor()) { Mandant m = Mandant.load(anw.getId()); Color color = UiMandant.getColorForMandator(m); lblRespPhysColor.setBackground(color); Rechnungssteller rs = m.getRechnungssteller(); String rst = (rs != null) ? rs.getLabel() : "Nicht gesetzt"; linkRechnungssteller.setText(rst + " " + CHANGE_LINK); } } } } private void updateRoles(){ List<Role> roles = new Query<Role>(Role.class).execute(); checkboxTableViewerRoles.setInput(roles); } private void updateAssociations(){ checkboxTableViewerAssociation.setInput(new Query<Mandant>(Mandant.class).execute()); checkboxTableViewerAssociation.setCheckedElements(new Mandant[] {}); } private class AnwenderCellLabelProvider extends CellLabelProvider { @Override public void update(ViewerCell cell){ User user = (User) cell.getElement(); cell.setText(user.getLabel()); Anwender ac = user.getAssignedContact(); if (ac != null && ac.isExecutiveDoctor()) { Mandant m = Mandant.load(ac.getId()); Color mc = UiMandant.getColorForMandator(m); cell.setImage(MandantSelectionContributionItem.getBoxSWTColorImage(mc)); } else { cell.setImage(Images.IMG_EMPTY_TRANSPARENT.getImage()); } if (user.isAdministrator()) { cell.setForeground(UiDesk.getColor(UiDesk.COL_RED)); cell.setImage(Images.IMG_AUSRUFEZ.getImage()); } } } protected DataBindingContext initDataBindings(){ DataBindingContext bindingContext = new DataBindingContext(); IObservableValue observeSelectionBtnIsAdminObserveWidget = WidgetProperties.selection().observe(btnUserIsAdmin); IObservableValue wvAdminObserveDetailValue = PojoProperties.value(User.class, "administrator", Boolean.class).observeDetail(wvUser); bindingContext.bindValue(observeSelectionBtnIsAdminObserveWidget, wvAdminObserveDetailValue, null, null); IObservableValue observeSelectionBtnIsMandatorObserveWidget = WidgetProperties.selection().observe(btnIsExecutiveDoctor); IObservableValue wvMandatorObserveDetailValue = PojoProperties .value(Anwender.class, "executiveDoctor", Boolean.class).observeDetail(wvAnwender); bindingContext.bindValue(observeSelectionBtnIsMandatorObserveWidget, wvMandatorObserveDetailValue, null, null); IObservableValue observeSelectionBtnIsActiveObserveWidget = WidgetProperties.selection().observe(btnUserIsLocked); IObservableValue wvActiveObserveDetailValue = PojoProperties.value(User.class, "active", Boolean.class).observeDetail(wvUser); bindingContext.bindValue(observeSelectionBtnIsActiveObserveWidget, wvActiveObserveDetailValue, new UpdateValueStrategy().setConverter(new BooleanNotConverter()), new UpdateValueStrategy().setConverter(new BooleanNotConverter())); return bindingContext; } @Override protected void performApply(){ releaseLockIfRequired(); super.performApply(); } @Override public boolean performOk(){ releaseLockIfRequired(); return super.performOk(); } @Override public boolean performCancel(){ releaseLockIfRequired(); return super.performCancel(); } private void releaseLockIfRequired(){ User user = (User) wvUser.getValue(); if (user != null && LocalLockServiceHolder.get().isLocked(user)) { LocalLockServiceHolder.get().releaseLock(user); } } @Override public void setUnlocked(boolean unlocked){ btnAllowExternalAccess.setEnabled(unlocked); btnIsExecutiveDoctor.setEnabled(unlocked); linkChangePassword.setEnabled(unlocked); linkContact.setEnabled(unlocked); linkTotp.setEnabled(unlocked); linkRechnungssteller.setEnabled(unlocked); btnUserIsAdmin.setEnabled(unlocked); btnUserIsLocked.setEnabled(unlocked); checkboxTableViewerAssociation.getTable().setEnabled(unlocked); checkboxTableViewerRoles.getTable().setEnabled(unlocked); lblRespPhysColor.setEnabled(unlocked); } public class MandantViewerComparator extends ViewerComparator{ public MandantViewerComparator(Viewer viewer) {} public int compare(Viewer viewer, Object o1, Object o2) { Mandant m1 = (Mandant) o1; Mandant m2 = (Mandant) o2; return m1.getName().compareToIgnoreCase(m2.getName()); } } }
package org.project.openbaton.nfvo.catalogue.mano.common; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Version; import org.project.openbaton.nfvo.catalogue.util.IdGenerator; import java.io.Serializable; @Entity public class AutoScalePolicy implements Serializable{ @Id private String id = IdGenerator.createUUID(); @Version private int version = 0; private String action; private String metric; private String statistic; private String comparisonOperator; private int period; private int threshold; private int cooldown; public String getMetric() { return metric; } public void setMetric(String metric) { this.metric = metric; } public int getPeriod() { return period; } public void setPeriod(int period) { this.period = period; } public int getThreshold() { return threshold; } public void setThreshold(int threshold) { this.threshold = threshold; } public int getCooldown() { return cooldown; } public void setCooldown(int cooldown) { this.cooldown = cooldown; } public String getStatistic() { return statistic; } public void setStatistic(String statistic) { this.statistic = statistic; } public String getComparisonOperator() { return comparisonOperator; } public void setComparisonOperator(String comparisonOperator) { this.comparisonOperator = comparisonOperator; } public String getId() { return id; } public String getAction() { return action; } public void setAction(String action) { this.action = action; } }
package org.chromium.chrome.browser.contextualsearch; import android.util.Pair; import org.chromium.base.metrics.RecordHistogram; import org.chromium.chrome.browser.compositor.bottombar.contextualsearch.ContextualSearchPanel.PanelState; import org.chromium.chrome.browser.compositor.bottombar.contextualsearch.ContextualSearchPanel.StateChangeReason; import org.chromium.chrome.browser.preferences.PrefServiceBridge; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; /** * Centralizes UMA data collection for Contextual Search. All calls must be made from the UI thread. */ public class ContextualSearchUma { // An invalid value for the number of taps remaining for the promo. Must be negative. private static final int PROMO_TAPS_REMAINING_INVALID = -1; // Constants to use for the original selection gesture private static final boolean LONG_PRESS = false; private static final boolean TAP = true; // Constants used to log UMA "enum" histograms about the Contextual Search's preference state. private static final int PREFERENCE_UNINITIALIZED = 0; private static final int PREFERENCE_ENABLED = 1; private static final int PREFERENCE_DISABLED = 2; private static final int PREFERENCE_HISTOGRAM_BOUNDARY = 3; // Constants used to log UMA "enum" histograms about whether search results were seen. private static final int RESULTS_SEEN = 0; private static final int RESULTS_NOT_SEEN = 1; private static final int RESULTS_SEEN_BOUNDARY = 2; // Constants used to log UMA "enum" histograms about whether the selection is valid. private static final int SELECTION_VALID = 0; private static final int SELECTION_INVALID = 1; private static final int SELECTION_BOUNDARY = 2; // Constants used to log UMA "enum" histograms about a request's outcome. private static final int REQUEST_NOT_FAILED = 0; private static final int REQUEST_FAILED = 1; private static final int REQUEST_BOUNDARY = 2; // Constants used to log UMA "enum" histograms about the panel's state transitions. // Entry code: first entry into CLOSED. private static final int ENTER_CLOSED_FROM_OTHER = 0; private static final int ENTER_CLOSED_FROM_PEEKED_BACK_PRESS = 1; private static final int ENTER_CLOSED_FROM_PEEKED_BASE_PAGE_SCROLL = 2; private static final int ENTER_CLOSED_FROM_PEEKED_TEXT_SELECT_TAP = 3; private static final int ENTER_CLOSED_FROM_EXPANDED_BACK_PRESS = 4; private static final int ENTER_CLOSED_FROM_EXPANDED_BASE_PAGE_TAP = 5; private static final int ENTER_CLOSED_FROM_EXPANDED_FLING = 6; private static final int ENTER_CLOSED_FROM_MAXIMIZED_BACK_PRESS = 7; private static final int ENTER_CLOSED_FROM_MAXIMIZED_FLING = 8; private static final int ENTER_CLOSED_FROM_MAXIMIZED_TAB_PROMOTION = 9; private static final int ENTER_CLOSED_FROM_MAXIMIZED_SERP_NAVIGATION = 10; private static final int ENTER_CLOSED_FROM_BOUNDARY = 11; // Entry code: first entry into PEEKED. private static final int ENTER_PEEKED_FROM_OTHER = 0; private static final int ENTER_PEEKED_FROM_CLOSED_TEXT_SELECT_TAP = 1; private static final int ENTER_PEEKED_FROM_CLOSED_EXT_SELECT_LONG_PRESS = 2; private static final int ENTER_PEEKED_FROM_PEEKED_TEXT_SELECT_TAP = 3; private static final int ENTER_PEEKED_FROM_PEEKED_TEXT_SELECT_LONG_PRESS = 4; private static final int ENTER_PEEKED_FROM_EXPANDED_SEARCH_BAR_TAP = 5; private static final int ENTER_PEEKED_FROM_EXPANDED_SWIPE = 6; private static final int ENTER_PEEKED_FROM_EXPANDED_FLING = 7; private static final int ENTER_PEEKED_FROM_MAXIMIZED_SWIPE = 8; private static final int ENTER_PEEKED_FROM_MAXIMIZED_FLING = 9; private static final int ENTER_PEEKED_FROM_BOUNDARY = 10; // Entry code: first entry into EXPANDED. private static final int ENTER_EXPANDED_FROM_OTHER = 0; private static final int ENTER_EXPANDED_FROM_PEEKED_SEARCH_BAR_TAP = 1; private static final int ENTER_EXPANDED_FROM_PEEKED_SWIPE = 2; private static final int ENTER_EXPANDED_FROM_PEEKED_FLING = 3; private static final int ENTER_EXPANDED_FROM_MAXIMIZED_SWIPE = 4; private static final int ENTER_EXPANDED_FROM_MAXIMIZED_FLING = 5; private static final int ENTER_EXPANDED_FROM_BOUNDARY = 6; // Entry code: first entry into MAXIMIZED. private static final int ENTER_MAXIMIZED_FROM_OTHER = 0; private static final int ENTER_MAXIMIZED_FROM_PEEKED_SWIPE = 1; private static final int ENTER_MAXIMIZED_FROM_PEEKED_FLING = 2; private static final int ENTER_MAXIMIZED_FROM_EXPANDED_SWIPE = 3; private static final int ENTER_MAXIMIZED_FROM_EXPANDED_FLING = 4; private static final int ENTER_MAXIMIZED_FROM_EXPANDED_SERP_NAVIGATION = 5; private static final int ENTER_MAXIMIZED_FROM_BOUNDARY = 6; // Exit code: first exit from CLOSED (or UNDEFINED). private static final int EXIT_CLOSED_TO_OTHER = 0; private static final int EXIT_CLOSED_TO_PEEKED_TEXT_SELECT_TAP = 1; private static final int EXIT_CLOSED_TO_PEEKED_TEXT_SELECT_LONG_PRESS = 2; private static final int EXIT_CLOSED_TO_BOUNDARY = 3; // Exit code: first exit from PEEKED. private static final int EXIT_PEEKED_TO_OTHER = 0; private static final int EXIT_PEEKED_TO_CLOSED_BACK_PRESS = 1; private static final int EXIT_PEEKED_TO_CLOSED_BASE_PAGE_SCROLL = 2; private static final int EXIT_PEEKED_TO_CLOSED_TEXT_SELECT_TAP = 3; private static final int EXIT_PEEKED_TO_PEEKED_TEXT_SELECT_TAP = 4; private static final int EXIT_PEEKED_TO_PEEKED_TEXT_SELECT_LONG_PRESS = 5; private static final int EXIT_PEEKED_TO_EXPANDED_SEARCH_BAR_TAP = 6; private static final int EXIT_PEEKED_TO_EXPANDED_SWIPE = 7; private static final int EXIT_PEEKED_TO_EXPANDED_FLING = 8; private static final int EXIT_PEEKED_TO_MAXIMIZED_SWIPE = 9; private static final int EXIT_PEEKED_TO_MAXIMIZED_FLING = 10; private static final int EXIT_PEEKED_TO_BOUNDARY = 11; // Exit code: first exit from EXPANDED. private static final int EXIT_EXPANDED_TO_OTHER = 0; private static final int EXIT_EXPANDED_TO_CLOSED_BACK_PRESS = 1; private static final int EXIT_EXPANDED_TO_CLOSED_BASE_PAGE_TAP = 2; private static final int EXIT_EXPANDED_TO_CLOSED_FLING = 3; private static final int EXIT_EXPANDED_TO_PEEKED_SEARCH_BAR_TAP = 4; private static final int EXIT_EXPANDED_TO_PEEKED_SWIPE = 5; private static final int EXIT_EXPANDED_TO_PEEKED_FLING = 6; private static final int EXIT_EXPANDED_TO_MAXIMIZED_SWIPE = 7; private static final int EXIT_EXPANDED_TO_MAXIMIZED_FLING = 8; private static final int EXIT_EXPANDED_TO_MAXIMIZED_SERP_NAVIGATION = 9; private static final int EXIT_EXPANDED_TO_BOUNDARY = 10; // Exit code: first exit from MAXIMIZED. private static final int EXIT_MAXIMIZED_TO_OTHER = 0; private static final int EXIT_MAXIMIZED_TO_CLOSED_BACK_PRESS = 1; private static final int EXIT_MAXIMIZED_TO_CLOSED_FLING = 2; private static final int EXIT_MAXIMIZED_TO_CLOSED_TAB_PROMOTION = 3; private static final int EXIT_MAXIMIZED_TO_CLOSED_SERP_NAVIGATION = 4; private static final int EXIT_MAXIMIZED_TO_PEEKED_SWIPE = 5; private static final int EXIT_MAXIMIZED_TO_PEEKED_FLING = 6; private static final int EXIT_MAXIMIZED_TO_EXPANDED_SWIPE = 7; private static final int EXIT_MAXIMIZED_TO_EXPANDED_FLING = 8; private static final int EXIT_MAXIMIZED_TO_BOUNDARY = 9; // Constants used to log UMA "enum" histograms with details about whether search results // were seen, and what the original triggering gesture was. private static final int RESULTS_SEEN_FROM_TAP = 0; private static final int RESULTS_NOT_SEEN_FROM_TAP = 1; private static final int RESULTS_SEEN_FROM_LONG_PRESS = 2; private static final int RESULTS_NOT_SEEN_FROM_LONG_PRESS = 3; private static final int RESULTS_BY_GESTURE_BOUNDARY = 4; // Constants used to log UMA "enum" histograms with details about whether search results // were seen, and what the original triggering gesture was. private static final int PROMO_ENABLED_FROM_TAP = 0; private static final int PROMO_DISABLED_FROM_TAP = 1; private static final int PROMO_UNDECIDED_FROM_TAP = 2; private static final int PROMO_ENABLED_FROM_LONG_PRESS = 3; private static final int PROMO_DISABLED_FROM_LONG_PRESS = 4; private static final int PROMO_UNDECIDED_FROM_LONG_PRESS = 5; private static final int PROMO_BY_GESTURE_BOUNDARY = 6; // Constants used to log UMA "enum" histograms with summary counts for SERP loading times. private static final int PREFETCHED_PARIALLY_LOADED = 0; private static final int PREFETCHED_FULLY_LOADED = 1; private static final int NOT_PREFETCHED = 2; private static final int PREFETCH_BOUNDARY = 3; // Constants used to log UMA "enum" histograms for HTTP / HTTPS. private static final int PROTOCOL_IS_HTTP = 0; private static final int PROTOCOL_NOT_HTTP = 1; private static final int PROTOCOL_BOUNDARY = 2; // Constants used to log UMA "enum" histograms for single / multi-word. private static final int RESOLVED_SINGLE_WORD = 0; private static final int RESOLVED_MULTI_WORD = 1; private static final int RESOLVED_BOUNDARY = 2; /** * Key used in maps from {state, reason} to state entry (exit) logging code. */ static class StateChangeKey { final PanelState mState; final StateChangeReason mReason; final int mHashCode; StateChangeKey(PanelState state, StateChangeReason reason) { mState = state; mReason = reason; mHashCode = 31 * state.hashCode() + reason.hashCode(); } @Override public boolean equals(Object obj) { if (!(obj instanceof StateChangeKey)) { return false; } if (obj == this) { return true; } StateChangeKey other = (StateChangeKey) obj; return mState.equals(other.mState) && mReason.equals(other.mReason); } @Override public int hashCode() { return mHashCode; } } // TODO(donnd): switch from using Maps to some method that does not require creation of a key. // Entry code map: first entry into CLOSED. private static final Map<StateChangeKey, Integer> ENTER_CLOSED_STATE_CHANGE_CODES; static { Map<StateChangeKey, Integer> codes = new HashMap<StateChangeKey, Integer>(); codes.put(new StateChangeKey(PanelState.PEEKED, StateChangeReason.BACK_PRESS), ENTER_CLOSED_FROM_PEEKED_BACK_PRESS); codes.put(new StateChangeKey(PanelState.PEEKED, StateChangeReason.BASE_PAGE_SCROLL), ENTER_CLOSED_FROM_PEEKED_BASE_PAGE_SCROLL); codes.put(new StateChangeKey(PanelState.PEEKED, StateChangeReason.TEXT_SELECT_TAP), ENTER_CLOSED_FROM_PEEKED_TEXT_SELECT_TAP); codes.put(new StateChangeKey(PanelState.EXPANDED, StateChangeReason.BACK_PRESS), ENTER_CLOSED_FROM_EXPANDED_BACK_PRESS); codes.put(new StateChangeKey(PanelState.EXPANDED, StateChangeReason.BASE_PAGE_TAP), ENTER_CLOSED_FROM_EXPANDED_BASE_PAGE_TAP); codes.put(new StateChangeKey(PanelState.EXPANDED, StateChangeReason.FLING), ENTER_CLOSED_FROM_EXPANDED_FLING); codes.put(new StateChangeKey(PanelState.MAXIMIZED, StateChangeReason.BACK_PRESS), ENTER_CLOSED_FROM_MAXIMIZED_BACK_PRESS); codes.put(new StateChangeKey(PanelState.MAXIMIZED, StateChangeReason.FLING), ENTER_CLOSED_FROM_MAXIMIZED_FLING); codes.put(new StateChangeKey(PanelState.MAXIMIZED, StateChangeReason.TAB_PROMOTION), ENTER_CLOSED_FROM_MAXIMIZED_TAB_PROMOTION); codes.put(new StateChangeKey(PanelState.MAXIMIZED, StateChangeReason.SERP_NAVIGATION), ENTER_CLOSED_FROM_MAXIMIZED_SERP_NAVIGATION); ENTER_CLOSED_STATE_CHANGE_CODES = Collections.unmodifiableMap(codes); } // Entry code map: first entry into PEEKED. private static final Map<StateChangeKey, Integer> ENTER_PEEKED_STATE_CHANGE_CODES; static { Map<StateChangeKey, Integer> codes = new HashMap<StateChangeKey, Integer>(); // Note: we don't distinguish entering PEEKED from UNDEFINED / CLOSED. codes.put(new StateChangeKey(PanelState.UNDEFINED, StateChangeReason.TEXT_SELECT_TAP), ENTER_PEEKED_FROM_CLOSED_TEXT_SELECT_TAP); codes.put(new StateChangeKey(PanelState.UNDEFINED, StateChangeReason.TEXT_SELECT_LONG_PRESS), ENTER_PEEKED_FROM_CLOSED_EXT_SELECT_LONG_PRESS); codes.put(new StateChangeKey(PanelState.CLOSED, StateChangeReason.TEXT_SELECT_TAP), ENTER_PEEKED_FROM_CLOSED_TEXT_SELECT_TAP); codes.put(new StateChangeKey(PanelState.CLOSED, StateChangeReason.TEXT_SELECT_LONG_PRESS), ENTER_PEEKED_FROM_CLOSED_EXT_SELECT_LONG_PRESS); codes.put(new StateChangeKey(PanelState.PEEKED, StateChangeReason.TEXT_SELECT_TAP), ENTER_PEEKED_FROM_PEEKED_TEXT_SELECT_TAP); codes.put(new StateChangeKey(PanelState.PEEKED, StateChangeReason.TEXT_SELECT_LONG_PRESS), ENTER_PEEKED_FROM_PEEKED_TEXT_SELECT_LONG_PRESS); codes.put(new StateChangeKey(PanelState.EXPANDED, StateChangeReason.SEARCH_BAR_TAP), ENTER_PEEKED_FROM_EXPANDED_SEARCH_BAR_TAP); codes.put(new StateChangeKey(PanelState.EXPANDED, StateChangeReason.SWIPE), ENTER_PEEKED_FROM_EXPANDED_SWIPE); codes.put(new StateChangeKey(PanelState.EXPANDED, StateChangeReason.FLING), ENTER_PEEKED_FROM_EXPANDED_FLING); codes.put(new StateChangeKey(PanelState.MAXIMIZED, StateChangeReason.SWIPE), ENTER_PEEKED_FROM_MAXIMIZED_SWIPE); codes.put(new StateChangeKey(PanelState.MAXIMIZED, StateChangeReason.FLING), ENTER_PEEKED_FROM_MAXIMIZED_FLING); ENTER_PEEKED_STATE_CHANGE_CODES = Collections.unmodifiableMap(codes); } // Entry code map: first entry into EXPANDED. private static final Map<StateChangeKey, Integer> ENTER_EXPANDED_STATE_CHANGE_CODES; static { Map<StateChangeKey, Integer> codes = new HashMap<StateChangeKey, Integer>(); codes.put(new StateChangeKey(PanelState.PEEKED, StateChangeReason.SEARCH_BAR_TAP), ENTER_EXPANDED_FROM_PEEKED_SEARCH_BAR_TAP); codes.put(new StateChangeKey(PanelState.PEEKED, StateChangeReason.SWIPE), ENTER_EXPANDED_FROM_PEEKED_SWIPE); codes.put(new StateChangeKey(PanelState.PEEKED, StateChangeReason.FLING), ENTER_EXPANDED_FROM_PEEKED_FLING); codes.put(new StateChangeKey(PanelState.MAXIMIZED, StateChangeReason.SWIPE), ENTER_EXPANDED_FROM_MAXIMIZED_SWIPE); codes.put(new StateChangeKey(PanelState.MAXIMIZED, StateChangeReason.FLING), ENTER_EXPANDED_FROM_MAXIMIZED_FLING); ENTER_EXPANDED_STATE_CHANGE_CODES = Collections.unmodifiableMap(codes); } // Entry code map: first entry into MAXIMIZED. private static final Map<StateChangeKey, Integer> ENTER_MAXIMIZED_STATE_CHANGE_CODES; static { Map<StateChangeKey, Integer> codes = new HashMap<StateChangeKey, Integer>(); codes.put(new StateChangeKey(PanelState.PEEKED, StateChangeReason.SWIPE), ENTER_MAXIMIZED_FROM_PEEKED_SWIPE); codes.put(new StateChangeKey(PanelState.PEEKED, StateChangeReason.FLING), ENTER_MAXIMIZED_FROM_PEEKED_FLING); codes.put(new StateChangeKey(PanelState.EXPANDED, StateChangeReason.SWIPE), ENTER_MAXIMIZED_FROM_EXPANDED_SWIPE); codes.put(new StateChangeKey(PanelState.EXPANDED, StateChangeReason.FLING), ENTER_MAXIMIZED_FROM_EXPANDED_FLING); codes.put(new StateChangeKey(PanelState.EXPANDED, StateChangeReason.SERP_NAVIGATION), ENTER_MAXIMIZED_FROM_EXPANDED_SERP_NAVIGATION); ENTER_MAXIMIZED_STATE_CHANGE_CODES = Collections.unmodifiableMap(codes); } // Exit code map: first exit from CLOSED. private static final Map<StateChangeKey, Integer> EXIT_CLOSED_TO_STATE_CHANGE_CODES; static { Map<StateChangeKey, Integer> codes = new HashMap<StateChangeKey, Integer>(); codes.put(new StateChangeKey(PanelState.PEEKED, StateChangeReason.TEXT_SELECT_TAP), EXIT_CLOSED_TO_PEEKED_TEXT_SELECT_TAP); codes.put(new StateChangeKey(PanelState.PEEKED, StateChangeReason.TEXT_SELECT_LONG_PRESS), EXIT_CLOSED_TO_PEEKED_TEXT_SELECT_LONG_PRESS); EXIT_CLOSED_TO_STATE_CHANGE_CODES = Collections.unmodifiableMap(codes); } // Exit code map: first exit from PEEKED. private static final Map<StateChangeKey, Integer> EXIT_PEEKED_TO_STATE_CHANGE_CODES; static { Map<StateChangeKey, Integer> codes = new HashMap<StateChangeKey, Integer>(); codes.put(new StateChangeKey(PanelState.CLOSED, StateChangeReason.BACK_PRESS), EXIT_PEEKED_TO_CLOSED_BACK_PRESS); codes.put(new StateChangeKey(PanelState.CLOSED, StateChangeReason.BASE_PAGE_SCROLL), EXIT_PEEKED_TO_CLOSED_BASE_PAGE_SCROLL); codes.put(new StateChangeKey(PanelState.CLOSED, StateChangeReason.BASE_PAGE_TAP), EXIT_PEEKED_TO_CLOSED_TEXT_SELECT_TAP); codes.put(new StateChangeKey(PanelState.PEEKED, StateChangeReason.TEXT_SELECT_TAP), EXIT_PEEKED_TO_PEEKED_TEXT_SELECT_TAP); codes.put(new StateChangeKey(PanelState.PEEKED, StateChangeReason.TEXT_SELECT_LONG_PRESS), EXIT_PEEKED_TO_PEEKED_TEXT_SELECT_LONG_PRESS); codes.put(new StateChangeKey(PanelState.EXPANDED, StateChangeReason.SEARCH_BAR_TAP), EXIT_PEEKED_TO_EXPANDED_SEARCH_BAR_TAP); codes.put(new StateChangeKey(PanelState.EXPANDED, StateChangeReason.SWIPE), EXIT_PEEKED_TO_EXPANDED_SWIPE); codes.put(new StateChangeKey(PanelState.EXPANDED, StateChangeReason.FLING), EXIT_PEEKED_TO_EXPANDED_FLING); codes.put(new StateChangeKey(PanelState.MAXIMIZED, StateChangeReason.SWIPE), EXIT_PEEKED_TO_MAXIMIZED_SWIPE); codes.put(new StateChangeKey(PanelState.MAXIMIZED, StateChangeReason.FLING), EXIT_PEEKED_TO_MAXIMIZED_FLING); EXIT_PEEKED_TO_STATE_CHANGE_CODES = Collections.unmodifiableMap(codes); } // Exit code map: first exit from EXPANDED. private static final Map<StateChangeKey, Integer> EXIT_EXPANDED_TO_STATE_CHANGE_CODES; static { Map<StateChangeKey, Integer> codes = new HashMap<StateChangeKey, Integer>(); codes.put(new StateChangeKey(PanelState.CLOSED, StateChangeReason.BACK_PRESS), EXIT_EXPANDED_TO_CLOSED_BACK_PRESS); codes.put(new StateChangeKey(PanelState.CLOSED, StateChangeReason.BASE_PAGE_TAP), EXIT_EXPANDED_TO_CLOSED_BASE_PAGE_TAP); codes.put(new StateChangeKey(PanelState.CLOSED, StateChangeReason.FLING), EXIT_EXPANDED_TO_CLOSED_FLING); codes.put(new StateChangeKey(PanelState.PEEKED, StateChangeReason.SEARCH_BAR_TAP), EXIT_EXPANDED_TO_PEEKED_SEARCH_BAR_TAP); codes.put(new StateChangeKey(PanelState.PEEKED, StateChangeReason.SWIPE), EXIT_EXPANDED_TO_PEEKED_SWIPE); codes.put(new StateChangeKey(PanelState.PEEKED, StateChangeReason.FLING), EXIT_EXPANDED_TO_PEEKED_FLING); codes.put(new StateChangeKey(PanelState.MAXIMIZED, StateChangeReason.SWIPE), EXIT_EXPANDED_TO_MAXIMIZED_SWIPE); codes.put(new StateChangeKey(PanelState.MAXIMIZED, StateChangeReason.FLING), EXIT_EXPANDED_TO_MAXIMIZED_FLING); codes.put(new StateChangeKey(PanelState.MAXIMIZED, StateChangeReason.SERP_NAVIGATION), EXIT_EXPANDED_TO_MAXIMIZED_SERP_NAVIGATION); EXIT_EXPANDED_TO_STATE_CHANGE_CODES = Collections.unmodifiableMap(codes); } // Exit code map: first exit from MAXIMIZED. private static final Map<StateChangeKey, Integer> EXIT_MAXIMIZED_TO_STATE_CHANGE_CODES; static { Map<StateChangeKey, Integer> codes = new HashMap<StateChangeKey, Integer>(); codes.put(new StateChangeKey(PanelState.CLOSED, StateChangeReason.BACK_PRESS), EXIT_MAXIMIZED_TO_CLOSED_BACK_PRESS); codes.put(new StateChangeKey(PanelState.CLOSED, StateChangeReason.FLING), EXIT_MAXIMIZED_TO_CLOSED_FLING); codes.put(new StateChangeKey(PanelState.CLOSED, StateChangeReason.TAB_PROMOTION), EXIT_MAXIMIZED_TO_CLOSED_TAB_PROMOTION); codes.put(new StateChangeKey(PanelState.CLOSED, StateChangeReason.SERP_NAVIGATION), EXIT_MAXIMIZED_TO_CLOSED_SERP_NAVIGATION); codes.put(new StateChangeKey(PanelState.PEEKED, StateChangeReason.SWIPE), EXIT_MAXIMIZED_TO_PEEKED_SWIPE); codes.put(new StateChangeKey(PanelState.PEEKED, StateChangeReason.FLING), EXIT_MAXIMIZED_TO_PEEKED_FLING); codes.put(new StateChangeKey(PanelState.EXPANDED, StateChangeReason.SWIPE), EXIT_MAXIMIZED_TO_EXPANDED_SWIPE); codes.put(new StateChangeKey(PanelState.EXPANDED, StateChangeReason.FLING), EXIT_MAXIMIZED_TO_EXPANDED_FLING); EXIT_MAXIMIZED_TO_STATE_CHANGE_CODES = Collections.unmodifiableMap(codes); } // "Seen by gesture" code map: logged on first exit from expanded panel, or promo, // broken down by gesture. private static final Map<Pair<Boolean, Boolean>, Integer> SEEN_BY_GESTURE_CODES; static { final boolean unseen = false; final boolean seen = true; Map<Pair<Boolean, Boolean>, Integer> codes = new HashMap<Pair<Boolean, Boolean>, Integer>(); codes.put(new Pair<Boolean, Boolean>(seen, TAP), RESULTS_SEEN_FROM_TAP); codes.put(new Pair<Boolean, Boolean>(unseen, TAP), RESULTS_NOT_SEEN_FROM_TAP); codes.put(new Pair<Boolean, Boolean>(seen, LONG_PRESS), RESULTS_SEEN_FROM_LONG_PRESS); codes.put(new Pair<Boolean, Boolean>(unseen, LONG_PRESS), RESULTS_NOT_SEEN_FROM_LONG_PRESS); SEEN_BY_GESTURE_CODES = Collections.unmodifiableMap(codes); } // "Promo outcome by gesture" code map: logged on exit from promo, broken down by gesture. private static final Map<Pair<Integer, Boolean>, Integer> PROMO_BY_GESTURE_CODES; static { Map<Pair<Integer, Boolean>, Integer> codes = new HashMap<Pair<Integer, Boolean>, Integer>(); codes.put(new Pair<Integer, Boolean>(PREFERENCE_ENABLED, TAP), PROMO_ENABLED_FROM_TAP); codes.put(new Pair<Integer, Boolean>(PREFERENCE_DISABLED, TAP), PROMO_DISABLED_FROM_TAP); codes.put(new Pair<Integer, Boolean>(PREFERENCE_UNINITIALIZED, TAP), PROMO_UNDECIDED_FROM_TAP); codes.put(new Pair<Integer, Boolean>(PREFERENCE_ENABLED, LONG_PRESS), PROMO_ENABLED_FROM_LONG_PRESS); codes.put(new Pair<Integer, Boolean>(PREFERENCE_DISABLED, LONG_PRESS), PROMO_DISABLED_FROM_LONG_PRESS); codes.put(new Pair<Integer, Boolean>(PREFERENCE_UNINITIALIZED, LONG_PRESS), PROMO_UNDECIDED_FROM_LONG_PRESS); PROMO_BY_GESTURE_CODES = Collections.unmodifiableMap(codes); } /** * Logs the state of the Contextual Search preference. This function should be called if the * Contextual Search feature is active, and will track the different preference settings * (disabled, enabled or uninitialized). Calling more than once is fine. */ public static void logPreferenceState() { RecordHistogram.recordEnumeratedHistogram("Search.ContextualSearchPreferenceState", getPreferenceValue(), PREFERENCE_HISTOGRAM_BOUNDARY); } /** * Logs the given number of promo taps remaining. Should be called only for users that * are still undecided. * @param promoTapsRemaining The number of taps remaining (should not be negative). */ public static void logPromoTapsRemaining(int promoTapsRemaining) { if (promoTapsRemaining >= 0) { RecordHistogram.recordCountHistogram("Search.ContextualSearchPromoTapsRemaining", promoTapsRemaining); } } /** * Logs the historic number of times that a Tap gesture triggered the peeking promo * for users that have never opened the panel. This should be called periodically for * undecided users only. * @param promoTaps The historic number of taps that have caused the peeking bar for the promo, * for users that have never opened the panel. */ public static void logPromoTapsForNeverOpened(int promoTaps) { RecordHistogram.recordCountHistogram("Search.ContextualSearchPromoTapsForNeverOpened", promoTaps); } /** * Logs the historic number of times that a Tap gesture triggered the peeking promo before * the user ever opened the panel. This should be called periodically for all users. * @param promoTaps The historic number of taps that have caused the peeking bar for the promo * before the first open of the panel, for all users that have ever opened the panel. */ public static void logPromoTapsBeforeFirstOpen(int promoTaps) { RecordHistogram.recordCountHistogram("Search.ContextualSearchPromoTapsBeforeFirstOpen", promoTaps); } /** * Records the total count of times the promo panel has *ever* been opened. This should only * be called when the user is still undecided. * @param count The total historic count of times the panel has ever been opened for the * current user. */ public static void logPromoOpenCount(int count) { RecordHistogram.recordCountHistogram("Search.ContextualSearchPromoOpenCount", count); } /** * Logs the number of taps that have been counted since the user last opened the panel, for * undecided users. * @param tapsSinceOpen The number of taps to log. */ public static void logTapsSinceOpenForUndecided(int tapsSinceOpen) { RecordHistogram.recordCountHistogram("Search.ContextualSearchTapsSinceOpenUndecided", tapsSinceOpen); } /** * Logs the number of taps that have been counted since the user last opened the panel, for * decided users. * @param tapsSinceOpen The number of taps to log. */ public static void logTapsSinceOpenForDecided(int tapsSinceOpen) { RecordHistogram.recordCountHistogram("Search.ContextualSearchTapsSinceOpenDecided", tapsSinceOpen); } /** * Logs whether the Search Term was single or multiword. * @param isSingleWord Whether the resolved search term is a single word or not. */ public static void logSearchTermResolvedWords(boolean isSingleWord) { RecordHistogram.recordEnumeratedHistogram("Search.ContextualSearchResolvedTermWords", isSingleWord ? RESOLVED_SINGLE_WORD : RESOLVED_MULTI_WORD, RESOLVED_BOUNDARY); } /** * Logs whether the base page was using the HTTP protocol or not. * @param isHttpBasePage Whether the base page was using the HTTP protocol or not (should * be false for HTTPS or other URIs). */ public static void logBasePageProtocol(boolean isHttpBasePage) { RecordHistogram.recordEnumeratedHistogram("Search.ContextualSearchBasePageProtocol", isHttpBasePage ? PROTOCOL_IS_HTTP : PROTOCOL_NOT_HTTP, PROTOCOL_BOUNDARY); } /** * Logs changes to the Contextual Search preference, aside from those resulting from the first * run flow. * @param enabled Whether the preference is being enabled or disabled. */ public static void logPreferenceChange(boolean enabled) { RecordHistogram.recordEnumeratedHistogram("Search.ContextualSearchPreferenceStateChange", enabled ? PREFERENCE_ENABLED : PREFERENCE_DISABLED, PREFERENCE_HISTOGRAM_BOUNDARY); } /** * Logs the outcome of the promo (first run flow). * Logs multiple histograms; with and without the originating gesture. * @param wasTap Whether the gesture that originally caused the panel to show was a Tap. */ public static void logPromoOutcome(boolean wasTap) { int preferenceCode = getPreferenceValue(); RecordHistogram.recordEnumeratedHistogram("Search.ContextualSearchFirstRunFlowOutcome", preferenceCode, PREFERENCE_HISTOGRAM_BOUNDARY); int preferenceByGestureCode = getPromoByGestureStateCode(preferenceCode, wasTap); RecordHistogram.recordEnumeratedHistogram("Search.ContextualSearchPromoOutcomeByGesture", preferenceByGestureCode, PROMO_BY_GESTURE_BOUNDARY); } /** * Logs the duration of a Contextual Search panel being viewed by the user. * @param wereResultsSeen Whether search results were seen. * @param isChained Whether the Contextual Search ended with the start of another. * @param durationMs The duration of the contextual search in milliseconds. */ public static void logDuration(boolean wereResultsSeen, boolean isChained, long durationMs) { if (wereResultsSeen) { RecordHistogram.recordTimesHistogram("Search.ContextualSearchDurationSeen", durationMs, TimeUnit.MILLISECONDS); } else if (isChained) { RecordHistogram.recordTimesHistogram("Search.ContextualSearchDurationUnseenChained", durationMs, TimeUnit.MILLISECONDS); } else { RecordHistogram.recordTimesHistogram("Search.ContextualSearchDurationUnseen", durationMs, TimeUnit.MILLISECONDS); } } /** * Log the duration of finishing loading the SERP after the panel is opened. * @param wasPrefetch Whether the request was prefetch-enabled or not. * @param durationMs The duration of loading the SERP till completely loaded, in milliseconds. * Note that this value will be 0 when the SERP is prefetched and the user waits a * while before opening the panel. */ public static void logSearchPanelLoadDuration(boolean wasPrefetch, long durationMs) { if (wasPrefetch) { RecordHistogram.recordMediumTimesHistogram("Search.ContextualSearchDurationPrefetched", durationMs, TimeUnit.MILLISECONDS); } else { RecordHistogram.recordMediumTimesHistogram( "Search.ContextualSearchDurationNonPrefetched", durationMs, TimeUnit.MILLISECONDS); } // Also record a summary histogram with counts for each possibility. int code = !wasPrefetch ? NOT_PREFETCHED : (durationMs == 0 ? PREFETCHED_FULLY_LOADED : PREFETCHED_PARIALLY_LOADED); RecordHistogram.recordEnumeratedHistogram("Search.ContextualSearchPrefetchSummary", code, PREFETCH_BOUNDARY); } /** * Logs whether the promo was seen. * Logs multiple histograms, with and without the original triggering gesture. * @param wasPanelSeen Whether the panel was seen. * @param wasTap Whether the gesture that originally caused the panel to show was a Tap. */ public static void logPromoSeen(boolean wasPanelSeen, boolean wasTap) { RecordHistogram.recordEnumeratedHistogram("Search.ContextualSearchFirstRunPanelSeen", wasPanelSeen ? RESULTS_SEEN : RESULTS_NOT_SEEN, RESULTS_SEEN_BOUNDARY); logHistogramByGesture(wasPanelSeen, wasTap, "Search.ContextualSearchPromoSeenByGesture"); } /** * Logs whether search results were seen. * Logs multiple histograms; with and without the original triggering gesture. * @param wasPanelSeen Whether the panel was seen. * @param wasTap Whether the gesture that originally caused the panel to show was a Tap. */ public static void logResultsSeen(boolean wasPanelSeen, boolean wasTap) { RecordHistogram.recordEnumeratedHistogram("Search.ContextualSearchResultsSeen", wasPanelSeen ? RESULTS_SEEN : RESULTS_NOT_SEEN, RESULTS_SEEN_BOUNDARY); logHistogramByGesture(wasPanelSeen, wasTap, "Search.ContextualSearchResultsSeenByGesture"); } /** * Logs whether a selection is valid. * @param isSelectionValid Whether the selection is valid. */ public static void logSelectionIsValid(boolean isSelectionValid) { RecordHistogram.recordEnumeratedHistogram("Search.ContextualSearchSelectionValid", isSelectionValid ? SELECTION_VALID : SELECTION_INVALID, SELECTION_BOUNDARY); } /** * Logs whether a normal priority search request failed. * @param isFailure Whether the request failed. */ public static void logNormalPrioritySearchRequestOutcome(boolean isFailure) { RecordHistogram.recordEnumeratedHistogram( "Search.ContextualSearchNormalPrioritySearchRequestStatus", isFailure ? REQUEST_FAILED : REQUEST_NOT_FAILED, REQUEST_BOUNDARY); } /** * Logs whether a low priority search request failed. * @param isFailure Whether the request failed. */ public static void logLowPrioritySearchRequestOutcome(boolean isFailure) { RecordHistogram.recordEnumeratedHistogram( "Search.ContextualSearchLowPrioritySearchRequestStatus", isFailure ? REQUEST_FAILED : REQUEST_NOT_FAILED, REQUEST_BOUNDARY); } /** * Logs whether a fallback search request failed. * @param isFailure Whether the request failed. */ public static void logFallbackSearchRequestOutcome(boolean isFailure) { RecordHistogram.recordEnumeratedHistogram( "Search.ContextualSearchFallbackSearchRequestStatus", isFailure ? REQUEST_FAILED : REQUEST_NOT_FAILED, REQUEST_BOUNDARY); } /** * Logs how a state was entered for the first time within a Contextual Search. * @param fromState The state to transition from. * @param toState The state to transition to. * @param reason The reason for the state transition. */ public static void logFirstStateEntry(PanelState fromState, PanelState toState, StateChangeReason reason) { int code; switch (toState) { case CLOSED: code = getStateChangeCode(fromState, reason, ENTER_CLOSED_STATE_CHANGE_CODES, ENTER_CLOSED_FROM_OTHER); RecordHistogram.recordEnumeratedHistogram( "Search.ContextualSearchEnterClosed", code, ENTER_CLOSED_FROM_BOUNDARY); break; case PEEKED: code = getStateChangeCode(fromState, reason, ENTER_PEEKED_STATE_CHANGE_CODES, ENTER_PEEKED_FROM_OTHER); RecordHistogram.recordEnumeratedHistogram( "Search.ContextualSearchEnterPeeked", code, ENTER_PEEKED_FROM_BOUNDARY); break; case EXPANDED: code = getStateChangeCode(fromState, reason, ENTER_EXPANDED_STATE_CHANGE_CODES, ENTER_EXPANDED_FROM_OTHER); RecordHistogram.recordEnumeratedHistogram( "Search.ContextualSearchEnterExpanded", code, ENTER_EXPANDED_FROM_BOUNDARY); break; case MAXIMIZED: code = getStateChangeCode(fromState, reason, ENTER_MAXIMIZED_STATE_CHANGE_CODES, ENTER_MAXIMIZED_FROM_OTHER); RecordHistogram.recordEnumeratedHistogram( "Search.ContextualSearchEnterMaximized", code, ENTER_MAXIMIZED_FROM_BOUNDARY); break; default: break; } } /** * Logs how a state was exited for the first time within a Contextual Search. * @param fromState The state to transition from. * @param toState The state to transition to. * @param reason The reason for the state transition. */ public static void logFirstStateExit(PanelState fromState, PanelState toState, StateChangeReason reason) { int code; switch (fromState) { case UNDEFINED: case CLOSED: code = getStateChangeCode(toState, reason, EXIT_CLOSED_TO_STATE_CHANGE_CODES, EXIT_CLOSED_TO_OTHER); RecordHistogram.recordEnumeratedHistogram( "Search.ContextualSearchExitClosed", code, EXIT_CLOSED_TO_BOUNDARY); break; case PEEKED: code = getStateChangeCode(toState, reason, EXIT_PEEKED_TO_STATE_CHANGE_CODES, EXIT_PEEKED_TO_OTHER); RecordHistogram.recordEnumeratedHistogram( "Search.ContextualSearchExitPeeked", code, EXIT_PEEKED_TO_BOUNDARY); break; case EXPANDED: code = getStateChangeCode(toState, reason, EXIT_EXPANDED_TO_STATE_CHANGE_CODES, EXIT_EXPANDED_TO_OTHER); RecordHistogram.recordEnumeratedHistogram( "Search.ContextualSearchExitExpanded", code, EXIT_EXPANDED_TO_BOUNDARY); break; case MAXIMIZED: code = getStateChangeCode(toState, reason, EXIT_MAXIMIZED_TO_STATE_CHANGE_CODES, EXIT_MAXIMIZED_TO_OTHER); RecordHistogram.recordEnumeratedHistogram( "Search.ContextualSearchExitMaximized", code, EXIT_MAXIMIZED_TO_BOUNDARY); break; default: break; } } /** * Gets the state-change code for the given parameters by doing a lookup in the given map. * @param state The panel state. * @param reason The reason the state changed. * @param stateChangeCodes The map of state and reason to code. * @param defaultCode The code to return if the given values are not found in the map. * @return The code to write into an enum histogram, based on the given map. */ private static int getStateChangeCode(PanelState state, StateChangeReason reason, Map<StateChangeKey, Integer> stateChangeCodes, int defaultCode) { Integer code = stateChangeCodes.get(new StateChangeKey(state, reason)); if (code != null) { return code; } return defaultCode; } /** * Gets the panel-seen code for the given parameters by doing a lookup in the seen-by-gesture * map. * @param wasPanelSeen Whether the panel was seen. * @param wasTap Whether the gesture that originally caused the panel to show was a Tap. * @return The code to write into a panel-seen histogram. */ private static int getPanelSeenByGestureStateCode(boolean wasPanelSeen, boolean wasTap) { return SEEN_BY_GESTURE_CODES.get(new Pair<Boolean, Boolean>(wasPanelSeen, wasTap)); } /** * Gets the promo-outcome code for the given parameter by doing a lookup in the * promo-by-gesture map. * @param preferenceValue The code for the current preference value. * @param wasTap Whether the gesture that originally caused the panel to show was a Tap. * @return The code to write into a promo-outcome histogram. */ private static int getPromoByGestureStateCode(int preferenceValue, boolean wasTap) { return PROMO_BY_GESTURE_CODES.get(new Pair<Integer, Boolean>(preferenceValue, wasTap)); } /** * @return The code for the Contextual Search preference. */ private static int getPreferenceValue() { PrefServiceBridge preferences = PrefServiceBridge.getInstance(); if (preferences.isContextualSearchUninitialized()) { return PREFERENCE_UNINITIALIZED; } else if (preferences.isContextualSearchDisabled()) { return PREFERENCE_DISABLED; } return PREFERENCE_ENABLED; } /** * Logs to a seen-by-gesture histogram of the given name. * @param wasPanelSeen Whether the panel was seen. * @param wasTap Whether the gesture that originally caused the panel to show was a Tap. * @param histogramName The full name of the histogram to log to. */ private static void logHistogramByGesture(boolean wasPanelSeen, boolean wasTap, String histogramName) { RecordHistogram.recordEnumeratedHistogram(histogramName, getPanelSeenByGestureStateCode(wasPanelSeen, wasTap), RESULTS_BY_GESTURE_BOUNDARY); } }
package com.yahoo.vespa.model.admin.monitoring; public class DefaultMetricsConsumer { public static final String VESPA_CONSUMER_ID = "vespa"; private static final MetricSet vespaMetricSet = new VespaMetricSet(); @SuppressWarnings("UnusedDeclaration") public static MetricsConsumer getDefaultMetricsConsumer() { return new MetricsConsumer(VESPA_CONSUMER_ID, vespaMetricSet); } }
package com.gentics.mesh.core.data.container.impl; import static com.gentics.mesh.core.data.ContainerType.DRAFT; import static com.gentics.mesh.core.data.ContainerType.PUBLISHED; import static com.gentics.mesh.core.data.relationship.GraphRelationships.HAS_EDITOR; import static com.gentics.mesh.core.data.relationship.GraphRelationships.HAS_FIELD; import static com.gentics.mesh.core.data.relationship.GraphRelationships.HAS_FIELD_CONTAINER; import static com.gentics.mesh.core.data.relationship.GraphRelationships.HAS_ITEM; import static com.gentics.mesh.core.data.relationship.GraphRelationships.HAS_LIST; import static com.gentics.mesh.core.data.relationship.GraphRelationships.HAS_MICROSCHEMA_CONTAINER; import static com.gentics.mesh.core.data.relationship.GraphRelationships.HAS_SCHEMA_CONTAINER_VERSION; import static com.gentics.mesh.core.data.relationship.GraphRelationships.HAS_VERSION; import static com.gentics.mesh.core.rest.error.Errors.error; import static com.gentics.mesh.core.rest.error.Errors.nodeConflict; import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST; import static io.netty.handler.codec.http.HttpResponseStatus.CONFLICT; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; import com.gentics.mesh.core.data.node.field.DisplayField; import org.apache.commons.collections.CollectionUtils; import com.gentics.mesh.context.InternalActionContext; import com.gentics.mesh.core.data.ContainerType; import com.gentics.mesh.core.data.NodeGraphFieldContainer; import com.gentics.mesh.core.data.Release; import com.gentics.mesh.core.data.User; import com.gentics.mesh.core.data.diff.FieldChangeTypes; import com.gentics.mesh.core.data.diff.FieldContainerChange; import com.gentics.mesh.core.data.generic.MeshVertexImpl; import com.gentics.mesh.core.data.impl.GraphFieldContainerEdgeImpl; import com.gentics.mesh.core.data.impl.UserImpl; import com.gentics.mesh.core.data.node.Node; import com.gentics.mesh.core.data.node.field.BinaryGraphField; import com.gentics.mesh.core.data.node.field.GraphField; import com.gentics.mesh.core.data.node.field.StringGraphField; import com.gentics.mesh.core.data.node.field.impl.BinaryGraphFieldImpl; import com.gentics.mesh.core.data.node.field.impl.MicronodeGraphFieldImpl; import com.gentics.mesh.core.data.node.field.impl.StringGraphFieldImpl; import com.gentics.mesh.core.data.node.field.list.MicronodeGraphFieldList; import com.gentics.mesh.core.data.node.field.list.impl.MicronodeGraphFieldListImpl; import com.gentics.mesh.core.data.node.field.list.impl.StringGraphFieldListImpl; import com.gentics.mesh.core.data.node.field.nesting.MicronodeGraphField; import com.gentics.mesh.core.data.node.impl.MicronodeImpl; import com.gentics.mesh.core.data.node.impl.NodeImpl; import com.gentics.mesh.core.data.schema.GraphFieldSchemaContainerVersion; import com.gentics.mesh.core.data.schema.MicroschemaContainerVersion; import com.gentics.mesh.core.data.schema.SchemaContainerVersion; import com.gentics.mesh.core.data.schema.impl.SchemaContainerVersionImpl; import com.gentics.mesh.core.data.search.SearchQueueBatch; import com.gentics.mesh.core.rest.node.FieldMap; import com.gentics.mesh.core.rest.node.field.Field; import com.gentics.mesh.core.rest.schema.FieldSchema; import com.gentics.mesh.core.rest.schema.Schema; import com.gentics.mesh.core.rest.schema.SchemaModel; import com.gentics.mesh.dagger.MeshInternal; import com.gentics.mesh.graphdb.spi.Database; import com.gentics.mesh.graphdb.spi.FieldType; import com.gentics.mesh.path.Path; import com.gentics.mesh.path.PathSegment; import com.gentics.mesh.util.ETag; import com.gentics.mesh.util.Tuple; import com.gentics.mesh.util.VersionNumber; import com.google.common.base.Equivalence; import com.google.common.collect.MapDifference; import com.google.common.collect.Maps; import com.syncleus.ferma.traversals.EdgeTraversal; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; /** * @see NodeGraphFieldContainer */ public class NodeGraphFieldContainerImpl extends AbstractGraphFieldContainerImpl implements NodeGraphFieldContainer { private static final Logger log = LoggerFactory.getLogger(NodeGraphFieldContainerImpl.class); public static final String DISPLAY_FIELD_PROPERTY_KEY = "displayFieldValue"; public static final String VERSION_PROPERTY_KEY = "version"; public static void init(Database database) { database.addVertexType(NodeGraphFieldContainerImpl.class, MeshVertexImpl.class); // Webroot index: database.addVertexIndex(WEBROOT_INDEX_NAME, NodeGraphFieldContainerImpl.class, true, WEBROOT_PROPERTY_KEY, FieldType.STRING); database.addVertexIndex(PUBLISHED_WEBROOT_INDEX_NAME, NodeGraphFieldContainerImpl.class, true, PUBLISHED_WEBROOT_PROPERTY_KEY, FieldType.STRING); // Webroot url field index: database.addVertexIndex(WEBROOT_URLFIELD_INDEX_NAME, NodeGraphFieldContainerImpl.class, true, WEBROOT_URLFIELD_PROPERTY_KEY, FieldType.STRING_SET); database.addVertexIndex(PUBLISHED_WEBROOT_URLFIELD_INDEX_NAME, NodeGraphFieldContainerImpl.class, true, PUBLISHED_WEBROOT_URLFIELD_PROPERTY_KEY, FieldType.STRING_SET); } @Override public void setSchemaContainerVersion(GraphFieldSchemaContainerVersion<?, ?, ?, ?, ?> version) { setSingleLinkOutTo(version, HAS_SCHEMA_CONTAINER_VERSION); } @Override public SchemaContainerVersion getSchemaContainerVersion() { return out(HAS_SCHEMA_CONTAINER_VERSION).has(SchemaContainerVersionImpl.class).nextOrDefaultExplicit(SchemaContainerVersionImpl.class, null); } @Override public String getDisplayFieldValue() { // Normally the display field value would be loaded by // 1. Loading the displayField name from the used schema // 2. Loading the string field with the found name // 3. Loading the value from that field // This is very costly and thus we store the precomputed display field // within a local property. return getProperty(DISPLAY_FIELD_PROPERTY_KEY); } @Override public void updateDisplayFieldValue() { // TODO use schema storage instead Schema schema = getSchemaContainerVersion().getSchema(); String displayFieldName = schema.getDisplayField(); FieldSchema fieldSchema = schema.getField(displayFieldName); // Only update the display field value if the field can be located if (fieldSchema != null) { GraphField field = getField(fieldSchema); if (field != null && field instanceof DisplayField) { DisplayField displayField = (DisplayField) field; setProperty(DISPLAY_FIELD_PROPERTY_KEY, displayField.getDisplayName()); return; } } // Otherwise reset the value to null setProperty(DISPLAY_FIELD_PROPERTY_KEY, null); } @Override public void delete(SearchQueueBatch batch) { // TODO delete linked aggregation nodes for node lists etc for (BinaryGraphField binaryField : outE(HAS_FIELD).frame(BinaryGraphFieldImpl.class)) { binaryField.removeField(this); } // Lists // for (NumberGraphFieldList list : out(HAS_FIELD).frame(NumberGraphFieldListImpl.class)) { // list.removeField(this); // for (DateGraphFieldList list : out(HAS_FIELD).frame(DateGraphFieldListImpl.class)) { // list.removeField(this); // for (BooleanGraphFieldList list : out(HAS_FIELD).frame(BooleanGraphFieldListImpl.class)) { // list.removeField(this); // for (HtmlGraphFieldList list : out(HAS_FIELD).frame(HtmlGraphFieldListImpl.class)) { // list.removeField(this); // for (StringGraphFieldList list : out(HAS_FIELD).frame(StringGraphFieldListImpl.class)) { // list.removeField(this); // for (NodeGraphFieldList list : out(HAS_FIELD).frame(NodeGraphFieldListImpl.class)) { // list.removeField(this); // We don't need to handle node fields since those are only edges and will automatically be removed // Recursively delete all versions of the container NodeGraphFieldContainer next = getNextVersion(); if (next != null) { next.delete(batch); } // Delete the container from all releases and types getReleaseTypes().forEach(tuple -> { String releaseUuid = tuple.v1(); ContainerType type = tuple.v2(); if (type != ContainerType.INITIAL) { batch.delete(this, releaseUuid, type, false); } }); getElement().remove(); } @Override @SuppressWarnings("unchecked") public void deleteFromRelease(Release release, SearchQueueBatch batch) { String releaseUuid = release.getUuid(); batch.delete(this, releaseUuid, DRAFT, false); if (isPublished(releaseUuid)) { batch.delete(this, releaseUuid, PUBLISHED, false); setProperty(PUBLISHED_WEBROOT_PROPERTY_KEY, null); } // Remove the edge between the node and the container that matches the release inE(HAS_FIELD_CONTAINER).has(GraphFieldContainerEdgeImpl.RELEASE_UUID_KEY, releaseUuid).or(e -> e.traversal().has( GraphFieldContainerEdgeImpl.EDGE_TYPE_KEY, ContainerType.DRAFT.getCode()), e -> e.traversal().has( GraphFieldContainerEdgeImpl.EDGE_TYPE_KEY, ContainerType.PUBLISHED.getCode())).removeAll(); // remove webroot property setProperty(WEBROOT_PROPERTY_KEY, null); } @Override public void updateFieldsFromRest(InternalActionContext ac, FieldMap restFields) { super.updateFieldsFromRest(ac, restFields); String releaseUuid = ac.getRelease().getUuid(); updateWebrootPathInfo(releaseUuid, "node_conflicting_segmentfield_update"); updateDisplayFieldValue(); } @Override public Set<String> getUrlFieldValues() { SchemaModel schema = getSchemaContainerVersion().getSchema(); Set<String> urlFieldValues = new HashSet<>(); if (schema.getUrlFields() != null) { for (String urlField : schema.getUrlFields()) { FieldSchema fieldSchema = schema.getField(urlField); GraphField field = getField(fieldSchema); if (field instanceof StringGraphFieldImpl) { StringGraphFieldImpl stringField = (StringGraphFieldImpl) field; String value = stringField.getString(); if (value != null) { urlFieldValues.add(value); } } if (field instanceof StringGraphFieldListImpl) { StringGraphFieldListImpl stringListField = (StringGraphFieldListImpl) field; for (StringGraphField listField : stringListField.getList()) { if (listField != null) { String value = listField.getString(); if (value != null) { urlFieldValues.add(value); } } } } } } return urlFieldValues; } /** * Update the webroot url field index and also assert that the new values would not cause a conflict with the existing data. * * @param releaseUuid * @param urlFieldValues * @param propertyName * @param indexName */ private void updateWebrootUrlFieldsInfo(String releaseUuid, Set<String> urlFieldValues, String propertyName, String indexName) { if (urlFieldValues != null && !urlFieldValues.isEmpty()) { // Prefix each path with the releaseuuid in order to scope the paths by release Set<String> prefixedUrlFieldValues = urlFieldValues.stream().map(e -> releaseUuid + e).collect(Collectors.toSet()); // Individually check each url for (String urlFieldValue : prefixedUrlFieldValues) { NodeGraphFieldContainer conflictingContainer = MeshInternal.get().database().checkIndexUniqueness(indexName, this, urlFieldValue); if (conflictingContainer != null) { if (log.isDebugEnabled()) { log.debug("Found conflicting container with uuid {" + conflictingContainer.getUuid() + "}"); } // We know that the found container already occupies the index with one of the given paths. Lets compare both sets of paths in order to // determine // which path caused the conflict. Set<String> fromConflictingContainer = conflictingContainer.getUrlFieldValues(); Node conflictingNode = conflictingContainer.getParentNode(); @SuppressWarnings("unchecked") Collection<String> conflictingValues = CollectionUtils.intersection(fromConflictingContainer, urlFieldValues); String paths = conflictingValues.stream().map(n -> n.toString()).collect(Collectors.joining(",")); throw nodeConflict(conflictingNode.getUuid(), conflictingContainer.getDisplayFieldValue(), conflictingContainer.getLanguage() .getLanguageTag(), "node_conflicting_urlfield_update", paths, conflictingContainer.getParentNode().getUuid(), conflictingContainer.getLanguage().getLanguageTag()); } } setProperty(propertyName, prefixedUrlFieldValues); } else { setProperty(propertyName, null); } } @Override public void updateWebrootPathInfo(String releaseUuid, String conflictI18n) { Set<String> urlFieldValues = getUrlFieldValues(); if (isDraft(releaseUuid)) { updateWebrootPathInfo(releaseUuid, conflictI18n, ContainerType.DRAFT, WEBROOT_PROPERTY_KEY, WEBROOT_INDEX_NAME); updateWebrootUrlFieldsInfo(releaseUuid, urlFieldValues, WEBROOT_URLFIELD_PROPERTY_KEY, WEBROOT_URLFIELD_INDEX_NAME); } else { setProperty(WEBROOT_PROPERTY_KEY, null); setProperty(WEBROOT_URLFIELD_PROPERTY_KEY, null); } if (isPublished(releaseUuid)) { updateWebrootPathInfo(releaseUuid, conflictI18n, ContainerType.PUBLISHED, PUBLISHED_WEBROOT_PROPERTY_KEY, PUBLISHED_WEBROOT_INDEX_NAME); updateWebrootUrlFieldsInfo(releaseUuid, urlFieldValues, PUBLISHED_WEBROOT_URLFIELD_PROPERTY_KEY, PUBLISHED_WEBROOT_URLFIELD_INDEX_NAME); } else { setProperty(PUBLISHED_WEBROOT_PROPERTY_KEY, null); setProperty(PUBLISHED_WEBROOT_URLFIELD_PROPERTY_KEY, null); } } /** * Update the webroot path info (checking for uniqueness before) * * @param releaseUuid * release Uuid * @param conflictI18n * i18n for the message in case of conflict * @param type * edge type * @param propertyName * name of the property * @param indexName * name of the index to check for uniqueness */ protected void updateWebrootPathInfo(String releaseUuid, String conflictI18n, ContainerType type, String propertyName, String indexName) { Node node = getParentNode(); String segmentFieldName = getSchemaContainerVersion().getSchema().getSegmentField(); // Determine the webroot path of the container parent node String segment = node.getPathSegment(releaseUuid, type, getLanguage().getLanguageTag()); // The webroot uniqueness will be checked by validating that the string [segmentValue-releaseUuid-parentNodeUuid] is only listed once within the given // specific index for (drafts or published nodes) if (segment != null) { StringBuilder webRootInfo = new StringBuilder(segment); webRootInfo.append("-").append(releaseUuid); Node parent = node.getParentNode(releaseUuid); if (parent != null) { webRootInfo.append("-").append(parent.getUuid()); } // check for uniqueness of webroot path NodeGraphFieldContainerImpl conflictingContainer = MeshInternal.get().database().checkIndexUniqueness(indexName, this, webRootInfo .toString()); if (conflictingContainer != null) { if (log.isDebugEnabled()) { log.debug("Found conflicting container with uuid {" + conflictingContainer.getUuid() + "} using index {" + indexName + "}"); } Node conflictingNode = conflictingContainer.getParentNode(); throw nodeConflict(conflictingNode.getUuid(), conflictingContainer.getDisplayFieldValue(), conflictingContainer.getLanguage() .getLanguageTag(), conflictI18n, segmentFieldName, segment); } else { setProperty(propertyName, webRootInfo.toString()); } } else { setProperty(propertyName, null); } } @Override public Node getParentNode(String uuid) { return inE(HAS_FIELD_CONTAINER).has(GraphFieldContainerEdgeImpl.EDGE_TYPE_KEY, ContainerType.DRAFT.getCode()).has( GraphFieldContainerEdgeImpl.RELEASE_UUID_KEY, uuid).nextOrDefaultExplicit(NodeImpl.class, null); } /** * Get the parent node * * @return parent node */ public Node getParentNode() { Node parentNode = in(HAS_FIELD_CONTAINER).nextOrDefaultExplicit(NodeImpl.class, null); if (parentNode == null) { // the field container is not directly linked to its Node, get the // initial field container NodeGraphFieldContainer initial = null; NodeGraphFieldContainer previous = getPreviousVersion(); while (previous != null) { initial = previous; previous = previous.getPreviousVersion(); } if (initial != null) { return initial.getParentNode(); } throw error(BAD_REQUEST, "error_field_container_without_node"); } return parentNode; } @Override public void setVersion(VersionNumber version) { setProperty(VERSION_PROPERTY_KEY, version.toString()); } @Override public VersionNumber getVersion() { String version = getProperty(VERSION_PROPERTY_KEY); return version == null ? null : new VersionNumber(version); } @Override public NodeGraphFieldContainer getNextVersion() { return out(HAS_VERSION).has(NodeGraphFieldContainerImpl.class).nextOrDefaultExplicit(NodeGraphFieldContainerImpl.class, null); } @Override public void setNextVersion(NodeGraphFieldContainer container) { setSingleLinkOutTo(container, HAS_VERSION); } @Override public NodeGraphFieldContainer getPreviousVersion() { return in(HAS_VERSION).has(NodeGraphFieldContainerImpl.class).nextOrDefaultExplicit(NodeGraphFieldContainerImpl.class, null); } @Override public NodeGraphFieldContainer findVersion(String version) { if (getVersion().toString().equals(version)) { return this; } NodeGraphFieldContainer container = this; while (container != null) { container = container.getNextVersion(); if (container != null && container.getVersion().toString().equals(version)) { return container; } } container = this; while (container != null) { container = container.getPreviousVersion(); if (container != null && container.getVersion().toString().equals(version)) { return container; } } return null; } @Override public void clone(NodeGraphFieldContainer container) { List<GraphField> otherFields = container.getFields(); for (GraphField graphField : otherFields) { graphField.cloneTo(this); } } @Override public boolean isDraft(String releaseUuid) { EdgeTraversal<?, ?, ?> traversal = inE(HAS_FIELD_CONTAINER).has(GraphFieldContainerEdgeImpl.RELEASE_UUID_KEY, releaseUuid).has( GraphFieldContainerEdgeImpl.EDGE_TYPE_KEY, ContainerType.DRAFT.getCode()); return traversal.hasNext(); } @Override public boolean isPublished(String releaseUuid) { EdgeTraversal<?, ?, ?> traversal = inE(HAS_FIELD_CONTAINER).has(GraphFieldContainerEdgeImpl.RELEASE_UUID_KEY, releaseUuid).has( GraphFieldContainerEdgeImpl.EDGE_TYPE_KEY, ContainerType.PUBLISHED.getCode()); return traversal.hasNext(); } @Override public Set<Tuple<String, ContainerType>> getReleaseTypes() { Set<Tuple<String, ContainerType>> typeSet = new HashSet<>(); inE(HAS_FIELD_CONTAINER).frameExplicit(GraphFieldContainerEdgeImpl.class).forEach(edge -> typeSet.add(Tuple.tuple(edge.getReleaseUuid(), edge .getType()))); return typeSet; } @Override public Set<String> getReleases(ContainerType type) { Set<String> releaseUuids = new HashSet<>(); inE(HAS_FIELD_CONTAINER).has(GraphFieldContainerEdgeImpl.EDGE_TYPE_KEY, type.getCode()).frameExplicit(GraphFieldContainerEdgeImpl.class) .forEach(edge -> releaseUuids.add(edge.getReleaseUuid())); return releaseUuids; } @Override public void validate() { Schema schema = getSchemaContainerVersion().getSchema(); Map<String, GraphField> fieldsMap = getFields().stream().collect(Collectors.toMap(GraphField::getFieldKey, Function.identity())); schema.getFields().stream().forEach(fieldSchema -> { GraphField field = fieldsMap.get(fieldSchema.getName()); if (fieldSchema.isRequired() && field == null) { throw error(CONFLICT, "node_error_missing_mandatory_field_value", fieldSchema.getName(), schema.getName()); } if (field != null) { field.validate(); } }); } @Override public List<FieldContainerChange> compareTo(FieldMap fieldMap) { List<FieldContainerChange> changes = new ArrayList<>(); Schema schemaA = getSchemaContainerVersion().getSchema(); Map<String, FieldSchema> fieldSchemaMap = schemaA.getFieldsAsMap(); // Handle all fields for (String fieldName : fieldSchemaMap.keySet()) { FieldSchema fieldSchema = fieldSchemaMap.get(fieldName); // Check content GraphField fieldA = getField(fieldSchema); Field fieldB = fieldMap.getField(fieldName, fieldSchema); // Handle null cases. The field may not have been created yet. if (fieldA != null && fieldB == null && fieldMap.hasField(fieldName)) { // Field only exists in A changes.add(new FieldContainerChange(fieldName, FieldChangeTypes.UPDATED)); } else if (fieldA == null && fieldB != null) { // Field only exists in B changes.add(new FieldContainerChange(fieldName, FieldChangeTypes.UPDATED)); } else if (fieldA != null && fieldB != null) { // Field exists in A and B and the fields are not equal to each // other. changes.addAll(fieldA.compareTo(fieldB)); } else { // Both fields are equal if those fields are both null } } return changes; } @Override public List<FieldContainerChange> compareTo(NodeGraphFieldContainer container) { List<FieldContainerChange> changes = new ArrayList<>(); Schema schemaA = getSchemaContainerVersion().getSchema(); Map<String, FieldSchema> fieldMapA = schemaA.getFieldsAsMap(); Schema schemaB = container.getSchemaContainerVersion().getSchema(); Map<String, FieldSchema> fieldMapB = schemaB.getFieldsAsMap(); // Generate a structural diff first. This way it is easy to determine // which fields have been added or removed. MapDifference<String, FieldSchema> diff = Maps.difference(fieldMapA, fieldMapB, new Equivalence<FieldSchema>() { @Override protected boolean doEquivalent(FieldSchema a, FieldSchema b) { return a.getName().equals(b.getName()); } @Override protected int doHash(FieldSchema t) { // TODO Auto-generated method stub return 0; } }); // Handle fields which exist only in A - They have been removed in B for (FieldSchema field : diff.entriesOnlyOnLeft().values()) { changes.add(new FieldContainerChange(field.getName(), FieldChangeTypes.REMOVED)); } // Handle fields which don't exist in A - They have been added in B for (FieldSchema field : diff.entriesOnlyOnRight().values()) { changes.add(new FieldContainerChange(field.getName(), FieldChangeTypes.ADDED)); } // Handle fields which are common in both schemas for (String fieldName : diff.entriesInCommon().keySet()) { FieldSchema fieldSchemaA = fieldMapA.get(fieldName); FieldSchema fieldSchemaB = fieldMapB.get(fieldName); // Check whether the field type is different in between both schemas if (fieldSchemaA.getType().equals(fieldSchemaB.getType())) { // Check content GraphField fieldA = getField(fieldSchemaA); GraphField fieldB = container.getField(fieldSchemaB); // Handle null cases. The field may not have been created yet. if (fieldA != null && fieldB == null) { // Field only exists in A changes.add(new FieldContainerChange(fieldName, FieldChangeTypes.UPDATED)); } else if (fieldA == null && fieldB != null) { // Field only exists in B changes.add(new FieldContainerChange(fieldName, FieldChangeTypes.UPDATED)); } else if (fieldA != null && fieldB != null) { changes.addAll(fieldA.compareTo(fieldB)); } else { // Both fields are equal if those fields are both null } } else { // The field type has changed changes.add(new FieldContainerChange(fieldName, FieldChangeTypes.UPDATED)); } } return changes; } @Override public List<? extends MicronodeGraphField> getMicronodeFields(MicroschemaContainerVersion version) { return outE(HAS_FIELD).mark().inV().has(MicronodeImpl.class).out(HAS_MICROSCHEMA_CONTAINER).has(MicroschemaContainerVersionImpl.class).has( "uuid", version.getUuid()).back().toListExplicit(MicronodeGraphFieldImpl.class); } @Override public List<? extends MicronodeGraphFieldList> getMicronodeListFields(MicroschemaContainerVersion version) { return out(HAS_LIST).has(MicronodeGraphFieldListImpl.class).mark().out(HAS_ITEM).has(MicronodeImpl.class).out(HAS_MICROSCHEMA_CONTAINER).has( MicroschemaContainerVersionImpl.class).has("uuid", version.getUuid()).back().toListExplicit(MicronodeGraphFieldListImpl.class); } @Override public String getETag(InternalActionContext ac) { return ETag.hash(getUuid()); } @Override public User getEditor() { return out(HAS_EDITOR).nextOrDefaultExplicit(UserImpl.class, null); } @Override public String getSegmentFieldValue() { String segmentFieldKey = getSchemaContainerVersion().getSchema().getSegmentField(); // 1. The container may reference a schema which has no segment field set thus no path segment can be determined if (segmentFieldKey == null) { return null; } // 2. Try to load the path segment using the string field StringGraphField stringField = getString(segmentFieldKey); if (stringField != null) { return stringField.getString(); } // 3. Try to load the path segment using the binary field since the string field could not be found if (stringField == null) { BinaryGraphField binaryField = getBinary(segmentFieldKey); if (binaryField != null) { return binaryField.getFileName(); } } return null; } public com.gentics.mesh.path.Path getPath(InternalActionContext ac) { Path nodePath = new Path(); nodePath.addSegment(new PathSegment(this, null, getLanguage().getLanguageTag())); return nodePath; } }
package de.danoeh.antennapod.core.service.playback; import android.content.Context; import android.os.Handler; import android.os.Looper; import android.os.Vibrator; import androidx.annotation.NonNull; import android.util.Log; import de.danoeh.antennapod.core.preferences.SleepTimerPreferences; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import java.util.List; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import de.danoeh.antennapod.core.event.FeedItemEvent; import de.danoeh.antennapod.core.event.QueueEvent; import de.danoeh.antennapod.core.feed.FeedItem; import de.danoeh.antennapod.core.preferences.UserPreferences; import de.danoeh.antennapod.core.storage.DBReader; import de.danoeh.antennapod.core.util.playback.Playable; import io.reactivex.Completable; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.schedulers.Schedulers; /** * Manages the background tasks of PlaybackSerivce, i.e. * the sleep timer, the position saver, the widget updater and * the queue loader. * <p/> * The PlaybackServiceTaskManager(PSTM) uses a callback object (PSTMCallback) * to notify the PlaybackService about updates from the running tasks. */ public class PlaybackServiceTaskManager { private static final String TAG = "PlaybackServiceTaskMgr"; /** * Update interval of position saver in milliseconds. */ public static final int POSITION_SAVER_WAITING_INTERVAL = 5000; /** * Notification interval of widget updater in milliseconds. */ public static final int WIDGET_UPDATER_NOTIFICATION_INTERVAL = 1000; private static final int SCHED_EX_POOL_SIZE = 2; private final ScheduledThreadPoolExecutor schedExecutor; private ScheduledFuture<?> positionSaverFuture; private ScheduledFuture<?> widgetUpdaterFuture; private ScheduledFuture<?> sleepTimerFuture; private volatile Future<List<FeedItem>> queueFuture; private volatile Future<?> chapterLoaderFuture; private SleepTimer sleepTimer; private final Context context; private final PSTMCallback callback; /** * Sets up a new PSTM. This method will also start the queue loader task. * * @param context * @param callback A PSTMCallback object for notifying the user about updates. Must not be null. */ public PlaybackServiceTaskManager(@NonNull Context context, @NonNull PSTMCallback callback) { this.context = context; this.callback = callback; schedExecutor = new ScheduledThreadPoolExecutor(SCHED_EX_POOL_SIZE, r -> { Thread t = new Thread(r); t.setPriority(Thread.MIN_PRIORITY); return t; }); loadQueue(); EventBus.getDefault().register(this); } @Subscribe public void onEvent(QueueEvent event) { Log.d(TAG, "onEvent(QueueEvent " + event +")"); cancelQueueLoader(); loadQueue(); } private synchronized boolean isQueueLoaderActive() { return queueFuture != null && !queueFuture.isDone(); } private synchronized void cancelQueueLoader() { if (isQueueLoaderActive()) { queueFuture.cancel(true); } } private synchronized void loadQueue() { if (!isQueueLoaderActive()) { queueFuture = schedExecutor.submit(() -> DBReader.getQueue()); } } @Subscribe public void onEvent(FeedItemEvent event) { // Use case: when an item in the queue has been downloaded, // listening to the event to ensure the downloaded item will be used. Log.d(TAG, "onEvent(FeedItemEvent " + event + ")"); for (FeedItem item : event.items) { if (isItemInQueue(item.getId())) { Log.d(TAG, "onEvent(FeedItemEvent) - some item (" + item.getId() + ") in the queue has been updated (usually downloaded). Refresh the queue."); cancelQueueLoader(); loadQueue(); return; } } } private boolean isItemInQueue(long itemId) { List<FeedItem> queue = getQueueIfLoaded(); if (queue != null) { for (FeedItem item : queue) { if (item.getId() == itemId) { return true; } } } return false; } /** * Returns the queue if it is already loaded or null if it hasn't been loaded yet. * In order to wait until the queue has been loaded, use getQueue() */ public synchronized List<FeedItem> getQueueIfLoaded() { if (queueFuture.isDone()) { try { return queueFuture.get(); } catch (InterruptedException | ExecutionException | CancellationException e) { e.printStackTrace(); } } return null; } /** * Returns the queue or waits until the PSTM has loaded the queue from the database. */ public synchronized List<FeedItem> getQueue() throws InterruptedException { try { return queueFuture.get(); } catch (ExecutionException e) { throw new IllegalArgumentException(e); } } /** * Starts the position saver task. If the position saver is already active, nothing will happen. */ public synchronized void startPositionSaver() { if (!isPositionSaverActive()) { Runnable positionSaver = callback::positionSaverTick; positionSaver = useMainThreadIfNecessary(positionSaver); positionSaverFuture = schedExecutor.scheduleWithFixedDelay(positionSaver, POSITION_SAVER_WAITING_INTERVAL, POSITION_SAVER_WAITING_INTERVAL, TimeUnit.MILLISECONDS); Log.d(TAG, "Started PositionSaver"); } else { Log.d(TAG, "Call to startPositionSaver was ignored."); } } /** * Returns true if the position saver is currently running. */ public synchronized boolean isPositionSaverActive() { return positionSaverFuture != null && !positionSaverFuture.isCancelled() && !positionSaverFuture.isDone(); } /** * Cancels the position saver. If the position saver is not running, nothing will happen. */ public synchronized void cancelPositionSaver() { if (isPositionSaverActive()) { positionSaverFuture.cancel(false); Log.d(TAG, "Cancelled PositionSaver"); } } /** * Starts the widget updater task. If the widget updater is already active, nothing will happen. */ public synchronized void startWidgetUpdater() { if (!isWidgetUpdaterActive() && !schedExecutor.isShutdown()) { Runnable widgetUpdater = callback::onWidgetUpdaterTick; widgetUpdater = useMainThreadIfNecessary(widgetUpdater); widgetUpdaterFuture = schedExecutor.scheduleWithFixedDelay(widgetUpdater, WIDGET_UPDATER_NOTIFICATION_INTERVAL, WIDGET_UPDATER_NOTIFICATION_INTERVAL, TimeUnit.MILLISECONDS); Log.d(TAG, "Started WidgetUpdater"); } else { Log.d(TAG, "Call to startWidgetUpdater was ignored."); } } public synchronized void setSleepTimer(long waitingTime) { if (waitingTime <= 0) { throw new IllegalArgumentException("Waiting time <= 0"); } Log.d(TAG, "Setting sleep timer to " + waitingTime + " milliseconds"); if (isSleepTimerActive()) { sleepTimerFuture.cancel(true); } sleepTimer = new SleepTimer(waitingTime); sleepTimerFuture = schedExecutor.schedule(sleepTimer, 0, TimeUnit.MILLISECONDS); } /** * Returns true if the sleep timer is currently active. */ public synchronized boolean isSleepTimerActive() { return sleepTimer != null && sleepTimerFuture != null && !sleepTimerFuture.isCancelled() && !sleepTimerFuture.isDone() && sleepTimer.getWaitingTime() > 0; } /** * Disables the sleep timer. If the sleep timer is not active, nothing will happen. */ public synchronized void disableSleepTimer() { if (isSleepTimerActive()) { Log.d(TAG, "Disabling sleep timer"); sleepTimer.cancel(); } } /** * Restarts the sleep timer. If the sleep timer is not active, nothing will happen. */ public synchronized void restartSleepTimer() { if (isSleepTimerActive()) { Log.d(TAG, "Restarting sleep timer"); sleepTimer.restart(); } } /** * Returns the current sleep timer time or 0 if the sleep timer is not active. */ public synchronized long getSleepTimerTimeLeft() { if (isSleepTimerActive()) { return sleepTimer.getWaitingTime(); } else { return 0; } } /** * Returns true if the widget updater is currently running. */ public synchronized boolean isWidgetUpdaterActive() { return widgetUpdaterFuture != null && !widgetUpdaterFuture.isCancelled() && !widgetUpdaterFuture.isDone(); } /** * Cancels the widget updater. If the widget updater is not running, nothing will happen. */ public synchronized void cancelWidgetUpdater() { if (isWidgetUpdaterActive()) { widgetUpdaterFuture.cancel(false); Log.d(TAG, "Cancelled WidgetUpdater"); } } private synchronized void cancelChapterLoader() { if (isChapterLoaderActive()) { chapterLoaderFuture.cancel(true); } } private synchronized boolean isChapterLoaderActive() { return chapterLoaderFuture != null && !chapterLoaderFuture.isDone(); } /** * Starts a new thread that loads the chapter marks from a playable object. If another chapter loader is already active, * it will be cancelled first. * On completion, the callback's onChapterLoaded method will be called. */ public synchronized void startChapterLoader(@NonNull final Playable media) { if (isChapterLoaderActive()) { cancelChapterLoader(); } if (media.getChapters() == null) { Completable.create(emitter -> { media.loadChapterMarks(); emitter.onComplete(); }) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(() -> callback.onChapterLoaded(media), throwable -> Log.d(TAG, "Error loading chapters: " + Log.getStackTraceString(throwable))); } } /** * Cancels all tasks. The PSTM will be in the initial state after execution of this method. */ public synchronized void cancelAllTasks() { cancelPositionSaver(); cancelWidgetUpdater(); disableSleepTimer(); cancelQueueLoader(); cancelChapterLoader(); } /** * Cancels all tasks and shuts down the internal executor service of the PSTM. The object should not be used after * execution of this method. */ public synchronized void shutdown() { EventBus.getDefault().unregister(this); cancelAllTasks(); schedExecutor.shutdown(); } private Runnable useMainThreadIfNecessary(Runnable runnable) { if (Looper.myLooper() == Looper.getMainLooper()) { // Called in main thread => ExoPlayer is used // Run on ui thread even if called from schedExecutor Handler handler = new Handler(); return () -> handler.post(runnable); } else { return runnable; } } /** * Sleeps for a given time and then pauses playback. */ class SleepTimer implements Runnable { private static final String TAG = "SleepTimer"; private static final long UPDATE_INTERVAL = 1000L; public static final long NOTIFICATION_THRESHOLD = 10000; private boolean hasVibrated = false; private final long waitingTime; private long timeLeft; private ShakeListener shakeListener; private final Handler handler; public SleepTimer(long waitingTime) { super(); this.waitingTime = waitingTime; this.timeLeft = waitingTime; if (UserPreferences.useExoplayer() && Looper.myLooper() == Looper.getMainLooper()) { // Run callbacks in main thread so they can call ExoPlayer methods themselves this.handler = new Handler(); } else { this.handler = null; } } private void postCallback(Runnable r) { if (handler == null) { r.run(); } else { handler.post(r); } } @Override public void run() { Log.d(TAG, "Starting"); long lastTick = System.currentTimeMillis(); while (timeLeft > 0) { try { Thread.sleep(UPDATE_INTERVAL); } catch (InterruptedException e) { Log.d(TAG, "Thread was interrupted while waiting"); e.printStackTrace(); break; } long now = System.currentTimeMillis(); timeLeft -= now - lastTick; lastTick = now; if (timeLeft < NOTIFICATION_THRESHOLD) { Log.d(TAG, "Sleep timer is about to expire"); if (SleepTimerPreferences.vibrate() && !hasVibrated) { Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE); if (v != null) { v.vibrate(500); hasVibrated = true; } } if (shakeListener == null && SleepTimerPreferences.shakeToReset()) { shakeListener = new ShakeListener(context, this); } postCallback(() -> callback.onSleepTimerAlmostExpired(timeLeft)); } if (timeLeft <= 0) { Log.d(TAG, "Sleep timer expired"); if (shakeListener != null) { shakeListener.pause(); shakeListener = null; } hasVibrated = false; if (!Thread.currentThread().isInterrupted()) { postCallback(callback::onSleepTimerExpired); } else { Log.d(TAG, "Sleep timer interrupted"); } } } } public long getWaitingTime() { return timeLeft; } public void restart() { postCallback(() -> { setSleepTimer(waitingTime); callback.onSleepTimerReset(); }); if (shakeListener != null) { shakeListener.pause(); shakeListener = null; } } public void cancel() { sleepTimerFuture.cancel(true); if (shakeListener != null) { shakeListener.pause(); } postCallback(callback::onSleepTimerReset); } } public interface PSTMCallback { void positionSaverTick(); void onSleepTimerAlmostExpired(long timeLeft); void onSleepTimerExpired(); void onSleepTimerReset(); void onWidgetUpdaterTick(); void onChapterLoaded(Playable media); } }
package org.mustbe.consulo.csharp.lang.psi.impl; import org.jetbrains.annotations.NotNull; import org.mustbe.consulo.csharp.lang.CSharpLanguage; import org.mustbe.consulo.csharp.lang.psi.impl.source.CSharpUsingListImpl; import org.mustbe.consulo.csharp.lang.psi.impl.source.resolve.util.CSharpResolveUtil; import org.mustbe.consulo.csharp.lang.psi.impl.stub.index.CSharpIndexKeys; import org.mustbe.consulo.csharp.lang.psi.impl.stub.index.MemberByAllNamespaceQNameIndex; import org.mustbe.consulo.csharp.lang.psi.impl.stub.index.MemberByNamespaceQNameIndex; import org.mustbe.consulo.dotnet.lang.psi.impl.IndexBasedDotNetNamespaceAsElement; import org.mustbe.consulo.dotnet.psi.DotNetNamespaceUtil; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.psi.ResolveState; import com.intellij.psi.scope.PsiScopeProcessor; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.stubs.StringStubIndexExtension; import com.intellij.psi.stubs.StubIndex; import com.intellij.util.Processor; /** * @author VISTALL * @since 23.09.14 */ public class CSharpNamespaceAsElementImpl extends IndexBasedDotNetNamespaceAsElement { public CSharpNamespaceAsElementImpl(@NotNull Project project, @NotNull String indexKey, @NotNull String qName) { super(project, CSharpLanguage.INSTANCE, indexKey, qName); } @Override public boolean processDeclarations(@NotNull final PsiScopeProcessor processor, @NotNull final ResolveState state, final PsiElement lastParent, @NotNull final PsiElement place) { if(!super.processDeclarations(processor, state, lastParent, place)) { return false; } if(processor.getHint(CSharpResolveUtil.NO_USING_LIST) == Boolean.TRUE) { return true; } GlobalSearchScope searchScope = state.get(RESOLVE_SCOPE); return StubIndex.getInstance().processElements(CSharpIndexKeys.USING_LIST_INDEX, DotNetNamespaceUtil.getIndexableNamespace(myQName), myProject, searchScope, CSharpUsingListImpl.class, new Processor<CSharpUsingListImpl>() { @Override public boolean process(CSharpUsingListImpl usingList) { return usingList.processDeclarations(processor, state, lastParent, place); } }); } @NotNull @Override public StringStubIndexExtension<? extends PsiElement> getHardIndexExtension() { return MemberByNamespaceQNameIndex.getInstance(); } @NotNull @Override public StringStubIndexExtension<? extends PsiElement> getSoftIndexExtension() { return MemberByAllNamespaceQNameIndex.getInstance(); } }
// This source code is available under agreement available at // You should have received a copy of the agreement // along with this program; if not, write to Talend SA // 9 rue Pages 92150 Suresnes, France package org.talend.dataprep.schema.xls; import static org.junit.Assert.assertFalse; import java.io.IOException; import java.io.InputStream; import java.nio.file.*; import java.util.List; import java.util.stream.Collectors; import org.assertj.core.api.Assertions; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.talend.dataprep.api.dataset.ColumnMetadata; import org.talend.dataprep.api.dataset.DataSetMetadata; import org.talend.dataprep.schema.AbstractSchemaTestUtils; import org.talend.dataprep.schema.Schema; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.core.IsNull.notNullValue; import org.talend.dataprep.schema.SchemaParser; /** * Unit test for the XLSSchemaParser class. * * @see XlsSchemaParser */ public class XlsSchemaParserTest extends AbstractSchemaTestUtils { private final static Logger logger = LoggerFactory.getLogger( XlsSerializerTest.class); /** The parser to test. */ @Autowired private XlsSchemaParser parser; @Test public void should_parse_xls() throws IOException { checkColumnsName("simple.xls", "Film", "Producer"); } @Test public void shouldParseFileWithHeader() throws Exception { checkColumnsName("file_with_header.xlsx", "col_0", "col_1", "col_2", "col_3", "col_4"); } @Test public void shouldParseFileWithEmptyColumn() throws Exception { checkColumnsName("empty_column.xlsx", "First Name", "Last Name", "Company", "Email Address", "col_5", "Current Product", "Product to send"); } /** * Load the excel file and check the parsed columns name against the given ones. * * @param sourceFileName the excel file name to load. * @param expectedColsName the expected columns name. * @throws IOException if an error occurs while reading the excel file. */ private void checkColumnsName(String sourceFileName, String... expectedColsName) throws IOException { try (InputStream inputStream = this.getClass().getResourceAsStream(sourceFileName)) { checkColumnsName(inputStream, expectedColsName); } } /** * Load the excel file and check the parsed columns name against the given ones. * * @param inputStream the excel file name as inputStream * @param expectedColsName the expected columns name. * @throws IOException if an error occurs while reading the excel file. */ private void checkColumnsName(InputStream inputStream, String... expectedColsName) throws IOException { DataSetMetadata datasetMetadata = ioTestUtils.getSimpleDataSetMetadata(); Schema result = parser.parse(new SchemaParser.Request(inputStream, datasetMetadata)); List<ColumnMetadata> columns = result.getSheetContents().get(0).getColumnMetadatas(); final List<String> actual = columns.stream().map(ColumnMetadata::getName).collect(Collectors.toList()); Assertions.assertThat(actual).containsExactly(expectedColsName); } @Test public void read_xls_TDP_143() throws Exception { String fileName = "state_table.xls"; try (InputStream inputStream = this.getClass().getResourceAsStream(fileName)) { List<ColumnMetadata> columnMetadatas = parser.parse(getRequest(inputStream, "#852")) .getSheetContents().get(0).getColumnMetadatas(); Assertions.assertThat(columnMetadatas).isNotNull().isNotEmpty().hasSize(17); } } @Test public void read_xls_TDP_1957() throws Exception { String fileName = "email_with_empty_rows.xlsx"; try (InputStream inputStream = this.getClass().getResourceAsStream(fileName)) { List<ColumnMetadata> columnMetadatas = parser.parse(getRequest(inputStream, "#852")) .getSheetContents().get(0).getColumnMetadatas(); Assertions.assertThat(columnMetadatas).isNotNull().isNotEmpty().hasSize(2); } } @Test public void parse_should_extract_single_sheet_xls() throws Exception { // given final String fileName = "simple.xls"; SchemaParser.Request request; try (InputStream inputStream = this.getClass().getResourceAsStream(fileName)) { request = getRequest(inputStream, "My Dataset"); // when final Schema schema = parser.parse(request); // then assertThat(schema.getSheetContents(), is(notNullValue())); assertThat(schema.draft(), is(false)); assertThat(schema.getSheetName(), is("Feuille1")); } } @Test public void parse_should_extract_multi_sheet_xls() throws Exception { // given final String fileName = "Talend_Desk-Tableau-Bord-011214.xls"; SchemaParser.Request request; try (InputStream inputStream = this.getClass().getResourceAsStream(fileName)) { request = getRequest(inputStream, "My Dataset"); // when final Schema schema = parser.parse(request); // then assertThat(schema.getSheetContents(), is(notNullValue())); assertThat(schema.draft(), is(true)); assertThat(schema.getSheetName(), is("Sumary")); } } @Test public void should_not_accept_csv_update() throws Exception { final DataSetMetadata metadata = metadataBuilder.metadata().id("toto").formatFamilyId("formatGuess#csv").build(); assertFalse(parser.accept(metadata)); } @Test public void should_not_accept_xls_update() throws Exception { final DataSetMetadata metadata = metadataBuilder.metadata().id("tata").formatFamilyId("formatGuess#xls").build(); assertFalse(parser.accept(metadata)); } @Test public void should_not_accept_html_update() throws Exception { final DataSetMetadata metadata = metadataBuilder.metadata().id("tata").formatFamilyId("formatGuess#html").build(); assertFalse(parser.accept(metadata)); } @Test public void very_large_import() throws Exception { String fileName = "veryhuge.xlsx"; Path path = Paths.get(fileName); if (!Files.exists( path )){ logger.info( "file {} not available so skip the test" ); return; } try (InputStream inputStream = Files.newInputStream(path)) { String[] cols = {"id", "first_name", "last_name", "email", "job_title", "company", "city", "state", "country", "date", "campaign_id", "lead_score", "registration", "city", "birth", "nbCommands", "id", "first_name", "last_name", "email", "job_title", "company", "city", "state", "country", "date", "campaign_id", "lead_score", "registration", "city", "birth", "nbCommands", "id", "first_name", "last_name", "email", "job_title", "company", "city", "state", "country", "date", "campaign_id", "lead_score", "registration", "city", "birth", "nbCommands", "id", "first_name", "last_name", "email", "job_title", "company", "city", "state", "country", "date", "campaign_id", "lead_score", "registration", "city", "birth", "nbCommands", "id", "first_name", "last_name", "email", "job_title", "company", "city", "state", "country", "date", "campaign_id", "lead_score", "registration", "city", "birth", "nbCommands", "id", "first_name", "last_name", "email", "job_title", "company", "city", "state", "country", "date", "campaign_id", "lead_score", "registration", "city", "birth", "nbCommands", "id", "first_name", "last_name", "email"}; checkColumnsName(inputStream, cols); } } }
package org.datavaultplatform.webapp.controllers; import com.google.common.base.Strings; import com.google.gson.Gson; import org.apache.commons.lang.RandomStringUtils; import org.datavaultplatform.common.model.DataManager; import org.datavaultplatform.common.model.Dataset; import org.datavaultplatform.common.model.Group; import org.datavaultplatform.common.model.RetentionPolicy; import org.datavaultplatform.common.model.Retrieve; import org.datavaultplatform.common.model.RoleAssignment; import org.datavaultplatform.common.model.User; import org.datavaultplatform.common.model.Vault; import org.datavaultplatform.common.request.CreateVault; import org.datavaultplatform.common.request.TransferVault; import org.datavaultplatform.common.response.DepositInfo; import org.datavaultplatform.common.response.VaultInfo; import org.datavaultplatform.webapp.exception.InvalidUunException; import org.datavaultplatform.webapp.services.RestService; import org.datavaultplatform.webapp.services.UserLookupService; import org.hibernate.validator.constraints.NotEmpty; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import org.springframework.web.servlet.view.RedirectView; import javax.validation.ConstraintViolation; import javax.validation.Valid; import javax.validation.Validator; import javax.validation.constraints.AssertTrue; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; @Controller //@RequestMapping("/vaults") public class VaultsController { private static final Logger logger = LoggerFactory.getLogger(VaultsController.class); private RestService restService; private UserLookupService userLookupService; private String system; private String link; private String welcome; public void setSystem(String system) throws Exception { this.system = system; } public void setLink(String link) throws Exception { this.link = link; } public void setRestService(RestService restService) throws Exception { this.restService = restService; } public void setWelcome(String welcome) { this.welcome = welcome; } public void setUserLookupService(UserLookupService userLookupService) { this.userLookupService = userLookupService; } @PostMapping(value = "/vaults/{vaultid}/data-owner/update") public ResponseEntity transferOwnership( @PathVariable("vaultid") String vaultId, @Valid VaultTransferRequest request) { if (!request.isOrphaning()) { User newOwner = restService.getUser(request.user); if (newOwner == null) { return ResponseEntity.status(422).body("No such user)"); } boolean hasVaultRole = restService.getRoleAssignmentsForUser(request.user) .stream() .anyMatch(role -> { Vault vault = role.getVault(); return vault != null && vault.getID().equals(vaultId); }); if (hasVaultRole) { return ResponseEntity.status(422).body("User already has a role in this vault"); } } TransferVault transfer = new TransferVault(); transfer.setUserId(request.user); transfer.setRoleId(request.role); transfer.setChangingRoles(request.assigningRole); transfer.setOrphaning(request.orphaning); restService.transferVault(vaultId, transfer); return ResponseEntity.ok().build(); } @RequestMapping(value = "/vaults", method = RequestMethod.GET) public String getVaultsListing(ModelMap model) throws Exception { model.addAttribute("vaults", restService.getVaultsListing()); // pass the view an empty Vault since the form expects it model.addAttribute("vault", new CreateVault()); Dataset[] datasets = restService.getDatasets(); model.addAttribute("datasets", datasets); RetentionPolicy[] policies = restService.getRetentionPolicyListing(); model.addAttribute("policies", policies); Group[] groups = restService.getGroups(); model.addAttribute("groups", groups); model.put("system", system); model.put("link", link); model.addAttribute("welcome", welcome); return "vaults/index"; } @RequestMapping(value = "/vaults/{vaultid}", method = RequestMethod.GET) public String getVault(ModelMap model, @PathVariable("vaultid") String vaultID) throws Exception { VaultInfo vault = restService.getVault(vaultID); List<RoleAssignment> roleAssignmentsForVault = restService.getRoleAssignmentsForVault(vaultID); model.addAttribute("vault", vault); model.addAttribute("roles", restService.getVaultRoles()); model.addAttribute("roleAssignments", roleAssignmentsForVault); model.addAttribute(restService.getRetentionPolicy(vault.getPolicyID())); model.addAttribute(restService.getGroup(vault.getGroupID())); DepositInfo[] deposits = restService.getDepositsListing(vaultID); model.addAttribute("deposits", deposits); Map<String, Retrieve[]> depositRetrievals = new HashMap<String, Retrieve[]>(); for (DepositInfo deposit : deposits) { Retrieve[] retrievals = restService.getDepositRetrieves(deposit.getID()); depositRetrievals.put(deposit.getName(), retrievals); } model.addAttribute("retrievals", depositRetrievals); DataManager[] dataManagers = restService.getDataManagers(vaultID); List<User> dataManagerUsers = new ArrayList<>(); for(DataManager dm : dataManagers){ User u = restService.getUser(dm.getUUN()); if(u == null) { u = new User(); u.setID(dm.getUUN()); u.setAdmin(false); // Generate random password to make sure account is not easily accessible String password = RandomStringUtils.randomAscii(10); u.setPassword(password); restService.addUser(u); } dataManagerUsers.add(u); } model.addAttribute("dataManagers", dataManagerUsers); return "vaults/vault"; } @RequestMapping(value = "/vaults/{vaultid}/{userid}", method = RequestMethod.GET) public String getVault(ModelMap model, @PathVariable("vaultid") String vaultID,@PathVariable("userid") String userID) throws Exception { model.addAttribute("vaults", restService.getVaultsListingAll(userID)); return "vaults/userVaults"; } // Process the completed 'create new vault' page @RequestMapping(value = "/vaults/create", method = RequestMethod.POST) public String addVault(@ModelAttribute CreateVault vault, ModelMap model) throws Exception { VaultInfo newVault = restService.addVault(vault); String vaultUrl = "/vaults/" + newVault.getID() + "/"; return "redirect:" + vaultUrl; } @RequestMapping(value = "/vaults/{vaultid}/addDataManager", method = RequestMethod.POST) public RedirectView addDataManager(ModelMap model, @PathVariable("vaultid") String vaultID, @RequestParam("uun") String uun, final RedirectAttributes redirectAttrs) throws Exception { logger.debug("Adding "+uun+" as DM"); String vaultUrl = "/vaults/" + vaultID + "/"; DataManager[] dataManagers = restService.getDataManagers(vaultID); logger.debug("Check if already DM"); for( DataManager dm : dataManagers ){ logger.debug("DM: "+dm.getUUN()); if(dm.getUUN().equals(uun)){ logger.info("User " + uun + " is already a Data Manager"); redirectAttrs.addFlashAttribute("warning", "<i>"+uun+"</i> is already a Data Manager of this Vault!"); return new RedirectView(vaultUrl, true); } } try { userLookupService.ensureUserExists(uun); } catch (InvalidUunException e) { redirectAttrs.addFlashAttribute("error", "<i>'" + uun + "'</i> doesnt seem to be a valid UUN!"); return new RedirectView(vaultUrl, true); } restService.addDataManager(vaultID, uun); redirectAttrs.addFlashAttribute("success", "<strong>'"+uun+"'</strong> added as Data Manager of this Vault!"); return new RedirectView(vaultUrl, true); } @RequestMapping(value = "/vaults/{vaultid}/deleteDataManager", method = RequestMethod.POST) public RedirectView deleteDataManager(ModelMap model, @PathVariable("vaultid") String vaultID, @RequestParam("uun") String uun, final RedirectAttributes redirectAttrs) throws Exception { logger.info("Get Data Manager with id: "+uun); DataManager dataManager = restService.getDataManager(vaultID, uun); logger.info("Deleting Data Manager..."); restService.deleteDataManager(vaultID, dataManager.getID()); String vaultUrl = "/vaults/" + vaultID + "/"; redirectAttrs.addFlashAttribute("success", "<strong>'"+uun+"'</strong> is no longer a Data Manager of this Vault!"); return new RedirectView(vaultUrl, true); } @RequestMapping(value = "/vaults/{vaultid}/updateVaultDescription", method = RequestMethod.POST) public String updateVaultDescription(ModelMap model, @PathVariable("vaultid") String vaultID, @RequestParam("description") String description ) throws Exception { VaultInfo vault = restService.updateVaultDescription(vaultID, description); String vaultUrl = "/vaults/" + vault.getID() + "/"; return "redirect:" + vaultUrl; } @RequestMapping(value = "/vaults/autocompleteuun/{term}", method = RequestMethod.GET) @ResponseBody public String autocompleteUUN(@PathVariable("term") String term) { List<String> result = userLookupService.getSuggestedUuns(term); Gson gson = new Gson(); return gson.toJson(result); } private static class VaultTransferRequest { private Long role; private String user; private boolean assigningRole; private boolean orphaning; private String reason; public void setOrphaning(boolean orphaning) { this.orphaning = orphaning; } public boolean isOrphaning() { return orphaning; } public void setAssigningRole(boolean assigningRole) { this.assigningRole = assigningRole; } public void setRole(Long role) { this.role = role; } public void setUser(String user) { this.user = user; } public Long getRole() { return role; } public String getUser() { return user; } @NotEmpty(message = "Must provide a transfer reason.") public String getReason() { return reason; } public void setReason(String reason) { this.reason = reason; } public boolean isAssigningRole() { return assigningRole; } @AssertTrue(message = "Must select a user.") public boolean isUserSelectionValid() { return orphaning || !Strings.isNullOrEmpty(user); } @AssertTrue(message = "Must select a role when assigning a new role.") public boolean isRoleSelectionValid() { return !assigningRole || role != null; } } }
package de.gurkenlabs.litiengine.sound; import java.awt.geom.Point2D; import java.util.function.Supplier; import javax.sound.sampled.FloatControl; import javax.sound.sampled.LineUnavailableException; import de.gurkenlabs.litiengine.Game; public class SFXPlayback extends SoundPlayback { private Sound sound; private FloatControl panControl; private Supplier<Point2D> source; private VolumeControl distance; private boolean loop; SFXPlayback(Sound sound, Supplier<Point2D> source, boolean loop) throws LineUnavailableException { super(sound.getFormat()); this.loop = loop; this.sound = sound; this.panControl = this.line.isControlSupported(FloatControl.Type.PAN) ? (FloatControl) this.line.getControl(FloatControl.Type.PAN) : null; this.source = source; this.distance = this.createVolumeControl(); } @Override public void run() { do { if (this.play(this.sound)) { return; } } while (this.loop); this.finish(); } void updateLocation(Point2D listenerLocation) { Point2D location = source.get(); if (location != null) { double dx = location.getX() - listenerLocation.getX(); double dy = location.getY() - listenerLocation.getY(); double dist = Math.sqrt(dx * dx + dy * dy); if (this.panControl != null) { this.panControl.setValue(dist > 0 ? (float) (dx / dist) : 0f); } this.distance.set(Game.config().sound().getSoundVolume() * (float) Math.max(1.0 - dist / Game.audio().getMaxDistance(), 0.0)); } else { this.distance.set(Game.config().sound().getSoundVolume()); } } }
package de.lmu.ifi.dbs.algorithm.clustering; import de.lmu.ifi.dbs.algorithm.Algorithm; import de.lmu.ifi.dbs.algorithm.DistanceBasedAlgorithm; import de.lmu.ifi.dbs.algorithm.result.ClustersPlusNoise; import de.lmu.ifi.dbs.algorithm.result.Result; import de.lmu.ifi.dbs.data.MetricalObject; import de.lmu.ifi.dbs.database.Database; import de.lmu.ifi.dbs.distance.Distance; import de.lmu.ifi.dbs.utilities.Description; import de.lmu.ifi.dbs.utilities.Progress; import de.lmu.ifi.dbs.utilities.QueryResult; import de.lmu.ifi.dbs.utilities.Util; import de.lmu.ifi.dbs.utilities.optionhandling.AttributeSettings; import de.lmu.ifi.dbs.utilities.optionhandling.OptionHandler; import de.lmu.ifi.dbs.utilities.optionhandling.UnusedParameterException; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; /** * DBSCAN provides the DBSCAN algorithm. * * @author Arthur Zimek (<a * href="mailto:zimek@dbs.ifi.lmu.de">zimek@dbs.ifi.lmu.de</a>) */ public class DBSCAN<O extends MetricalObject, D extends Distance<D>> extends DistanceBasedAlgorithm<O, D> { /** * Parameter for epsilon. */ public static final String EPSILON_P = "epsilon"; /** * Description for parameter epsilon. */ public static final String EPSILON_D = "<epsilon>an epsilon value suitable to the specified distance function"; /** * Parameter minimum points. */ public static final String MINPTS_P = "minpts"; /** * Description for parameter minimum points. */ public static final String MINPTS_D = "<int>minpts"; /** * Epsilon. */ protected String epsilon; /** * Minimum points. */ protected int minpts; /** * Holds a list of clusters found. */ protected List<List<Integer>> resultList; /** * Provides the result of the algorithm. */ protected ClustersPlusNoise<O> result; /** * Holds a set of noise. */ protected Set<Integer> noise; /** * Holds a set of processed ids. */ protected Set<Integer> processedIDs; /** * Sets epsilon and minimum points to the optionhandler additionally to the * parameters provided by super-classes. Since DBSCAN is a non-abstract * class, finally optionHandler is initialized. */ public DBSCAN() { super(); parameterToDescription.put(EPSILON_P + OptionHandler.EXPECTS_VALUE, EPSILON_D); parameterToDescription.put(MINPTS_P + OptionHandler.EXPECTS_VALUE, MINPTS_D); optionHandler = new OptionHandler(parameterToDescription, this.getClass().getName()); } /** * @see Algorithm#run(de.lmu.ifi.dbs.database.Database) */ public void runInTime(Database<O> database) throws IllegalStateException { if (isVerbose()) { System.out.println(); } try { Progress progress = new Progress(database.size()); resultList = new ArrayList<List<Integer>>(); noise = new HashSet<Integer>(); processedIDs = new HashSet<Integer>(database.size()); getDistanceFunction().setDatabase(database, isVerbose()); if (isVerbose()) { System.out.println("\nClustering:"); } if (database.size() >= minpts) { for (Iterator<Integer> iter = database.iterator(); iter.hasNext();) { Integer id = iter.next(); if (!processedIDs.contains(id)) { expandCluster(database, id, progress); if (processedIDs.size() == database.size() && noise.size() == 0) { break; } } if (isVerbose()) { progress.setProcessed(processedIDs.size()); System.out.print(Util.status(progress, resultList.size())); } } } else { for (Iterator<Integer> iter = database.iterator(); iter.hasNext();) { Integer id = iter.next(); noise.add(id); if (isVerbose()) { progress.setProcessed(processedIDs.size()); System.out.print(Util.status(progress, resultList.size())); } } } if (isVerbose()) { progress.setProcessed(processedIDs.size()); System.out.print(Util.status(progress, resultList.size())); } Integer[][] resultArray = new Integer[resultList.size() + 1][]; int i = 0; for (Iterator<List<Integer>> resultListIter = resultList.iterator(); resultListIter.hasNext(); i++) { resultArray[i] = resultListIter.next().toArray(new Integer[0]); } resultArray[resultArray.length - 1] = noise.toArray(new Integer[0]); result = new ClustersPlusNoise<O>(resultArray, database); if (isVerbose()) { progress.setProcessed(processedIDs.size()); System.out.print(Util.status(progress, resultList.size())); System.out.println(); } } catch (Exception e) { throw new IllegalStateException(e); } } /** * DBSCAN-function expandCluster. <p/> Border-Objects become members of the * first possible cluster. * * @param database the database on which the algorithm is run * @param startObjectID potential seed of a new potential cluster */ protected void expandCluster(Database<O> database, Integer startObjectID, Progress progress) { List<QueryResult<D>> seeds = database.rangeQuery(startObjectID, epsilon, getDistanceFunction()); // startObject is no core-object if (seeds.size() < minpts) { noise.add(startObjectID); processedIDs.add(startObjectID); if (isVerbose()) { progress.setProcessed(processedIDs.size()); System.out.print(Util.status(progress, resultList.size())); } return; } List<Integer> currentCluster = new ArrayList<Integer>(); for (QueryResult seed : seeds) { Integer nextID = seed.getID(); if (!processedIDs.contains(nextID)) { currentCluster.add(nextID); processedIDs.add(nextID); } else if (noise.contains(nextID)) { currentCluster.add(nextID); noise.remove(nextID); } } seeds.remove(0); while (seeds.size() > 0) { Integer o = seeds.remove(0).getID(); List<QueryResult<D>> neighborhood = database.rangeQuery(o, epsilon, getDistanceFunction()); if (neighborhood.size() >= minpts) { for (QueryResult<D> neighbor : neighborhood) { Integer p = neighbor.getID(); boolean inNoise = noise.contains(p); boolean unclassified = !processedIDs.contains(p); if (inNoise || unclassified) { if (unclassified) { seeds.add(neighbor); } currentCluster.add(p); processedIDs.add(p); if (inNoise) { noise.remove(p); } } } } if (isVerbose()) { progress.setProcessed(processedIDs.size()); int numClusters = currentCluster.size() > minpts ? resultList.size() + 1 : resultList.size(); System.out.print(Util.status(progress, numClusters)); } if (processedIDs.size() == database.size() && noise.size() == 0) { break; } } if (currentCluster.size() >= minpts) { resultList.add(currentCluster); } else { for (Integer id : currentCluster) { noise.add(id); } noise.add(startObjectID); processedIDs.add(startObjectID); } } /** * @see Algorithm#getDescription() */ public Description getDescription() { return new Description("DBSCAN", "Density-Based Clustering of Applications with Noise", "Algorithm to find density-connected sets in a database based on the parameters " + "minimumPoints and epsilon (specifying a volume). " + "These two parameters determine a density threshold for clustering.", "M. Ester, H.-P. Kriegel, J. Sander, and X. Xu: " + "A Density-Based Algorithm for Discovering Clusters in Large Spatial Databases with Noise. " + "In: Proc. 2nd Int. Conf. on Knowledge Discovery and Data Mining (KDD '96), " + "Portland, OR, 1996."); } /** * Sets the parameters epsilon and minpts additionally to the parameters set * by the super-class' method. Both epsilon and minpts are required * parameters. * * @see de.lmu.ifi.dbs.utilities.optionhandling.Parameterizable#setParameters(String[]) */ @Override public String[] setParameters(String[] args) throws IllegalArgumentException { String[] remainingParameters = super.setParameters(args); try { // test whether epsilon is compatible with distance function getDistanceFunction().valueOf(optionHandler.getOptionValue(EPSILON_P)); epsilon = optionHandler.getOptionValue(EPSILON_P); minpts = Integer.parseInt(optionHandler.getOptionValue(MINPTS_P)); } catch (UnusedParameterException e) { throw new IllegalArgumentException(e); } catch (NumberFormatException e) { throw new IllegalArgumentException(e); } return remainingParameters; } /** * @see de.lmu.ifi.dbs.algorithm.Algorithm#getResult() */ public Result<O> getResult() { return result; } /** * Returns the parameter setting of this algorithm. * * @return the parameter setting of this algorithm */ public List<AttributeSettings> getAttributeSettings() { List<AttributeSettings> result = super.getAttributeSettings(); AttributeSettings attributeSettings = result.get(0); attributeSettings.addSetting(EPSILON_P, epsilon); attributeSettings.addSetting(MINPTS_P, Integer.toString(minpts)); result.add(attributeSettings); return result; } }
package de.lmu.ifi.dbs.elki.algorithm.outlier; import java.util.ArrayList; import java.util.Collections; import java.util.List; import de.lmu.ifi.dbs.elki.algorithm.DistanceBasedAlgorithm; import de.lmu.ifi.dbs.elki.data.DatabaseObject; import de.lmu.ifi.dbs.elki.database.AssociationID; import de.lmu.ifi.dbs.elki.database.Database; import de.lmu.ifi.dbs.elki.database.DistanceResultPair; import de.lmu.ifi.dbs.elki.database.datastore.DataStoreFactory; import de.lmu.ifi.dbs.elki.database.datastore.DataStoreUtil; import de.lmu.ifi.dbs.elki.database.datastore.WritableDataStore; import de.lmu.ifi.dbs.elki.database.datastore.WritableRecordStore; import de.lmu.ifi.dbs.elki.database.ids.DBID; import de.lmu.ifi.dbs.elki.distance.distancevalue.NumberDistance; import de.lmu.ifi.dbs.elki.logging.progress.FiniteProgress; import de.lmu.ifi.dbs.elki.result.AnnotationFromDataStore; import de.lmu.ifi.dbs.elki.result.AnnotationResult; import de.lmu.ifi.dbs.elki.result.OrderingFromDataStore; import de.lmu.ifi.dbs.elki.result.OrderingResult; import de.lmu.ifi.dbs.elki.result.outlier.OutlierResult; import de.lmu.ifi.dbs.elki.result.outlier.OutlierScoreMeta; import de.lmu.ifi.dbs.elki.result.outlier.QuotientOutlierScoreMeta; import de.lmu.ifi.dbs.elki.utilities.documentation.Description; import de.lmu.ifi.dbs.elki.utilities.documentation.Reference; import de.lmu.ifi.dbs.elki.utilities.documentation.Title; import de.lmu.ifi.dbs.elki.utilities.optionhandling.OptionID; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameterization.Parameterization; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.DistanceParameter; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.DoubleParameter; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.IntParameter; import de.lmu.ifi.dbs.elki.utilities.pairs.DoubleIntPair; /** * Fast Outlier Detection Using the "Local Correlation Integral". * * Exact implementation only, not aLOCI. * * Outlier detection using multiple epsilon neighborhoods. * * Based on: S. Papadimitriou, H. Kitagawa, P. B. Gibbons and C. Faloutsos: * LOCI: Fast Outlier Detection Using the Local Correlation Integral. In: Proc. * 19th IEEE Int. Conf. on Data Engineering (ICDE '03), Bangalore, India, 2003. * * @author Erich Schubert * * @param <O> Object type * @param <D> Distance type */ @Title("LOCI: Fast Outlier Detection Using the Local Correlation Integral") @Description("Algorithm to compute outliers based on the Local Correlation Integral") @Reference(authors = "S. Papadimitriou, H. Kitagawa, P. B. Gibbons, C. Faloutsos", title = "LOCI: Fast Outlier Detection Using the Local Correlation Integral", booktitle = "Proc. 19th IEEE Int. Conf. on Data Engineering (ICDE '03), Bangalore, India, 2003", url = "http://dx.doi.org/10.1109/ICDE.2003.1260802") public class LOCI<O extends DatabaseObject, D extends NumberDistance<D, ?>> extends DistanceBasedAlgorithm<O, D, OutlierResult> { /** * OptionID for {@link #RMAX_PARAM} */ public static final OptionID RMAX_ID = OptionID.getOrCreateOptionID("loci.rmax", "The maximum radius of the neighborhood to be considered."); /** * OptionID for {@link #NMIN_PARAM} */ public static final OptionID NMIN_ID = OptionID.getOrCreateOptionID("loci.nmin", "Minimum neighborhood size to be considered."); /** * OptionID for {@link #ALPHA_PARAM} */ public static final OptionID ALPHA_ID = OptionID.getOrCreateOptionID("loci.alpha", "Scaling factor for averaging neighborhood"); /** * Parameter to specify the maximum radius of the neighborhood to be * considered, must be suitable to the distance function specified. * <p> * Key: {@code -loci.rmax} * </p> */ private final DistanceParameter<D> RMAX_PARAM = new DistanceParameter<D>(RMAX_ID, getDistanceFactory()); /** * Holds the value of {@link #RMAX_PARAM}. */ private D rmax; /** * Parameter to specify the minimum neighborhood size * <p> * Key: {@code -loci.nmin} * </p> * <p> * Default: {@code 20} * </p> */ private final IntParameter NMIN_PARAM = new IntParameter(NMIN_ID, 20); /** * Holds the value of {@link #NMIN_PARAM}. */ private double nmin; /** * Parameter to specify the averaging neighborhood scaling * <p> * Key: {@code -loci.alpha} * </p> * <p> * Default: {@code 0.5} * </p> */ private final DoubleParameter ALPHA_PARAM = new DoubleParameter(ALPHA_ID, 0.5); /** * Holds the value of {@link #ALPHA_PARAM}. */ private double alpha; /** * The LOCI MDEF / SigmaMDEF maximum values radius */ public static final AssociationID<Double> LOCI_MDEF_CRITICAL_RADIUS = AssociationID.getOrCreateAssociationID("loci.mdefrad", Double.class); /** * The LOCI MDEF / SigmaMDEF maximum value (normalized MDEF) */ public static final AssociationID<Double> LOCI_MDEF_NORM = AssociationID.getOrCreateAssociationID("loci.mdefnorm", Double.class); /** * Constructor, adhering to * {@link de.lmu.ifi.dbs.elki.utilities.optionhandling.Parameterizable} * * @param config Parameterization */ public LOCI(Parameterization config) { super(config); // maximum query range if(config.grab(RMAX_PARAM)) { rmax = RMAX_PARAM.getValue(); } // minimum neighborhood size if(config.grab(NMIN_PARAM)) { nmin = NMIN_PARAM.getValue(); } // scaling factor for averaging range if(config.grab(ALPHA_PARAM)) { alpha = ALPHA_PARAM.getValue(); } } /** * Runs the algorithm in the timed evaluation part. */ @Override protected OutlierResult runInTime(Database<O> database) throws IllegalStateException { getDistanceFunction().setDatabase(database); FiniteProgress progressPreproc = logger.isVerbose() ? new FiniteProgress("LOCI preprocessing", database.size(), logger) : null; // LOCI preprocessing step WritableDataStore<ArrayList<DoubleIntPair>> interestingDistances = DataStoreUtil.makeStorage(database.getIDs(), DataStoreFactory.HINT_TEMP | DataStoreFactory.HINT_SORTED, ArrayList.class); for(DBID id : database.getIDs()) { List<DistanceResultPair<D>> neighbors = database.rangeQuery(id, rmax, getDistanceFunction()); // build list of critical distances ArrayList<DoubleIntPair> cdist = new ArrayList<DoubleIntPair>(neighbors.size() * 2); { int i = 0; for(DistanceResultPair<D> r : neighbors) { assert(i != Integer.MIN_VALUE); cdist.add(new DoubleIntPair(r.getDistance().doubleValue(), i)); cdist.add(new DoubleIntPair(r.getDistance().doubleValue() / alpha, Integer.MIN_VALUE)); i++; } } Collections.sort(cdist); // fill the gaps to have fast lookups of number of neighbors at a given // distance. int lastk = 0; for(DoubleIntPair c : cdist) { if(c.second == Integer.MIN_VALUE) { c.second = lastk; } else { lastk = c.second; } } interestingDistances.put(id, cdist); if(progressPreproc != null) { progressPreproc.incrementProcessed(logger); } } if(progressPreproc != null) { progressPreproc.ensureCompleted(logger); } // LOCI main step FiniteProgress progressLOCI = logger.isVerbose() ? new FiniteProgress("LOCI scores", database.size(), logger) : null; WritableRecordStore store = DataStoreUtil.makeRecordStorage(database.getIDs(), DataStoreFactory.HINT_STATIC, Double.class, Double.class); WritableDataStore<Double> mdef_norm = store.getStorage(0, Double.class); WritableDataStore<Double> mdef_radius = store.getStorage(1, Double.class); for(DBID id : database.getIDs()) { double maxmdefnorm = 0.0; double maxnormr = 0; List<DoubleIntPair> cdist = interestingDistances.get(id); double maxdist = cdist.get(cdist.size()-1).first; // Compute the largest neighborhood we will need. List<DistanceResultPair<D>> maxneighbors = database.rangeQuery(id, Double.toString(maxdist), getDistanceFunction()); for(DoubleIntPair c : cdist) { double alpha_r = alpha * c.first; // compute n(p_i, \alpha * r) from list int n_alphar = 0; for(DoubleIntPair c2 : cdist) { if(c2.first <= alpha_r) { n_alphar = c2.second; } else { break; } } // compute \hat{n}(p_i, r, \alpha) double nhat_r_alpha = 0.0; double sigma_nhat_r_alpha = 0.0; // note that the query range is c.first //List<DistanceResultPair<D>> rneighbors = database.rangeQuery(id, Double.toString(c.first), getDistanceFunction()); List<DistanceResultPair<D>> rneighbors = null; for (int i = 0; i < maxneighbors.size(); i++) { DistanceResultPair<D> ne = maxneighbors.get(i); if (ne.getDistance().doubleValue() > c.first) { if (i >= nmin) { rneighbors = maxneighbors.subList(0, i); } else { rneighbors = null; } break; } } if (rneighbors == null) { continue; } // redundant check. if(rneighbors.size() < nmin) { continue; } for(DistanceResultPair<D> rn : rneighbors) { List<DoubleIntPair> rncdist = interestingDistances.get(rn.getID()); int rn_alphar = 0; for(DoubleIntPair c2 : rncdist) { if(c2.first <= alpha_r) { rn_alphar = c2.second; } else { break; } } nhat_r_alpha = nhat_r_alpha + rn_alphar; sigma_nhat_r_alpha = sigma_nhat_r_alpha + (rn_alphar * rn_alphar); } // finalize average and deviation nhat_r_alpha = nhat_r_alpha / rneighbors.size(); sigma_nhat_r_alpha = Math.sqrt(sigma_nhat_r_alpha / rneighbors.size() - nhat_r_alpha * nhat_r_alpha); double mdef = 1.0 - (n_alphar / nhat_r_alpha); double sigmamdef = sigma_nhat_r_alpha / nhat_r_alpha; double mdefnorm = mdef / sigmamdef; if(mdefnorm > maxmdefnorm) { maxmdefnorm = mdefnorm; maxnormr = c.first; } } // FIXME: when nmin was never fulfilled, the values will remain 0. mdef_norm.put(id, maxmdefnorm); mdef_radius.put(id, maxnormr); if(progressLOCI != null) { progressLOCI.incrementProcessed(logger); } } if(progressLOCI != null) { progressLOCI.ensureCompleted(logger); } AnnotationResult<Double> scoreResult = new AnnotationFromDataStore<Double>(LOCI_MDEF_NORM, mdef_norm); OrderingResult orderingResult = new OrderingFromDataStore<Double>(mdef_norm, true); // TODO: actually provide min and max? OutlierScoreMeta scoreMeta = new QuotientOutlierScoreMeta(Double.NaN, Double.NaN, 0.0, Double.POSITIVE_INFINITY, 0.0); OutlierResult result = new OutlierResult(scoreMeta, scoreResult, orderingResult); result.addResult(new AnnotationFromDataStore<Double>(LOCI_MDEF_CRITICAL_RADIUS, mdef_radius)); return result; } }
package de.lmu.ifi.dbs.elki.persistent; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel.MapMode; import java.nio.channels.FileLock; import de.lmu.ifi.dbs.elki.utilities.exceptions.ExceptionMessages; /** * On Disc Array storage for records of a given size. * * This can be used to implement various fixed size record-based data * structures. The file format is designed to have a fixed-size header followed * by the actual data. * * @author Erich Schubert * * @apiviz.composedOf RandomAccessFile */ // TODO: ensure file doesn't become to big - check for overflows in recordsize * // numrecs + headersize public class OnDiskArray { /** * Serial version. * * NOTE: Change this version whenever the file structure is changed in an * incompatible way: This will modify the file magic, and thus prevent * applications from reading incompatible files. */ private static final long serialVersionUID = 7586497243452875056L; /** * Magic number used to identify files. */ protected int magic; /** * Size of the header in the file. Note that the internal header is four * integers already. */ private int headersize; /** * Size of the records in the file. */ private int recordsize; /** * Number of records in the file. */ private int numrecs; /** * File name. */ private File filename; /** * Random Access File object. */ final private RandomAccessFile file; /** * Lock for the file that will be kept while writing. */ private FileLock lock = null; /** * Writable or read-only object. */ private boolean writable; /** * The memory mapped buffer. */ private MappedByteBuffer map; /** * Size of the classes header size. */ private static final int INTERNAL_HEADER_SIZE = 4 * ByteArrayUtil.SIZE_INT; /** * Position of file size (in records). */ private static final int HEADER_POS_SIZE = 3 * ByteArrayUtil.SIZE_INT; /** * Constructor to write a new file. * * @param filename File name to be opened. * @param magicseed Magic number to derive real magic from. * @param extraheadersize header size NOT including the internal header * @param recordsize Record size * @param initialsize Initial file size (in records) * @throws IOException on IO errors */ public OnDiskArray(File filename, int magicseed, int extraheadersize, int recordsize, int initialsize) throws IOException { this.magic = mixMagic((int) serialVersionUID, magicseed); this.headersize = extraheadersize + INTERNAL_HEADER_SIZE; this.recordsize = recordsize; this.filename = filename; this.writable = true; // do not allow overwriting, unless empty if (filename.exists() && filename.length() > 0) { throw new IOException(ExceptionMessages.FILE_EXISTS); } // open file. file = new RandomAccessFile(filename, "rw"); // and acquire a file write lock lock = file.getChannel().lock(); // write magic header file.writeInt(this.magic); // write header size file.writeInt(this.headersize); // write size of a single record file.writeInt(this.recordsize); // write number of records // verify position. if (file.getFilePointer() != HEADER_POS_SIZE) { // TODO: more appropriate exception class? throw new IOException("File position doesn't match when writing file size."); } file.writeInt(initialsize); // we should have written the complete internal header now. if (file.getFilePointer() != INTERNAL_HEADER_SIZE) { // TODO: more appropriate exception class? throw new IOException("File position doesn't match header size after writing header."); } // resize file resizeFile(initialsize); // map array mapArray(); } /** * Constructor to open an existing file. The provided record size must match * the record size stored within the files header. If you don't know this size * yet and/or need to access the extra header you should use the other * constructor below * * @param filename File name to be opened. * @param magicseed Magic number to derive real magic from. * @param extraheadersize header size NOT including the internal header * @param recordsize Record size * @param writable flag to open the file writable * @throws IOException on IO errors */ public OnDiskArray(File filename, int magicseed, int extraheadersize, int recordsize, boolean writable) throws IOException { this.magic = mixMagic((int) serialVersionUID, magicseed); this.headersize = extraheadersize + INTERNAL_HEADER_SIZE; this.recordsize = recordsize; this.filename = filename; this.writable = writable; String mode = writable ? "rw" : "r"; file = new RandomAccessFile(filename, mode); if (writable) { // acquire a file write lock lock = file.getChannel().lock(); } validateHeader(true); mapArray(); } /** * Constructor to open an existing file. The record size is read from the * file's header and can be obtained by <code>getRecordsize()</code> * * @param filename File name to be opened. * @param magicseed Magic number to derive real magic from. * @param extraheadersize header size NOT including the internal header * @param writable flag to open the file writable * @throws IOException on IO errors */ public OnDiskArray(File filename, int magicseed, int extraheadersize, boolean writable) throws IOException { this.magic = mixMagic((int) serialVersionUID, magicseed); this.headersize = extraheadersize + INTERNAL_HEADER_SIZE; this.filename = filename; this.writable = writable; String mode = writable ? "rw" : "r"; file = new RandomAccessFile(filename, mode); if (writable) { // acquire a file write lock lock = file.getChannel().lock(); } validateHeader(false); mapArray(); } /** * (Re-) map the data array. * * @throws IOException on mapping error. */ private synchronized void mapArray() throws IOException { if (map != null) { ByteArrayUtil.unmapByteBuffer(map); map = null; } MapMode mode = writable ? MapMode.READ_WRITE : MapMode.READ_ONLY; map = file.getChannel().map(mode, headersize, recordsize * numrecs); } /** * Validates the header and throws an IOException if the header is invalid. If * validateRecordSize is set to true the record size must match exactly the * stored record size within the files header, else the record size is read * from the header and used. * * @param validateRecordSize * @throws IOException */ private void validateHeader(boolean validateRecordSize) throws IOException { int readmagic = file.readInt(); // Validate magic number if (readmagic != this.magic) { file.close(); throw new IOException("Magic in LinearDiskCache does not match: " + readmagic + " instead of " + this.magic); } // Validate header size if (file.readInt() != this.headersize) { file.close(); throw new IOException("Header size in LinearDiskCache does not match."); } if (validateRecordSize) { // Validate record size if (file.readInt() != this.recordsize) { file.close(); throw new IOException("Recordsize in LinearDiskCache does not match."); } } else { // or just read it from file this.recordsize = file.readInt(); } // read the number of records and validate with file size. if (file.getFilePointer() != HEADER_POS_SIZE) { throw new IOException("Incorrect file position when reading header."); } this.numrecs = file.readInt(); if (numrecs < 0 || file.length() != indexToFileposition(numrecs)) { throw new IOException("File size and number of records do not agree."); } // yet another sanity check. We should have read all of our internal header // now. if (file.getFilePointer() != INTERNAL_HEADER_SIZE) { throw new IOException("Incorrect file position after reading header."); } } /** * Mix two magic numbers into one, to obtain a combined magic. Note: * mixMagic(a,b) != mixMagic(b,a) usually. * * @param magic1 Magic number to mix. * @param magic2 Magic number to mix. * @return Mixed magic number. */ public static final int mixMagic(int magic1, int magic2) { final long prime = 2654435761L; long result = 1; result = prime * result + magic1; result = prime * result + magic2; return (int) result; } /** * Compute file position from index number * * @param index Index offset * @return file position */ private long indexToFileposition(long index) { long pos = headersize + index * recordsize; return pos; } /** * Resize file to the intended size * * @param newsize New file size. * @throws IOException on IO errors */ public synchronized void resizeFile(int newsize) throws IOException { if (!writable) { throw new IOException("File is not writeable!"); } // update the number of records this.numrecs = newsize; file.seek(HEADER_POS_SIZE); file.writeInt(numrecs); // resize file file.setLength(indexToFileposition(numrecs)); mapArray(); } /** * Get a record buffer * * @param index Record index * @return Byte buffer for the record * @throws IOException on IO errors */ public synchronized ByteBuffer getRecordBuffer(int index) throws IOException { if (index < 0 || index >= numrecs) { throw new IOException("Access beyond end of file."); } // Adjust buffer view synchronized (map) { map.limit(recordsize * (index + 1)); map.position(recordsize * index); return map.slice(); } } /** * Return the size of the extra header. Accessor. * * @return Extra header size */ protected int getExtraHeaderSize() { return headersize - INTERNAL_HEADER_SIZE; } /** * Read the extra header data. * * @return additional header data * @throws IOException on IO errors */ public synchronized ByteBuffer getExtraHeader() throws IOException { final int size = headersize - INTERNAL_HEADER_SIZE; final MapMode mode = writable ? MapMode.READ_WRITE : MapMode.READ_ONLY; return file.getChannel().map(mode, INTERNAL_HEADER_SIZE, size); } /** * Get the size of a single record. * * @return Record size. */ protected int getRecordsize() { return recordsize; } /** * Get the file name. * * @return File name */ public File getFilename() { return filename; } /** * Check if the file is writable. * * @return true if the file is writable. */ public boolean isWritable() { return writable; } /** * Explicitly close the file. Note: following operations will likely cause * IOExceptions. * * @throws IOException on IO errors */ public synchronized void close() throws IOException { writable = false; if (lock != null) { lock.release(); lock = null; } file.close(); } /** * Get number of records in file. * * @return Number of records in the file. */ public int getNumRecords() { return numrecs; } /** * Ensure that the file can fit the given number of records. * * @param size Size * @throws IOException */ public void ensureSize(int size) throws IOException { if (size > getNumRecords()) { resizeFile(size); } } }
package org.geomajas.gwt.client.widget; import java.util.ArrayList; import java.util.List; import org.geomajas.command.CommandResponse; import org.geomajas.command.dto.SearchFeatureRequest; import org.geomajas.command.dto.SearchFeatureResponse; import org.geomajas.gwt.client.command.CommandCallback; import org.geomajas.gwt.client.command.GwtCommand; import org.geomajas.gwt.client.command.GwtCommandDispatcher; import org.geomajas.gwt.client.i18n.I18nProvider; import org.geomajas.gwt.client.map.MapModel; import org.geomajas.gwt.client.map.event.LayerDeselectedEvent; import org.geomajas.gwt.client.map.event.LayerSelectedEvent; import org.geomajas.gwt.client.map.event.LayerSelectionHandler; import org.geomajas.gwt.client.map.event.MapModelEvent; import org.geomajas.gwt.client.map.event.MapModelHandler; import org.geomajas.gwt.client.map.feature.Feature; import org.geomajas.gwt.client.map.layer.Layer; import org.geomajas.gwt.client.map.layer.VectorLayer; import org.geomajas.gwt.client.widget.attribute.AttributeCriterionPane; import org.geomajas.gwt.client.widget.event.SearchEvent; import org.geomajas.gwt.client.widget.event.SearchHandler; import org.geomajas.layer.feature.SearchCriterion; import com.google.gwt.event.shared.HandlerRegistration; import com.smartgwt.client.types.Alignment; import com.smartgwt.client.types.VerticalAlignment; import com.smartgwt.client.util.SC; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.HTMLPane; import com.smartgwt.client.widgets.IButton; import com.smartgwt.client.widgets.events.ClickEvent; import com.smartgwt.client.widgets.events.ClickHandler; import com.smartgwt.client.widgets.form.DynamicForm; import com.smartgwt.client.widgets.form.fields.BlurbItem; import com.smartgwt.client.widgets.form.fields.FormItem; import com.smartgwt.client.widgets.form.fields.RadioGroupItem; import com.smartgwt.client.widgets.form.fields.SelectItem; import com.smartgwt.client.widgets.form.fields.events.ChangedEvent; import com.smartgwt.client.widgets.form.fields.events.ChangedHandler; import com.smartgwt.client.widgets.layout.HLayout; import com.smartgwt.client.widgets.layout.LayoutSpacer; import com.smartgwt.client.widgets.layout.VLayout; import com.smartgwt.client.widgets.layout.VStack; /** * <p> * Widget that supports searching for features through their alpha numerical attributes. Requires a value for * "manualLayerSelection" at construction time. If true, a select box will be shown so the user can select what layer to * search in. The possible list of layers consists of all the vector layers that are present in the given MapModel. If * false, this widget will react to the layer select events that come from the MapMdodel. In that case searching happens * in the selected layer (if it's a vector layer). * </p> * <p> * When a search has been executed, and a result is returned from the server, a {@link SearchEvent} will be triggered. * So in order to do something with the result, add a {@link SearchHandler} to this widget. Hint: There is a * <code>DefaultSearchHandler</code> that displays the resulting set of features in a {@link FeatureListGrid} widget. * </p> * * @author Pieter De Graef */ public class FeatureSearch extends Canvas { /** * The logical operator. This operator determines whether all the criteria have to be met in the search (AND), or * just one of them (OR). * * @author Pieter De Graef */ public static enum LogicalOperator { AND, OR } private VectorLayer layer; // The vector layer to search in. private FormItem layerSelect; // A form item that shows the user what layer he's searching in. private RadioGroupItem logicalOperatorRadio; // Logical operator; match one or match all criteria? private IButton searchButton; // The actual button that executes the search. private IButton resetButton; // A button that resets the search layout. private VStack criterionStack; private VStack buttonStack; private MapModel mapModel; private List<AttributeCriterionPane> criterionPanes; private List<HLayout> buttonPanes; private List<HandlerRegistration> addHandlers; private List<HandlerRegistration> removeHandlers; /** The maximum number of allowed results. No more features will be retrieved then this number. */ private int maximumResultSize = 100; private boolean manualLayerSelection; // Constructors: /** * Create a search widget for searching in a specific map model. This widget will automatically react to the * selection of layers within that map model, and redraw to compensate for the selected layer. In other words, * searching always happens on the selected layer. * * @param mapModel * The MapModel containing the possible layer to search in. * @param manualLayerSelection * If true, a select box will be shown so the user can select what layer to search in. The possible list * of layers consists of all the vector layers that are present in the given MapModel. If false, this * widget will react to the layer select events that come from the MapMdodel. In that case searching * happens in the selected layer (if it's a vector layer).<br/> * This value cannot be altered anymore. */ public FeatureSearch(MapModel mapModel, boolean manualLayerSelection) { super(); this.mapModel = mapModel; this.manualLayerSelection = manualLayerSelection; criterionPanes = new ArrayList<AttributeCriterionPane>(); buttonPanes = new ArrayList<HLayout>(); addHandlers = new ArrayList<HandlerRegistration>(); removeHandlers = new ArrayList<HandlerRegistration>(); buildUI(); setLogicalOperator(LogicalOperator.AND); } // Public methods: /** * <p> * Add a handler for the {@link SearchEvent}. A search event, is the event that is triggered when the result of a * search request successfully returns from the server. The list of features from that result will be present in * that search event object. * </p> * <p> * Hint: There is a <code>DefaultSearchHandler</code> that displays the resulting set of features in a * {@link FeatureListGrid} widget. * </p> */ public HandlerRegistration addSearchHandler(SearchHandler handler) { return doAddHandler(handler, SearchEvent.TYPE); } /** * Add a new empty row in the search grid, at the given position. An single row can be used to create a single * criterion. * * @param index * Row number in the search grid, that indicates where to add/insert a new empty row. */ public void addEmptyRow(final int index) { if (layer == null || !(layer instanceof VectorLayer)) { return; } searchButton.setDisabled(false); if (index > 0) { resetButton.setDisabled(false); } // Empty row: AttributeCriterionPane newRow = new AttributeCriterionPane(layer); newRow.setHeight(32); newRow.setStyleName("searchRow"); HLayout btnLayout = new HLayout(); btnLayout.setHeight(32); btnLayout.setMembersMargin(5); btnLayout.setAlign(Alignment.CENTER); btnLayout.setPadding(4); btnLayout.setStyleName("searchRow"); IButton btnAddRow = new IButton(); btnAddRow.setWidth(26); btnAddRow.setIcon("[ISOMORPHIC]/geomajas/silk/add.png"); HandlerRegistration addReg = btnAddRow.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { IButton btnAddRow2 = (IButton) event.getSource(); for (int i = 0; i < buttonPanes.size(); i++) { IButton button = (IButton) buttonPanes.get(i).getMember(0); if (btnAddRow2.equals(button)) { addEmptyRow(i + 1); break; } } buttonPanes.get(0).getMember(1).setDisabled(false); } }); IButton btnRemoveRow = new IButton(); btnRemoveRow.setWidth(26); btnRemoveRow.setIcon("[ISOMORPHIC]/geomajas/silk/remove.png"); HandlerRegistration removeReg = btnRemoveRow.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { IButton sourceBtn = (IButton) event.getSource(); for (int i = 0; i < buttonPanes.size(); i++) { IButton button = (IButton) buttonPanes.get(i).getMember(1); if (sourceBtn.equals(button)) { criterionStack.removeMember(criterionPanes.remove(i)); // Remove row 0 from add button/registration: buttonStack.removeMember(buttonPanes.remove(i)); addHandlers.remove(i).removeHandler(); removeHandlers.remove(i).removeHandler(); break; } } if (buttonPanes.size() == 1) { buttonPanes.get(0).getMember(1).setDisabled(true); resetButton.setDisabled(true); } } }); if (index == 0) { btnRemoveRow.setDisabled(true); } btnLayout.addMember(btnAddRow); btnLayout.addMember(btnRemoveRow); // Add to the stacks: criterionStack.addMember(newRow, index + 1); buttonStack.addMember(btnLayout, index + 1); // Add to the lists: criterionPanes.add(index, newRow); buttonPanes.add(index, btnLayout); addHandlers.add(index, addReg); removeHandlers.add(index, removeReg); } /** * Get the full list of search criteria from the criterion grid. * * @return */ public List<SearchCriterion> getSearchCriteria() { List<SearchCriterion> criteria = new ArrayList<SearchCriterion>(); for (AttributeCriterionPane criterionPane : criterionPanes) { if (criterionPane.hasErrors()) { SC.warn(I18nProvider.getSearch().warningInvalidCriteria()); return null; } SearchCriterion criterion = criterionPane.getSearchCriterion(); if (criterion != null) { criteria.add(criterion); } } if (criteria == null || criteria.size() == 0) { SC.warn(I18nProvider.getSearch().warningNoCriteria()); } return criteria; } /** * Empty the grid, thereby removing all rows. When that is done, a new empty row will be displayed. */ public void empty() { searchButton.setDisabled(true); resetButton.setDisabled(true); for (AttributeCriterionPane criterionPane : criterionPanes) { criterionStack.removeMember(criterionPane); } criterionPanes.clear(); for (HLayout criterionPane : buttonPanes) { buttonStack.removeMember(criterionPane); } buttonPanes.clear(); for (HandlerRegistration handlerRegistration : addHandlers) { handlerRegistration.removeHandler(); } addHandlers.clear(); for (HandlerRegistration handlerRegistration : removeHandlers) { handlerRegistration.removeHandler(); } removeHandlers.clear(); addEmptyRow(0); } /** * Execute the actual search. All features that are returned in the result will be added to the layer's feature * store. Then a {@link SearchEvent} is fired. */ public void search() { if (layer != null) { // First we try to get the list of criteria: List<SearchCriterion> criteria = getSearchCriteria(); if (criteria != null && !criteria.isEmpty()) { SearchFeatureRequest request = new SearchFeatureRequest(); String value = (String) logicalOperatorRadio.getValue(); if (value.equals(I18nProvider.getSearch().radioOperatorAnd())) { request.setBooleanOperator("AND"); } else { request.setBooleanOperator("OR"); } request.setCriteria(criteria.toArray(new SearchCriterion[0])); request.setCrs(mapModel.getCrs()); request.setLayerId(layer.getServerLayerId()); request.setMax(maximumResultSize); request.setFilter(layer.getFilter()); request.setFeatureIncludes(GwtCommandDispatcher.getInstance().getLazyFeatureIncludesSelect()); GwtCommand command = new GwtCommand("command.feature.Search"); command.setCommandRequest(request); GwtCommandDispatcher.getInstance().execute(command, new CommandCallback() { public void execute(CommandResponse response) { if (response instanceof SearchFeatureResponse) { SearchFeatureResponse resp = (SearchFeatureResponse) response; List<Feature> features = new ArrayList<Feature>(); for (org.geomajas.layer.feature.Feature dtoFeature : resp.getFeatures()) { Feature feature = new Feature(dtoFeature, layer); layer.getFeatureStore().addFeature(feature); features.add(feature); } SearchEvent event = new SearchEvent(layer, features); FeatureSearch.this.fireEvent(event); } } }); } } } // Getters and setters: /** * Set a new value for the logical operator. This operator determines whether all the criteria have to be met in the * search, or just one of them. */ public void setLogicalOperator(LogicalOperator operator) { switch (operator) { case AND: logicalOperatorRadio.setValue(I18nProvider.getSearch().radioOperatorAnd()); break; case OR: logicalOperatorRadio.setValue(I18nProvider.getSearch().radioOperatorOr()); } } /** * Return the current value for the logical operator.This operator determines whether all the criteria have to be * met in the search, or just one of them. * * @return */ public LogicalOperator getLogicalOperator() { String value = (String) logicalOperatorRadio.getValue(); if (value.equals(I18nProvider.getSearch().radioOperatorAnd())) { return LogicalOperator.AND; } return LogicalOperator.OR; } /** * Return the layer onto which searching should happen. (the MapModel's selected layer) * * @return */ public VectorLayer getLayer() { return layer; } /** * Set a new layer onto which searching should happen. * * @param layer */ public void setLayer(VectorLayer layer) { this.layer = layer; empty(); } /** * Get the maximum number of allowed results. No more features will be retrieved then this number. */ public int getMaximumResultSize() { return maximumResultSize; } /** * Set a new maximum number of allowed results. No more features will be retrieved then this number. * * @param maximumResultSize * The new value. */ public void setMaximumResultSize(int maximumResultSize) { this.maximumResultSize = maximumResultSize; } // Private methods: private void buildUI() { // Create the layout: VLayout layout = new VLayout(); layout.setWidth100(); layout.setHeight100(); logicalOperatorRadio = new RadioGroupItem("logicalOperator"); logicalOperatorRadio.setValueMap(I18nProvider.getSearch().radioOperatorOr(), I18nProvider.getSearch() .radioOperatorAnd()); logicalOperatorRadio.setVertical(false); logicalOperatorRadio.setRequired(true); logicalOperatorRadio.setAlign(Alignment.LEFT); logicalOperatorRadio.setWidth(250); logicalOperatorRadio.setShowTitle(false); HLayout optionLayout = new HLayout(); optionLayout.setHeight(50); optionLayout.setWidth100(); VLayout leftLayout = new VLayout(); leftLayout.setAlign(Alignment.LEFT); HLayout layerLayout = new HLayout(); layerLayout.setWidth(420); DynamicForm layerForm = new DynamicForm(); layerForm.setHeight(30); if (manualLayerSelection) { layerSelect = new SelectItem(); layerSelect.setTitle(I18nProvider.getSearch().labelLayerSelected()); layerSelect.setWidth(250); layerSelect.setHint(I18nProvider.getSearch().labelNoLayerSelected()); ((SelectItem) layerSelect).setShowHintInField(true); layerSelect.addChangedHandler(new ChangedHandler() { public void onChanged(ChangedEvent event) { String layerLabel = (String) event.getValue(); for (Layer<?> vLayer : mapModel.getLayers()) { if (vLayer.getLabel().equals(layerLabel)) { setLayer((VectorLayer) vLayer); } } } }); mapModel.addMapModelHandler(new MapModelHandler() { public void onMapModelChange(MapModelEvent event) { List<String> layers = new ArrayList<String>(); for (Layer<?> vLayer : mapModel.getLayers()) { if (vLayer instanceof VectorLayer) { layers.add(vLayer.getLabel()); } } layerSelect.setValueMap(layers.toArray(new String[0])); } }); } else { mapModel.addLayerSelectionHandler(new LayerSelectionHandler() { public void onDeselectLayer(LayerDeselectedEvent event) { empty(); updateLabelTitle(I18nProvider.getSearch().labelNoLayerSelected()); } public void onSelectLayer(LayerSelectedEvent event) { if (event.getLayer() instanceof VectorLayer) { setLayer((VectorLayer) event.getLayer()); if (event.getLayer() != null) { updateLabelTitle(event.getLayer().getLabel()); } } } }); layerSelect = new BlurbItem(); layerSelect.setShowTitle(true); layerSelect.setTitle(I18nProvider.getSearch().labelLayerSelected()); layerSelect.setWidth(250); layerSelect.setValue("<b>" + I18nProvider.getSearch().labelNoLayerSelected() + "</b>"); } layerForm.setFields(layerSelect); layerLayout.addMember(layerForm); leftLayout.addMember(layerLayout); DynamicForm logicalForm = new DynamicForm(); logicalForm.setAutoWidth(); logicalForm.setLayoutAlign(Alignment.CENTER); logicalForm.setFields(logicalOperatorRadio); leftLayout.setWidth(420); leftLayout.addMember(logicalForm); VLayout rightLayout = new VLayout(); rightLayout.setLayoutAlign(VerticalAlignment.TOP); rightLayout.setMargin(5); rightLayout.setMembersMargin(5); rightLayout.setWidth(100); searchButton = new IButton(I18nProvider.getSearch().btnSearch()); searchButton.setIcon("[ISOMORPHIC]/geomajas/silk/find.png"); searchButton.setWidth(100); searchButton.setDisabled(true); searchButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { search(); } }); resetButton = new IButton(I18nProvider.getSearch().btnReset()); resetButton.setIcon("[ISOMORPHIC]/geomajas/silk/undo.png"); resetButton.setWidth(100); resetButton.setDisabled(true); resetButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { empty(); } }); rightLayout.addMember(searchButton); rightLayout.addMember(resetButton); optionLayout.addMember(leftLayout); optionLayout.addMember(new LayoutSpacer()); optionLayout.addMember(rightLayout); // Create a header for the criterionStack: HLayout headerLayout = new HLayout(); headerLayout.setHeight(26); headerLayout.setStyleName("headerBar"); HTMLPane attrHeader = new HTMLPane(); attrHeader.setStyleName("searchHeader"); attrHeader.setContents("Attribute"); attrHeader.setWidth(140); HTMLPane operatorHeader = new HTMLPane(); operatorHeader.setContents("Operator"); operatorHeader.setWidth(140); operatorHeader.setStyleName("searchHeader"); HTMLPane valueHeader = new HTMLPane(); valueHeader.setContents("Value"); valueHeader.setStyleName("searchHeader"); criterionStack = new VStack(); criterionStack.setAlign(VerticalAlignment.TOP); headerLayout.addMember(attrHeader); headerLayout.addMember(operatorHeader); headerLayout.addMember(valueHeader); criterionStack.addMember(headerLayout); buttonStack = new VStack(); buttonStack.setWidth(70); buttonStack.setAlign(VerticalAlignment.TOP); HTMLPane btnHeader = new HTMLPane(); btnHeader.setStyleName("headerBar"); btnHeader.setWidth(70); btnHeader.setHeight(26); buttonStack.addMember(btnHeader); HLayout searchGrid = new HLayout(); searchGrid.addMember(criterionStack); searchGrid.addMember(buttonStack); searchGrid.setBorder("1px solid lightgrey"); layout.addMember(optionLayout); layout.addMember(searchGrid); addChild(layout); } private void updateLabelTitle(String title) { layerSelect.setValue("<b>" + title + "</b>"); } }
import javax.swing.JPanel; import java.awt.Color; import java.awt.event.MouseMotionAdapter; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.Point; import javax.swing.JLabel; import javax.swing.BorderFactory; import javax.swing.border.BevelBorder; import java.util.ArrayList; import javax.swing.JTextField; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.Dimension; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.DefaultMutableTreeNode; public class Device{ private int X,Y; String name= ""; String description=""; String id=""; String vendor=""; String type=""; String family=""; String model=""; ArrayList <String[]> properties = new ArrayList <String[]>(); ArrayList <DeviceModule> modules = new ArrayList <DeviceModule>(); Device reference; public Device(){reference = this;} public void updateInfo(){ Repository.window.mainpanel.p4.dut.additem.setEnabled(true); Repository.window.mainpanel.p4.dut.additem.setText("Add module"); Repository.window.mainpanel.p4.dut.remitem.setEnabled(true); Repository.window.mainpanel.p4.dut.remitem.setText("Remove device"); Repository.window.mainpanel.p4.dut.temp = reference; Repository.window.mainpanel.p4.dut.tname.setText(name.toString()); Repository.window.mainpanel.p4.dut.ttype.setText(type.toString()); Repository.window.mainpanel.p4.dut.tvendor.setText(vendor.toString()); Repository.window.mainpanel.p4.dut.tmodel.setText(model.toString()); Repository.window.mainpanel.p4.dut.tfamily.setText(family.toString()); Repository.window.mainpanel.p4.dut.tid.setText(id.toString()); Repository.window.mainpanel.p4.dut.tdescription.setText(description.toString()); Repository.window.mainpanel.p4.dut.propname.setText(""); Repository.window.mainpanel.p4.dut.propvalue.setText(""); updatePropertys();} public void updatePropertys(){ Repository.window.mainpanel.p4.dut.properties.removeAll(); if(Repository.window.mainpanel.p4.dut.nodetemp1.getChildAt(Repository.window.mainpanel.p4.dut.nodetemp1.getChildCount()-1).isLeaf()){ while(Repository.window.mainpanel.p4.dut.nodetemp1.getChildCount()>6){ ((DefaultTreeModel)Repository.window.mainpanel.p4.dut.explorer.tree.getModel()).removeNodeFromParent(((DefaultMutableTreeNode)Repository.window.mainpanel.p4.dut.nodetemp1.getChildAt(6)));}} else{ while(Repository.window.mainpanel.p4.dut.nodetemp1.getChildAt(6).isLeaf()){ ((DefaultTreeModel)Repository.window.mainpanel.p4.dut.explorer.tree.getModel()).removeNodeFromParent(((DefaultMutableTreeNode)Repository.window.mainpanel.p4.dut.nodetemp1.getChildAt(6)));}} for(int i =0;i<properties.size();i++){ DefaultMutableTreeNode child2 = new DefaultMutableTreeNode(properties.get(i)[0]+" - "+properties.get(i)[1],false); if(Repository.window.mainpanel.p4.dut.nodetemp1.getChildAt(Repository.window.mainpanel.p4.dut.nodetemp1.getChildCount()-1).isLeaf()){ ((DefaultTreeModel)Repository.window.mainpanel.p4.dut.explorer.tree.getModel()).insertNodeInto(child2,Repository.window.mainpanel.p4.dut.nodetemp1,Repository.window.mainpanel.p4.dut.nodetemp1.getChildCount());} else{ ((DefaultTreeModel)Repository.window.mainpanel.p4.dut.explorer.tree.getModel()).insertNodeInto(child2,Repository.window.mainpanel.p4.dut.nodetemp1,6+i);} final JButton b = new JButton("remove"); b.setBounds(280,i*23+18,78,19); b.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ev){ properties.remove(Repository.window.mainpanel.p4.dut.properties.getComponentZOrder(b)/3); updatePropertys();}}); Repository.window.mainpanel.p4.dut.properties.add(b); final JTextField text1 = new JTextField(); text1.setText(properties.get(i)[0]); text1.setBounds(6,i*23+18,135,25); text1.addKeyListener(new KeyAdapter(){ public void keyReleased(KeyEvent ev){ properties.get(Repository.window.mainpanel.p4.dut.properties.getComponentZOrder(text1)/3)[0]=text1.getText(); ((DefaultMutableTreeNode)Repository.window.mainpanel.p4.dut.nodetemp1.getChildAt(6+(Repository.window.mainpanel.p4.dut.properties.getComponentZOrder(text1)/3))).setUserObject(text1.getText()+" - "+properties.get(Repository.window.mainpanel.p4.dut.properties.getComponentZOrder(text1)/3)[1]); ((DefaultTreeModel)Repository.window.mainpanel.p4.dut.explorer.tree.getModel()).nodeChanged(Repository.window.mainpanel.p4.dut.nodetemp1.getChildAt(6+(Repository.window.mainpanel.p4.dut.properties.getComponentZOrder(text1)/3)));}}); final JTextField text2 = new JTextField(); text2.setText(properties.get(i)[1]); text2.setBounds(143,i*23+18,135,25); text2.addKeyListener(new KeyAdapter(){ public void keyReleased(KeyEvent ev){ properties.get(Repository.window.mainpanel.p4.dut.properties.getComponentZOrder(text1)/3)[1]=text2.getText(); ((DefaultMutableTreeNode)Repository.window.mainpanel.p4.dut.nodetemp1.getChildAt(6+(Repository.window.mainpanel.p4.dut.properties.getComponentZOrder(text1)/3))).setUserObject(properties.get(Repository.window.mainpanel.p4.dut.properties.getComponentZOrder(text1)/3)[0]+" - "+text2.getText()); ((DefaultTreeModel)Repository.window.mainpanel.p4.dut.explorer.tree.getModel()).nodeChanged(Repository.window.mainpanel.p4.dut.nodetemp1.getChildAt(6+(Repository.window.mainpanel.p4.dut.properties.getComponentZOrder(text1)/3)));}}); Repository.window.mainpanel.p4.dut.properties.add(text2); Repository.window.mainpanel.p4.dut.properties.add(text1);} Repository.window.mainpanel.p4.dut.properties.setPreferredSize(new Dimension(Repository.window.mainpanel.p4.dut.properties.getWidth(),properties.size()*23+18)); Repository.window.mainpanel.p4.dut.properties.revalidate(); Repository.window.mainpanel.p4.dut.properties.repaint();} public void setDescription(String description){ this.description = description;} public void setID(String id){ this.id=id;} public void setVendor(String vendor){ this.vendor = vendor;} public void setType(String type){ this.type=type;} public String toString(){ return "Device: "+name.toString();} public void addModule(DeviceModule module){ modules.add(module);} public void setFamily(String family){ this.family=family;} public void setModel(String model){ this.model=model;} public void setName(String name){ this.name=name;}}
package com.blarg.gdx.entities; import com.badlogic.gdx.utils.*; import com.blarg.gdx.entities.systemcomponents.InactiveComponent; import com.blarg.gdx.events.EventManager; import com.blarg.gdx.ReflectionUtils; import com.blarg.gdx.graphics.RenderContext; public class EntityManager implements Disposable { public final EventManager eventManager; ObjectSet<Entity> entities; ObjectMap<Class<? extends Component>, ObjectMap<Entity, Component>> componentStore; ObjectMap<Class<? extends Component>, Component> globalComponents; Array<ComponentSystem> componentSystems; Pool<Entity> entityPool = new Pool<Entity>() { @Override protected Entity newObject() { return new Entity(EntityManager.this); } }; ObjectMap<Entity, Component> empty; public EntityManager(EventManager eventManager) { if (eventManager == null) throw new IllegalArgumentException("eventManager can not be null."); this.eventManager = eventManager; entities = new ObjectSet<Entity>(); componentStore = new ObjectMap<Class<? extends Component>, ObjectMap<Entity, Component>>(); globalComponents = new ObjectMap<Class<? extends Component>, Component>(); componentSystems = new Array<ComponentSystem>(); // possibly ugliness, but this allows us to return empty.keys() in getAllWith() // when there are no entities with a given component, preventing the calling code // from needing to check for null before a for-loop empty = new ObjectMap<Entity, Component>(); } /*** public ComponentSystem management */ public <T extends ComponentSystem> T addSubsystem(Class<T> componentSystemType) { if (getSubsystem(componentSystemType) != null) throw new UnsupportedOperationException("ComponentSystem of that type is already registered."); T subsystem; try { subsystem = ReflectionUtils.instantiateObject(componentSystemType, new Class<?>[] { EntityManager.class, EventManager.class }, new Object[] { this, eventManager }); } catch (Exception e) { throw new IllegalArgumentException("Could not instantiate this type of ComponentSystem.", e); } componentSystems.add(subsystem); return subsystem; } public <T extends ComponentSystem> T getSubsystem(Class<T> componentSystemType) { int i = getSubsystemIndex(componentSystemType); if (i == -1) return null; else return componentSystemType.cast(componentSystems.get(i)); } public <T extends ComponentSystem> void removeSubsystem(Class<T> componentSystemType) { int i = getSubsystemIndex(componentSystemType); if (i == -1) return; componentSystems.removeIndex(i); } public void removeAllSubsystems() { for (int i = 0; i < componentSystems.size; ++i) componentSystems.get(i).dispose(); componentSystems.clear(); } /*** public Entity management ***/ public Entity add() { Entity entity = entityPool.obtain(); entities.add(entity); return entity; } public <T extends Component> Entity getFirstWith(Class<T> componentType) { ObjectMap<Entity, Component> componentEntities = componentStore.get(componentType); if (componentEntities == null) return null; if (componentEntities.size > 0) return componentEntities.keys().next(); else return null; } public <T extends Component> ObjectMap.Keys<Entity> getAllWith(Class<T> componentType) { ObjectMap<Entity, Component> componentEntities = componentStore.get(componentType); if (componentEntities == null) return empty.keys(); // calling code won't need to check for null else return componentEntities.keys(); } public void remove(Entity entity) { if (entity == null) throw new IllegalArgumentException("entity can not be null."); removeAllComponentsFrom(entity); entities.remove(entity); entityPool.free(entity); } public void removeAll() { for (Entity i : entities) { removeAllComponentsFrom(i); entityPool.free(i); } entities.clear(); } /*** public Entity Component management ***/ public <T extends Component> T addComponent(Class<T> componentType, Entity entity) { if (getComponent(componentType, entity) != null) throw new UnsupportedOperationException("Component of that type has been added to this entity already."); // find the component-to-entity list for this component type, or create it if it doesn't exist yet ObjectMap<Entity, Component> componentEntities = componentStore.get(componentType); if (componentEntities == null) { componentEntities = new ObjectMap<Entity, Component>(); componentStore.put(componentType, componentEntities); } T component = Pools.obtain(componentType); componentEntities.put(entity, component); return componentType.cast(component); } public <T extends Component> T getComponent(Class<T> componentType, Entity entity) { ObjectMap<Entity, Component> componentEntities = componentStore.get(componentType); if (componentEntities == null) return null; Component existing = componentEntities.get(entity); if (existing == null) return null; else return componentType.cast(existing); } public <T extends Component> void removeComponent(Class<T> componentType, Entity entity) { ObjectMap<Entity, Component> componentEntities = componentStore.get(componentType); if (componentEntities == null) return; Component component = componentEntities.remove(entity); Pools.free(component); } public <T extends Component> boolean hasComponent(Class<T> componentType, Entity entity) { ObjectMap<Entity, Component> componentEntities = componentStore.get(componentType); if (componentEntities == null) return false; return componentEntities.containsKey(entity); } public void getAllComponentsFor(Entity entity, Array<Component> list) { if (list == null) throw new IllegalArgumentException("list can not be null."); for (ObjectMap.Entry<Class<? extends Component>, ObjectMap<Entity, Component>> i : componentStore.entries()) { ObjectMap<Entity, Component> entitiesWithComponent = i.value; Component component = entitiesWithComponent.get(entity); if (component != null) list.add(component); } } /*** global component management ***/ public <T extends Component> T addGlobal(Class<T> componentType) { if (getGlobal(componentType) != null) throw new UnsupportedOperationException("Global component of that type has been added already."); T component = Pools.obtain(componentType); globalComponents.put(componentType, component); return componentType.cast(component); } public <T extends Component> T getGlobal(Class<T> componentType) { Component existing = globalComponents.get(componentType); if (existing == null) return null; else return componentType.cast(existing); } public <T extends Component> void removeGlobal(Class<T> componentType) { Component component = globalComponents.remove(componentType); Pools.free(component); } public <T extends Component> boolean hasGlobal(Class<T> componentType) { return globalComponents.containsKey(componentType); } public void removeAllGlobals() { for (ObjectMap.Entry<Class<? extends Component>, Component> i : globalComponents.entries()) Pools.free(i.value); globalComponents.clear(); } /*** events ***/ public void onAppResume() { for (int i = 0; i < componentSystems.size; ++i) componentSystems.get(i).onAppResume(); } public void onAppPause() { for (int i = 0; i < componentSystems.size; ++i) componentSystems.get(i).onAppPause(); } public void onResize() { for (int i = 0; i < componentSystems.size; ++i) componentSystems.get(i).onResize(); } public void onRender(float delta, RenderContext renderContext) { for (int i = 0; i < componentSystems.size; ++i) componentSystems.get(i).onRender(delta, renderContext); } public void onUpdate(float delta) { for (Entity i : getAllWith(InactiveComponent.class)) remove(i); for (int i = 0; i < componentSystems.size; ++i) componentSystems.get(i).onUpdate(delta); } /*** private Entity/Component management ***/ private void removeAllComponentsFrom(Entity entity) { if (entity == null) throw new IllegalArgumentException("entity can not be null."); for (ObjectMap.Entry<Class<? extends Component>, ObjectMap<Entity, Component>> i : componentStore.entries()) { ObjectMap<Entity, Component> entitiesWithComponent = i.value; Component component = entitiesWithComponent.get(entity); if (component != null) Pools.free(component); entitiesWithComponent.remove(entity); } } private <T extends ComponentSystem> int getSubsystemIndex(Class<T> componentSystemType) { for (int i = 0; i < componentSystems.size; ++i) { if (componentSystems.get(i).getClass() == componentSystemType) return i; } return -1; } @Override public void dispose() { removeAll(); removeAllGlobals(); removeAllSubsystems(); } }
package org.ovirt.engine.ui.uicommonweb; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashSet; import java.util.List; import org.ovirt.engine.core.common.VdcObjectType; import org.ovirt.engine.core.common.action.VdcReturnValueBase; import org.ovirt.engine.core.common.businessentities.AuditLog; import org.ovirt.engine.core.common.businessentities.DbUser; import org.ovirt.engine.core.common.businessentities.Disk; import org.ovirt.engine.core.common.businessentities.Disk.DiskStorageType; import org.ovirt.engine.core.common.businessentities.DiskImage; import org.ovirt.engine.core.common.businessentities.Provider; import org.ovirt.engine.core.common.businessentities.ProviderType; import org.ovirt.engine.core.common.businessentities.Role; import org.ovirt.engine.core.common.businessentities.ServerCpu; import org.ovirt.engine.core.common.businessentities.Snapshot; import org.ovirt.engine.core.common.businessentities.StorageDomain; import org.ovirt.engine.core.common.businessentities.StorageDomainSharedStatus; import org.ovirt.engine.core.common.businessentities.StorageDomainStatus; import org.ovirt.engine.core.common.businessentities.StorageDomainType; import org.ovirt.engine.core.common.businessentities.StoragePool; import org.ovirt.engine.core.common.businessentities.StoragePoolStatus; import org.ovirt.engine.core.common.businessentities.VDS; import org.ovirt.engine.core.common.businessentities.VDSGroup; import org.ovirt.engine.core.common.businessentities.VDSStatus; import org.ovirt.engine.core.common.businessentities.VM; import org.ovirt.engine.core.common.businessentities.VmTemplate; import org.ovirt.engine.core.common.businessentities.VolumeType; import org.ovirt.engine.core.common.businessentities.comparators.LexoNumericComparator; import org.ovirt.engine.core.common.businessentities.comparators.NameableComparator; import org.ovirt.engine.core.common.businessentities.network.Network; import org.ovirt.engine.core.common.businessentities.network.NetworkInterface; import org.ovirt.engine.core.common.businessentities.network.VdsNetworkInterface; import org.ovirt.engine.core.common.businessentities.network.VnicProfileView; import org.ovirt.engine.core.common.scheduling.ClusterPolicy; import org.ovirt.engine.core.common.scheduling.PolicyUnit; import org.ovirt.engine.core.common.scheduling.PolicyUnitType; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.compat.StringHelper; import org.ovirt.engine.core.compat.Version; import org.ovirt.engine.ui.uicommonweb.dataprovider.AsyncDataProvider; import org.ovirt.engine.ui.uicommonweb.models.EntityModel; import org.ovirt.engine.ui.uicommonweb.models.ListModel; import org.ovirt.engine.ui.uicommonweb.models.clusters.ClusterNetworkModel; import org.ovirt.engine.ui.uicommonweb.models.hosts.HostInterfaceListModel; import org.ovirt.engine.ui.uicommonweb.models.providers.ExternalNetwork; import org.ovirt.engine.ui.uicommonweb.models.storage.LunModel; import org.ovirt.engine.ui.uicommonweb.models.storage.SanTargetModel; import org.ovirt.engine.ui.uicommonweb.models.storage.StorageDomainModel; import org.ovirt.engine.ui.uicommonweb.models.vms.DataCenterWithCluster; import org.ovirt.engine.ui.uicommonweb.models.vms.DiskModel; import org.ovirt.engine.ui.uicommonweb.models.vms.TimeZoneModel; import org.ovirt.engine.ui.uicompat.DateTimeUtils; import org.ovirt.engine.ui.uicompat.EnumTranslator; import org.ovirt.engine.ui.uicompat.IEqualityComparer; @SuppressWarnings("unused") public final class Linq { public static class AuditLogComparer implements Comparator<AuditLog>, Serializable { private static final long serialVersionUID = 7488030875073130111L; @Override public int compare(AuditLog x, AuditLog y) { long xid = x.getaudit_log_id(); long yid = y.getaudit_log_id(); return Long.valueOf(xid).compareTo(yid); } } public static class VdsSPMPriorityComparer implements Comparator<VDS>, Serializable { private static final long serialVersionUID = 1114793850392069219L; @Override public int compare(VDS vds1, VDS vds2) { return (vds1.getVdsSpmPriority() < vds2.getVdsSpmPriority()) ? 1 : ((vds1.getVdsSpmPriority() == vds2.getVdsSpmPriority()) ? 0 : -1); } } public static class DiskImageByLastModifiedComparer implements Comparator<DiskImage>, Serializable { private static final long serialVersionUID = -6085272225112945238L; @Override public int compare(DiskImage x, DiskImage y) { if (x.getLastModified().before(y.getLastModified())) { return -1; } if (x.getLastModified().after(y.getLastModified())) { return 1; } return 0; } } public static class DiskImageByLastModifiedTimeOfDayComparer implements Comparator<DiskImage>, Serializable { private static final long serialVersionUID = 7206189809641328921L; @Override public int compare(DiskImage x, DiskImage y) { return DateTimeUtils.getTimeOfDay(x.getLastModified()) .compareTo(DateTimeUtils.getTimeOfDay(y.getLastModified())); } } public static class StorageDomainModelByNameComparer implements Comparator<StorageDomainModel>, Serializable { private static final long serialVersionUID = 5142897643241941178L; @Override public int compare(StorageDomainModel x, StorageDomainModel y) { return x.getStorageDomain().getStorageName().compareTo(y.getStorageDomain().getStorageName()); } } public static class DiskByAliasComparer implements Comparator<Disk>, Serializable { private static final long serialVersionUID = 7683690514569802083L; @Override public int compare(Disk x, Disk y) { String xAlias = x.getDiskAlias(); String yAlias = y.getDiskAlias(); if (xAlias == null) { return 1; } if (yAlias == null) { return -1; } return xAlias.compareTo(yAlias); } } public static class DiskModelByAliasComparer implements Comparator<DiskModel>, Serializable { private static final long serialVersionUID = -3838651062327707058L; @Override public int compare(DiskModel x, DiskModel y) { String xAlias = x.getDisk() != null ? x.getDisk().getDiskAlias() : ""; String yAlias = y.getDisk() != null ? y.getDisk().getDiskAlias() : ""; if (xAlias == null) { return 1; } if (yAlias == null) { return -1; } return xAlias.compareTo(yAlias); } } public static class SanTargetModelComparer implements Comparator<SanTargetModel>, Serializable { private static final long serialVersionUID = -5674954613952206979L; @Override public int compare(SanTargetModel x, SanTargetModel y) { return x.getName().compareTo(y.getName()); } } public static class DiskImageByCreationDateComparer implements Comparator<DiskImage>, Serializable { private static final long serialVersionUID = -5909501177227219287L; @Override public int compare(DiskImage x, DiskImage y) { if (x.getCreationDate().before(y.getCreationDate())) { return -1; } if (x.getCreationDate().after(y.getCreationDate())) { return 1; } return 0; } } public static class SnapshotByCreationDateCommparer implements Comparator<Snapshot>, Serializable { private static final long serialVersionUID = -4063737182979806402L; @Override public int compare(Snapshot x, Snapshot y) { return x.getCreationDate().compareTo(y.getCreationDate()); } } public static boolean isHostBelongsToAnyOfClusters(ArrayList<VDSGroup> clusters, VDS host) { for (VDSGroup cluster : clusters) { if (cluster.getId().equals(host.getVdsGroupId())) { return true; } } return false; } /** * Checks if Any StorageDomain Is Matser And Active * * @param sdl * @return */ public static boolean isAnyStorageDomainIsMatserAndActive(List<StorageDomain> sdl) { for (StorageDomain a : sdl) { if (a.getStorageDomainType() == StorageDomainType.Master && a.getStatus() != null && a.getStatus() == StorageDomainStatus.Active) { return true; } } return false; } public static boolean isDataActiveStorageDomain(StorageDomain storageDomain) { boolean isData = storageDomain.getStorageDomainType() == StorageDomainType.Data || storageDomain.getStorageDomainType() == StorageDomainType.Master; boolean isActive = isActiveStorageDomain(storageDomain); return isData && isActive; } public static boolean isActiveStorageDomain(StorageDomain storageDomain) { boolean isActive = storageDomain.getStatus() != null && storageDomain.getStatus() == StorageDomainStatus.Active; return isActive; } /** * Finds min Version by clusters list. * * @param source * IList to look in * @return Version MinVersion */ public static Version getMinVersionByClusters(List<VDSGroup> source) { Version minVersion = source != null && source.size() > 0 ? source.get(0).getcompatibility_version() : null; if (minVersion != null) { for (VDSGroup cluster : source) { minVersion = cluster.getcompatibility_version().compareTo(minVersion) < 0 ? (Version) cluster.getcompatibility_version() : minVersion; } } return minVersion; } /** * Check if storage_domains item with specified Guid exist in List * * @param items * @param id * @return */ public static boolean isSDItemExistInList(ArrayList<StorageDomain> items, Guid id) { for (StorageDomain b : items) { if (b.getId().equals(id)) { return true; } } return false; } /** * Check if VDSGroup item with specified id exist in List * * @param items * @param id * @return */ public static boolean isClusterItemExistInList(List<VDSGroup> items, Guid id) { for (VDSGroup a : items) { if (id.equals(a.getId())) { return true; } } return false; } public static NetworkInterface findInterfaceByName(ArrayList<VdsNetworkInterface> items, String name) { for (NetworkInterface i : items) { if (StringHelper.stringsEqual(i.getName(), name)) { return i; } } return null; } public static VdsNetworkInterface findInterfaceByNetworkName(ArrayList<VdsNetworkInterface> items, String name) { for (VdsNetworkInterface i : items) { if (StringHelper.stringsEqual(i.getNetworkName(), name)) { return i; } } return null; } public static VdsNetworkInterface findInterfaceByIsBond(ArrayList<VdsNetworkInterface> items) { for (VdsNetworkInterface i : items) { if (i.getBonded() != null && i.getBonded()) { return i; } } return null; } public static VdsNetworkInterface findInterfaceNetworkNameNotEmpty(ArrayList<VdsNetworkInterface> items) { for (VdsNetworkInterface i : items) { if (!StringHelper.isNullOrEmpty(i.getNetworkName())) { return i; } } return null; } public static ArrayList<VdsNetworkInterface> findAllInterfaceNetworkNameNotEmpty(ArrayList<VdsNetworkInterface> items) { ArrayList<VdsNetworkInterface> ret = new ArrayList<VdsNetworkInterface>(); for (VdsNetworkInterface i : items) { if (!StringHelper.isNullOrEmpty(i.getNetworkName())) { ret.add(i); } } return ret; } public static ArrayList<VdsNetworkInterface> findAllInterfaceBondNameIsEmpty(ArrayList<VdsNetworkInterface> items) { ArrayList<VdsNetworkInterface> ret = new ArrayList<VdsNetworkInterface>(); for (VdsNetworkInterface i : items) { if (StringHelper.isNullOrEmpty(i.getBondName())) { ret.add(i); } } return ret; } public static ArrayList<VdsNetworkInterface> findAllInterfaceVlanIdIsEmpty(ArrayList<VdsNetworkInterface> items) { ArrayList<VdsNetworkInterface> ret = new ArrayList<VdsNetworkInterface>(); for (VdsNetworkInterface i : items) { if (i.getVlanId() == null) { ret.add(i); } } return ret; } public static Network findNetworkByName(ArrayList<Network> items, String name) { for (Network n : items) { if (StringHelper.stringsEqual(n.getName(), name)) { return n; } } return null; } public static ArrayList<VDS> findAllVDSByPmEnabled(ArrayList<VDS> items) { ArrayList<VDS> ret = new ArrayList<VDS>(); for (VDS i : items) { if (i.getpm_enabled()) { ret.add(i); } } return ret; } public static SanTargetModel findSanTargetByNotIsConnected(ArrayList<SanTargetModel> items) { for (SanTargetModel i : items) { if (!i.getIsLoggedIn()) { return i; } } return null; } public static ArrayList<StorageDomain> findAllStorageDomainsBySharedStatus(ArrayList<StorageDomain> items, StorageDomainSharedStatus status) { ArrayList<StorageDomain> ret = new ArrayList<StorageDomain>(); for (StorageDomain i : items) { if (i.getStorageDomainSharedStatus() == status) { ret.add(i); } } return ret; } public static VdcReturnValueBase findVdcReturnValueByDescription(ArrayList<VdcReturnValueBase> items, String description) { for (VdcReturnValueBase i : items) { if (StringHelper.stringsEqual(i.getDescription(), description)) { return i; } } return null; } /** * Produces the set difference of two sequences by using the default equality */ // comparer to compare values. /** * <typeparam name="TSource"></typeparam> * * @param first * An System.Collections.Generic.IEnumerable<T> whose elements that are not also in second will be * returned. * @param second * An System.Collections.Generic.IEnumerable<T> whose elements that also occur in the first sequence will * cause those elements to be removed from the returned sequence. * @return A sequence that contains the set difference of the elements of two sequences. */ public static <TSource> ArrayList<TSource> except(ArrayList<TSource> first, ArrayList<TSource> second) { ArrayList<TSource> newIEnumerable = new ArrayList<TSource>(); if (first != null && second != null) { for (TSource t : first) { if (!second.contains(t)) { newIEnumerable.add(t); } } } return second == null ? first : newIEnumerable; } public static int count(Iterable source) { int result = 0; for (Object item : source) { result++; } return result; } public static <TSource> TSource firstOrDefault(Iterable<TSource> source) { for (TSource item : source) { return item; } return null; } public static <TSource> boolean all(Iterable<TSource> source, IPredicate<TSource> predicate) { for (TSource item : source) { if (!predicate.match(item)) { return false; } } return true; } public static <TSource> Iterable<TSource> where(Iterable<TSource> source, IPredicate<TSource> predicate) { ArrayList<TSource> list = new ArrayList<TSource>(); for (TSource item : source) { if (predicate.match(item)) { list.add(item); } } return list; } public static <TSource> boolean containsByIdentity(Iterable<TSource> source, Object item) { for (TSource sourceItem : source) { if (sourceItem == item) { return true; } } return false; } public static Version selectHighestVersion(ArrayList<Version> versions) { Version retVersion = firstOrDefault(versions); for (Version version : versions) { if (version.compareTo(retVersion) > 0) { retVersion = version; } } return retVersion; } public static <TSource> TSource firstOrDefault(Iterable<TSource> source, IPredicate<TSource> predicate) { for (TSource item : source) { if (predicate.match(item)) { return item; } } return null; } /** * Returns a new instance of list containing all items of the provided source. */ public static <TSource> ArrayList<TSource> toList(Iterable<TSource> source) { ArrayList<TSource> list = new ArrayList<TSource>(); for (TSource item : source) { list.add(item); } return list; } public static <TSource> ArrayList<TSource> distinct(ArrayList<TSource> source, IEqualityComparer<TSource> comparer) { ArrayList<TSource> list = new ArrayList<TSource>(); for (TSource a : source) { boolean found = false; for (TSource b : list) { if (comparer.equals(a, b)) { found = true; break; } } if (!found) { list.add(a); } } return list; } public static <TResult> ArrayList<TResult> cast(Iterable source) { ArrayList<TResult> list = new ArrayList<TResult>(); for (Object a : source) { TResult item = (TResult) a; list.add(item); } return list; } public static List concat(List... lists) { List result = new ArrayList<Object>(); for (List list : lists) { for (Object item : list) { result.add(item); } } return result; } public static <T> ArrayList<T> union(ArrayList<ArrayList<T>> lists) { HashSet<T> set = new HashSet<T>(); for (ArrayList<T> list : lists) { set.addAll(list); } return new ArrayList<T>(set); } public static <T> ArrayList<T> intersection(ArrayList<ArrayList<T>> lists) { ArrayList<T> result = new ArrayList<T>(); if (lists != null && !lists.isEmpty()) { result.addAll(lists.get(0)); for (ArrayList<T> list : lists) { result.retainAll(list); } } return result; } public static StorageDomain getStorageById(Guid storageId, ArrayList<StorageDomain> storageDomains) { for (StorageDomain storage : storageDomains) { if (storage.getId().equals(storageId)) { return storage; } } return null; } public static ArrayList<StorageDomain> getStorageDomainsByIds(ArrayList<Guid> storageIds, ArrayList<StorageDomain> storageDomains) { ArrayList<StorageDomain> list = new ArrayList<StorageDomain>(); for (Guid storageId : storageIds) { StorageDomain storageDomain = getStorageById(storageId, storageDomains); if (storageDomain != null) { list.add(getStorageById(storageId, storageDomains)); } } return list; } public static <T> ArrayList<EntityModel> toEntityModelList(ArrayList<T> list) { ArrayList<EntityModel> entityModelList = new ArrayList<EntityModel>(); if (list != null) { for (Object item : list) { EntityModel model = new EntityModel(); model.setEntity(item); entityModelList.add(model); } } return entityModelList; } public static ArrayList<DiskModel> filterDisksByType(ArrayList<DiskModel> diskModels, DiskStorageType type) { ArrayList<DiskModel> filteredList = new ArrayList<DiskModel>(); if (diskModels != null) { for (DiskModel item : diskModels) { if (item.getDisk().getDiskStorageType() == type) { filteredList.add(item); } } } return filteredList; } public static DiskModel diskToModel(Disk disk) { DiskModel diskModel = new DiskModel(); diskModel.getAlias().setEntity(disk.getDiskAlias()); if (disk.getDiskStorageType() == DiskStorageType.IMAGE) { DiskImage diskImage = (DiskImage) disk; EntityModel sizeEntity = new EntityModel(); sizeEntity.setEntity(diskImage.getSizeInGigabytes()); diskModel.setSize(sizeEntity); ListModel volumeList = new ListModel(); volumeList.setItems((diskImage.getVolumeType() == VolumeType.Preallocated ? new ArrayList<VolumeType>(Arrays.asList(new VolumeType[] { VolumeType.Preallocated })) : AsyncDataProvider.getVolumeTypeList())); volumeList.setSelectedItem(diskImage.getVolumeType()); diskModel.setVolumeType(volumeList); } diskModel.setDisk(disk); return diskModel; } public static ArrayList<DiskModel> disksToDiskModelList(ArrayList<Disk> disks) { ArrayList<DiskModel> diskModels = new ArrayList<DiskModel>(); for (Disk disk : disks) { DiskModel diskModel = new DiskModel(); diskModel.setDisk(disk); diskModels.add(diskModel); } return diskModels; } public final static class TimeZonePredicate implements IPredicate<TimeZoneModel> { private final String timeZone; public TimeZonePredicate(String timeZone) { this.timeZone = timeZone; } @Override public boolean match(TimeZoneModel source) { return StringHelper.stringsEqual(source.getTimeZoneKey(), timeZone); } } public final static class ServerCpuPredicate implements IPredicate<ServerCpu> { private final String cpuName; public ServerCpuPredicate(String cpuName) { this.cpuName = cpuName; } @Override public boolean match(ServerCpu source) { return StringHelper.stringsEqual(source.getCpuName(), cpuName); } } public final static class VersionPredicate implements IPredicate<Version> { private final Version version; public VersionPredicate(Version version) { this.version = version; } @Override public boolean match(Version source) { return source.equals(version); } } public final static class DataCenterWithClusterAccordingClusterPredicate implements IPredicate<DataCenterWithCluster> { private Guid clusterId; public DataCenterWithClusterAccordingClusterPredicate(Guid clusterId) { this.clusterId = clusterId; } @Override public boolean match(DataCenterWithCluster source) { if (source.getCluster() == null) { return false; } return source.getCluster().getId().equals(clusterId); } } public final static class DataCenterWithClusterPredicate implements IPredicate<DataCenterWithCluster> { private Guid dataCenterId; private Guid clusterId; public DataCenterWithClusterPredicate(Guid dataCenterId, Guid clusterId) { this.dataCenterId = dataCenterId; this.clusterId = clusterId; } @Override public boolean match(DataCenterWithCluster source) { if (source.getDataCenter() == null || source.getCluster() == null) { return false; } return source.getDataCenter().getId().equals(dataCenterId) && source.getCluster().getId().equals(clusterId); } } public final static class DataCenterPredicate implements IPredicate<StoragePool> { private Guid id = Guid.Empty; public DataCenterPredicate(Guid id) { this.id = id; } @Override public boolean match(StoragePool source) { return id.equals(source.getId()); } } public final static class DataCenterStatusPredicate implements IPredicate<StoragePool> { private StoragePoolStatus status = StoragePoolStatus.values()[0]; public DataCenterStatusPredicate(StoragePoolStatus status) { this.status = status; } @Override public boolean match(StoragePool source) { return source.getStatus() == status; } } public final static class DataCenterNotStatusPredicate implements IPredicate<StoragePool> { private StoragePoolStatus status = StoragePoolStatus.values()[0]; public DataCenterNotStatusPredicate(StoragePoolStatus status) { this.status = status; } @Override public boolean match(StoragePool source) { return source.getStatus() != status; } } public final static class CanDoActionSucceedPredicate implements IPredicate<VdcReturnValueBase> { @Override public boolean match(VdcReturnValueBase source) { return source.getCanDoAction(); } } public final static class ClusterPredicate implements IPredicate<VDSGroup> { private Guid id = Guid.Empty; public ClusterPredicate(Guid id) { this.id = id; } @Override public boolean match(VDSGroup source) { return id.equals(source.getId()); } } public final static class HostPredicate implements IPredicate<VDS> { private Guid id = Guid.Empty; public HostPredicate(Guid id) { this.id = id; } @Override public boolean match(VDS source) { return source.getId().equals(id); } } public final static class HostStatusPredicate implements IPredicate<VDS> { private VDSStatus status = VDSStatus.values()[0]; public HostStatusPredicate(VDSStatus status) { this.status = status; } @Override public boolean match(VDS source) { return source.getStatus().equals(status); } } public final static class TemplatePredicate implements IPredicate<VmTemplate> { private Guid id = Guid.Empty; public TemplatePredicate(Guid id) { this.id = id; } @Override public boolean match(VmTemplate source) { return source.getId().equals(id); } } public final static class StoragePredicate implements IPredicate<StorageDomain> { private Guid id = Guid.Empty; public StoragePredicate(Guid id) { this.id = id; } @Override public boolean match(StorageDomain source) { return id.equals(source.getId()); } } public final static class StorageNamePredicate implements IPredicate<StorageDomain> { private String name; public StorageNamePredicate(String name) { this.name = name; } @Override public boolean match(StorageDomain source) { return name.equals(source.getStorageName()); } } public final static class LunPredicate implements IPredicate<LunModel> { private final LunModel lun; public LunPredicate(LunModel lun) { this.lun = lun; } @Override public boolean match(LunModel source) { return StringHelper.stringsEqual(source.getLunId(), lun.getLunId()); } } public final static class TargetPredicate implements IPredicate<SanTargetModel> { private final SanTargetModel target; public TargetPredicate(SanTargetModel target) { this.target = target; } @Override public boolean match(SanTargetModel source) { return StringHelper.stringsEqual(source.getName(), target.getName()) && StringHelper.stringsEqual(source.getAddress(), target.getAddress()) && StringHelper.stringsEqual(source.getPort(), target.getPort()); } } public final static class DbUserPredicate implements IPredicate<DbUser> { private final DbUser target; public DbUserPredicate(DbUser target) { this.target = target; } @Override public boolean match(DbUser source) { return StringHelper.stringsEqual(source.getDomain(), target.getDomain()) && (StringHelper.isNullOrEmpty(target.getLoginName()) || StringHelper.stringsEqual(target.getLoginName(), "*") //$NON-NLS-1$ || source.getLoginName().toLowerCase().startsWith(target.getLoginName())); } } public final static class NetworkSameProviderPredicate implements IPredicate<Provider> { private final Network network; public NetworkSameProviderPredicate(Network network) { this.network = network; } @Override public boolean match(Provider provider) { return network.isExternal() ? provider.getId().equals(network.getProvidedBy().getProviderId()) : false; } } public interface IPredicate<TSource> { boolean match(TSource source); } public final static class RoleNameComparer implements Comparator<Role>, Serializable { private static final long serialVersionUID = -8611835505533367419L; @Override public int compare(Role left, Role right) { return left.getname().compareTo(right.getname()); } } public final static class InterfaceComparator implements Comparator<VdsNetworkInterface>, Serializable { private static final long serialVersionUID = -6806871048546270786L; LexoNumericComparator lexoNumeric = new LexoNumericComparator(); @Override public int compare(VdsNetworkInterface bond1, VdsNetworkInterface bond2) { return lexoNumeric.compare(bond1.getName(), bond2.getName()); } } public final static class NetworkComparator implements Comparator<Network>, Serializable { private static final long serialVersionUID = 990203400356561587L; private LexoNumericComparator lexoNumeric = new LexoNumericComparator(); @Override public int compare(Network net1, Network net2) { // management first if (net1.getName().equals(HostInterfaceListModel.ENGINE_NETWORK_NAME)) { return -1; } else if (net2.getName().equals(HostInterfaceListModel.ENGINE_NETWORK_NAME)) { return 1; } return lexoNumeric.compare(net1.getName(), net2.getName()); } } public final static class VnicProfileViewComparator implements Comparator<VnicProfileView>, Serializable { private static final long serialVersionUID = 990203400356561587L; private LexoNumericComparator lexoNumeric = new LexoNumericComparator(); @Override public int compare(VnicProfileView vnicProfile1, VnicProfileView vnicProfile2) { if (vnicProfile1 == VnicProfileView.EMPTY) { return vnicProfile2 == VnicProfileView.EMPTY ? 0 : 1; } else if (vnicProfile2 == VnicProfileView.EMPTY) { return -1; } int retVal = lexoNumeric.compare(vnicProfile1.getNetworkName(), vnicProfile2.getNetworkName()); return retVal == 0 ? lexoNumeric.compare(vnicProfile1.getName(), vnicProfile2.getName()) : retVal; } } public final static class ClusterNetworkModelComparator implements Comparator<ClusterNetworkModel>, Serializable { private static final long serialVersionUID = -8571840939180248617L; private LexoNumericComparator lexoNumeric = new LexoNumericComparator(); @Override public int compare(ClusterNetworkModel model1, ClusterNetworkModel model2) { // management first if (model1.isManagement()) { return -1; } else if (model2.isManagement()) { return 1; } return lexoNumeric.compare(model1.getNetworkName(), model2.getNetworkName()); } } public final static class ExternalNetworkComparator implements Comparator<ExternalNetwork>, Serializable { private static final long serialVersionUID = 4987035011384708563L; private NameableComparator comparator = new NameableComparator(); @Override public int compare(ExternalNetwork net1, ExternalNetwork net2) { return comparator.compare(net1.getNetwork(), net2.getNetwork()); }; } public final static class ProviderComparator implements Comparator<Provider>, Serializable { private static final long serialVersionUID = 627759940118704128L; @Override public int compare(Provider p1, Provider p2) { return LexoNumericComparator.comp(p1.getName(), p2.getName()); } } public final static class VmComparator implements Comparator<VM>, Serializable { @Override public int compare(VM v1, VM v2) { return LexoNumericComparator.comp(v1.getName(), v2.getName()); } } public final static class VmTemplateComparator implements Comparator<VmTemplate>, Serializable { @Override public int compare(VmTemplate t1, VmTemplate t2) { return LexoNumericComparator.comp(t1.getName(), t2.getName()); } } public final static Iterable<Provider> filterProvidersByProvidedType(Iterable<Provider> source, final VdcObjectType type) { return where(source, new IPredicate<Provider>() { @Override public boolean match(Provider provider) { return provider.getType().getProvidedTypes().contains(type); } }); } public final static class ProviderTypeComparator implements Comparator<ProviderType>, Serializable { private static final long serialVersionUID = -7917198421355959306L; @Override public int compare(ProviderType type1, ProviderType type2) { return LexoNumericComparator.comp(EnumTranslator.createAndTranslate(type1), EnumTranslator.createAndTranslate(type2)); } } /** * pre-defined cluster policies should be ordered first, then order lexicographically * @param list - cluster policy list */ public final static class ClusterPolicyComparator implements Comparator<ClusterPolicy>, Serializable { final LexoNumericComparator lexoNumeric = new LexoNumericComparator(); @Override public int compare(ClusterPolicy cp1, ClusterPolicy cp2) { if (cp1.isLocked() != cp2.isLocked()) { return cp1.isLocked() ? -1 : 1; } return lexoNumeric.compare(cp1.getName(), cp2.getName()); } } /** * sort policy units by: * first is external? * second is disabled? * third policyUnitType * forth name (lexicography) */ public final static class PolicyUnitComparator implements Comparator<PolicyUnit>, Serializable { final LexoNumericComparator lexoNumeric = new LexoNumericComparator(); @Override public int compare(PolicyUnit pu1, PolicyUnit pu2) { if (pu1.isInternal() != pu2.isInternal()) { return !pu1.isInternal() ? -1 : 1; } if (pu1.isEnabled() != pu2.isEnabled()) { return !pu1.isEnabled() ? -1 : 1; } if (pu1.getPolicyUnitType() != pu2.getPolicyUnitType()) { if (pu1.getPolicyUnitType().equals(PolicyUnitType.Filter) || pu2.getPolicyUnitType().equals(PolicyUnitType.LoadBalancing)) { return -1; } if (pu2.getPolicyUnitType().equals(PolicyUnitType.Filter) || pu1.getPolicyUnitType().equals(PolicyUnitType.LoadBalancing)) { return 1; } } return lexoNumeric.compare(pu1.getName(), pu2.getName()); } } }
package com.cmgapps.android.util; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.net.Uri; import android.text.format.DateUtils; import android.util.Log; public class CMGAppRater { private static final String TAG = "CMGAppRater"; private static final String APP_RATE_FILE_NAME = "CMGAppRater"; private static final int LAUNCHES_UNTIL_PROMPT = 10; private static final long DAYS_UNTIL_PROMPT = 7 * DateUtils.DAY_IN_MILLIS; private static final long DAYS_UNTIL_REMIND_AGAIN = 2 * DateUtils.DAY_IN_MILLIS; private static final String FIRST_USE = "first_use"; private static final String USE_COUNT = "use_count"; private static final String DECLINED_RATE = "declined_rate"; private static final String TRACKING_VERSION = "tracking_version"; private static final String REMIND_LATER_DATE = "remind_later_date"; private static final String APP_RATED = "rated"; private static final boolean RATER_DEBUG = false; private final SharedPreferences mPref; private final Context mContext; public CMGAppRater(Context context) { mContext = context; mPref = context.getSharedPreferences(APP_RATE_FILE_NAME, Context.MODE_PRIVATE); } public synchronized boolean checkForRating() { if (RATER_DEBUG) return true; if (mPref.getBoolean(DECLINED_RATE, false)) return false; if (mPref.getBoolean(APP_RATED, false)) return false; if (System.currentTimeMillis() < (mPref.getLong(FIRST_USE, System.currentTimeMillis()) + DAYS_UNTIL_PROMPT)) return false; if (mPref.getInt(USE_COUNT, 0) <= LAUNCHES_UNTIL_PROMPT) return false; if (System.currentTimeMillis() < (mPref.getLong(REMIND_LATER_DATE, System.currentTimeMillis()) + DAYS_UNTIL_REMIND_AGAIN)) return false; return true; } public synchronized void incrementUseCount() { Editor editor = mPref.edit(); int version_code = 0; try { version_code = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0).versionCode; } catch (NameNotFoundException exc) { Log.e(TAG, "PackageName not found: " + mContext.getPackageName()); } int tracking_version = mPref.getInt(TRACKING_VERSION, -1); if (tracking_version == -1) { tracking_version = version_code; editor.putInt(TRACKING_VERSION, tracking_version); } if (tracking_version == version_code) { if (mPref.getLong(FIRST_USE, 0L) == 0L) editor.putLong(FIRST_USE, System.currentTimeMillis()); editor.putInt(USE_COUNT, mPref.getInt(USE_COUNT, 0) + 1); } else { editor.putInt(TRACKING_VERSION, version_code).putLong(FIRST_USE, System.currentTimeMillis()).putInt(USE_COUNT, 1) .putBoolean(DECLINED_RATE, false).putLong(REMIND_LATER_DATE, 0L).putBoolean(APP_RATED, false); } PreferenceEditorHelper.commit(editor); } @SuppressLint("StringFormatMatches") public void show() { final Editor editor = mPref.edit(); final PackageManager pm = mContext.getPackageManager(); String appName = null; try { ApplicationInfo ai = pm.getApplicationInfo(mContext.getPackageName(), 0); appName = (String) pm.getApplicationLabel(ai); } catch (final NameNotFoundException e) { Log.e(TAG, "Application with the package name '" + mContext.getPackageName() + "' can not be found"); appName = ""; } new AlertDialog.Builder(mContext) .setTitle(R.string.dialog_cmgrate_title) .setMessage(mContext.getString(R.string.dialog_cmgrate_message, appName)) .setCancelable(false) .setIcon(mContext.getApplicationInfo().icon) .setPositiveButton(mContext.getString(R.string.dialog_cmgrate_ok, appName), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { editor.putBoolean(APP_RATED, true); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + mContext.getPackageName())); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); mContext.startActivity(intent); PreferenceEditorHelper.commit(editor); dialog.dismiss(); } }).setNegativeButton(R.string.dialog_cmgrate_no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { PreferenceEditorHelper.commit(editor.putBoolean(DECLINED_RATE, true)); dialog.dismiss(); } }).setNeutralButton(R.string.dialog_cmgrate_later, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { PreferenceEditorHelper.commit(editor.putLong(REMIND_LATER_DATE, System.currentTimeMillis())); dialog.dismiss(); } }).show(); PreferenceEditorHelper.commit(editor); } private static String ratePreferenceToString(SharedPreferences pref) { StringBuilder builder = new StringBuilder("CMG App Rater Preferences: "); builder.append(DECLINED_RATE).append(": ").append(pref.getBoolean(DECLINED_RATE, false)).append(",\n"); builder.append(APP_RATED).append(": ").append(pref.getBoolean(APP_RATED, false)).append(",\n"); builder.append(TRACKING_VERSION).append(": ").append(pref.getInt(TRACKING_VERSION, -1)).append(",\n"); builder.append(FIRST_USE).append(": ").append(pref.getLong(FIRST_USE, 0L)).append(",\n"); builder.append(USE_COUNT).append(": ").append(pref.getInt(USE_COUNT, 0)).append(",\n"); builder.append(REMIND_LATER_DATE).append(": ").append(pref.getLong(REMIND_LATER_DATE, 0)); return builder.toString(); } @Override public String toString() { return ratePreferenceToString(mPref); } }
package mondrian.olap.fun; import mondrian.olap.*; /** * A <code>MultiResolver</code> considers several overloadings of the same * function. If one of these overloadings matches the actual arguments, it * calls the factory method {@link #createFunDef}. * * @author jhyde * @since Feb 12, 2003 * @version $Id$ */ public abstract class MultiResolver extends FunUtil implements Resolver { private final String name; private final String signature; private final String description; private final String[] signatures; private final Syntax syntax; /** * Creates a <code>MultiResolver</code>. * * @param name Name of function or operator * @param signature Signature of function or operator * @param description Description of function or operator * @param signatures Array of possible signatures, each of which is an * encoding of the syntactic type, return type, and parameter * types of this operator. The "Members" operator has a syntactic * type "pxd" which means "an operator with * {@link Syntax#Property property} syntax (p) which returns a set * (x) and takes a dimension (d) as its argument". * See {@link FunUtil#decodeSyntacticType(String)}, * {@link FunUtil#decodeReturnCategory(String)}, * {@link FunUtil#decodeParameterCategories(String)}. */ protected MultiResolver( String name, String signature, String description, String[] signatures) { this.name = name; this.signature = signature; this.description = description; this.signatures = signatures; Util.assertTrue(signatures.length > 0); this.syntax = decodeSyntacticType(signatures[0]); for (int i = 1; i < signatures.length; i++) { Util.assertTrue(decodeSyntacticType(signatures[i]) == syntax); } } public String getName() { return name; } public String getDescription() { return description; } public String getSignature() { return signature; } public Syntax getSyntax() { return syntax; } public String[] getReservedWords() { return emptyStringArray; } public String[] getSignatures() { return signatures; } public FunDef getFunDef() { return null; } public FunDef resolve( Exp[] args, Validator validator, int[] conversionCount) { outer: for (String signature : signatures) { int[] parameterTypes = decodeParameterCategories(signature); if (parameterTypes.length != args.length) { continue; } for (int i = 0; i < args.length; i++) { if (!validator.canConvert( args[i], parameterTypes[i], conversionCount)) { continue outer; } } int returnType = decodeReturnCategory(signature); FunDef dummy = createDummyFunDef(this, returnType, args); return createFunDef(args, dummy); } return null; } public boolean requiresExpression(int k) { for (String signature : signatures) { int[] parameterTypes = decodeParameterCategories(signature); if ((k < parameterTypes.length) && parameterTypes[k] == Category.Set) { return false; } } return true; } protected abstract FunDef createFunDef(Exp[] args, FunDef dummyFunDef); } // End MultiResolver.java
package org.mozilla.focus.privacy; import android.content.Context; import android.preference.PreferenceManager; import android.support.test.InstrumentationRegistry; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import android.support.test.uiautomator.UiObjectNotFoundException; import android.util.Log; import junit.framework.Assert; import org.junit.After; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mozilla.focus.activity.MainActivity; import org.mozilla.focus.helpers.TestHelper; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import okhttp3.mockwebserver.RecordedRequest; import static android.support.test.espresso.action.ViewActions.click; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mozilla.focus.fragment.FirstrunFragment.FIRSTRUN_PREF; import static org.mozilla.focus.helpers.TestHelper.waitingTime; /** * This test browses to a test site and makes sure that no traces are left on disk. * * The test uses a whitelist so it might fail as soon as you store new files on disk. */ @RunWith(AndroidJUnit4.class) public class WebViewDataTest { private static final String LOGTAG = "WebViewDataTest"; /** * A list of files Android Studio will inject into the data dir if you: * - Build with Android Studio 3.0+ * - Have opened the "Android Profiler" tab at least once since the AS process started * - Run on an API 26+ device (or maybe when explicitly enabling advanced debugging on older devices) */ private static final Set<String> ANDROID_PROFILER_FILES = Collections.unmodifiableSet(new HashSet<>(Arrays.asList( "libperfa_x86.so", "perfa.jar", "perfd" ))); private static final Set<String> WHITELIST_DATA_DIR_CONTENTS; static { final Set<String> whitelistDataDirContents = new HashSet<>(Arrays.asList( "cache", "code_cache", "shared_prefs", "app_dxmaker_cache", "telemetry", "databases", "app_webview", "files", "app_screengrab" // The folder we store our screenshots in. )); // These profiler files should only be present local builds and we don't want to risk breaking the profiler // by removing them so we whitelist them. Additional details around when these files are added can be found in: // https://github.com/mozilla-mobile/focus-android/issues/1842#issuecomment-348038392 whitelistDataDirContents.addAll(ANDROID_PROFILER_FILES); WHITELIST_DATA_DIR_CONTENTS = Collections.unmodifiableSet(whitelistDataDirContents); } // We expect those folders to exist but they should be empty. private static final List<String> WHITELIST_EMPTY_FOLDERS = Collections.singletonList( "app_textures" ); // These profiler files should only be present local builds and we don't want to risk breaking the profiler // by removing them so we ignore them. Additional details around when these files are added can be found in: // https://github.com/mozilla-mobile/focus-android/issues/1842#issuecomment-348038392 private static final Set<String> NO_TRACES_IGNORE_LIST = Collections.unmodifiableSet(new HashSet<>(ANDROID_PROFILER_FILES)); private static final String TEST_PATH = "/copper/truck/destroy?smoke=violet#bizarre"; /** * If any of those strings show up in local files then we consider the browsing session to be leaked. */ private static final List<String> TEST_TRACES = Arrays.asList( // URL fragments "localhost", "copper", "truck", "destroy", "smoke", "violet", "bizarre", // Content from the test page "groovy", "rabbits", "gigantic", "experience", // Content from cookies "birthday", "armchair", "sphere", "battery", // Content from service worker "KANGAROO" ); private Context appContext; private MockWebServer webServer; @Rule public ActivityTestRule<MainActivity> mActivityTestRule = new ActivityTestRule<MainActivity>(MainActivity.class) { @Override protected void beforeActivityLaunched() { super.beforeActivityLaunched(); appContext = InstrumentationRegistry.getInstrumentation() .getTargetContext() .getApplicationContext(); PreferenceManager.getDefaultSharedPreferences(appContext) .edit() .putBoolean(FIRSTRUN_PREF, true) .apply(); webServer = new MockWebServer(); try { webServer.enqueue(new MockResponse() .setBody(TestHelper.readTestAsset("test.html")) .addHeader("Set-Cookie", "sphere=battery; Expires=Wed, 21 Oct 2035 07:28:00 GMT;")); webServer.enqueue(new MockResponse() .setBody(TestHelper.readTestAsset("service-worker.js")) .setHeader("Content-Type", "text/javascript")); webServer.start(); } catch (IOException e) { throw new AssertionError("Could not start web server", e); } } @Override protected void afterActivityFinished() { super.afterActivityFinished(); try { webServer.shutdown(); } catch (IOException e) { throw new AssertionError("Could not stop web server", e); } } }; @After public void tearDown() throws Exception { mActivityTestRule.getActivity().finishAndRemoveTask(); } @Test public void DeleteWebViewDataTest() throws InterruptedException, UiObjectNotFoundException, IOException { // Load website with service worker TestHelper.inlineAutocompleteEditText.waitForExists(waitingTime); TestHelper.inlineAutocompleteEditText.clearTextField(); TestHelper.inlineAutocompleteEditText.setText(webServer.url(TEST_PATH).toString()); TestHelper.hint.waitForExists(waitingTime); TestHelper.pressEnterKey(); Assert.assertTrue(TestHelper.webView.waitForExists(waitingTime)); // Assert website is loaded // check for disappearance of progress bar (as content won't load in geckoview) TestHelper.progressBar.waitUntilGone(waitingTime); // Erase browsing session TestHelper.floatingEraseButton.perform(click()); TestHelper.erasedMsg.waitForExists(waitingTime); Assert.assertTrue(TestHelper.inlineAutocompleteEditText.exists()); TestHelper.waitForIdle(); // Make sure all resources have been loaded from the web server assertPathsHaveBeenRequested(webServer, "/copper/truck/destroy?smoke=violet", // Actual URL "/copper/truck/service-worker.js"); // Our service worker is installed // Now let's assert that there are no surprises in the data directory final File dataDir = new File(appContext.getApplicationInfo().dataDir); assertTrue("App data directory should exist", dataDir.exists()); final File webViewDirectory = new File(dataDir, "app_webview"); assertTrue("WebView directory should exist", webViewDirectory.exists()); assertTrue("WebView directory contains several subdirectories", webViewDirectory.list().length <= 3); assertTrue("WebView subdirectories may be one of several", webViewDirectory.list()[0].equals("Service Worker") || webViewDirectory.list()[0].equals("GPUCache") || webViewDirectory.list()[0].equals("Local Storage")); assertCacheDirContentsPostErase(); for (final String name : dataDir.list()) { if (WHITELIST_EMPTY_FOLDERS.contains(name)) { final File folder = new File(dataDir, name); assertTrue(" Check +'" + name + "' is empty folder", folder.isDirectory() && folder.list().length == 0); continue; } assertTrue("Expected file '" + name + "' to be in the app's data dir whitelist", WHITELIST_DATA_DIR_CONTENTS.contains(name)); } assertNoTraces(dataDir); } private void assertPathsHaveBeenRequested(MockWebServer webServer, String... paths) throws InterruptedException { final List<String> expectedPaths = new ArrayList<>(paths.length); Collections.addAll(expectedPaths, paths); RecordedRequest request; while ((request = webServer.takeRequest(waitingTime, TimeUnit.MILLISECONDS)) != null) { if (!expectedPaths.remove(request.getPath())) { throw new AssertionError("Unknown path requested: " + request.getPath()); } } if (!expectedPaths.isEmpty()) { throw new AssertionError("Expected paths not requested: " + expectedPaths); } } private void assertNoTraces(File directory) throws IOException { for (final String name : directory.list()) { final File file = new File(directory, name); if (file.isDirectory()) { assertNoTraces(file); continue; } if (NO_TRACES_IGNORE_LIST.contains(name)) { Log.d(LOGTAG, "assertNoTraces: Ignoring file '" + name + "'..."); continue; } final String content = TestHelper.readFileToString(file); for (String trace : TEST_TRACES) { assertFalse("File '" + name + "' should not contain any traces of browser session (" + trace + ", path=" + file.getAbsolutePath() + ")", content.contains(trace)); } } } private void assertCacheDirContentsPostErase() { final File cacheDir = appContext.getCacheDir(); assertTrue(cacheDir.isDirectory()); final File[] cacheContents = cacheDir.listFiles(); assertTrue("cache contents directory may contain subdirectories", cacheContents.length <= 3); // Concern: different versions of WebView may have different structures to their files: // we'll cross that bridge when we come to it. final File webViewCacheDir = cacheContents[0]; assertEquals("sentry-buffered-events", webViewCacheDir.getName()); assertTrue(webViewCacheDir.isDirectory()); final List<File> webviewCacheContents = Arrays.asList(webViewCacheDir.listFiles()); assertTrue("webviewCacheContents directory may contain subdirectories", webviewCacheContents.size() <= 3); } }
package com.microexample.geolocation.controllers; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import com.microexample.geolocation.contracts.ICoordinatesService; import com.microexample.geolocation.models.Coordinate; @Controller @RequestMapping("/coordinates") public class CoordinatesController { private final ICoordinatesService _coordinatesService; @Autowired public CoordinatesController(ICoordinatesService coordinatesService) { _coordinatesService = coordinatesService; } @RequestMapping(method = RequestMethod.POST) @ResponseStatus(value = HttpStatus.CREATED) public @ResponseBody void post(@Valid @RequestBody Coordinate coordinate) { _coordinatesService.save(coordinate); } }
package com.example.profbola.bakingtime.ui; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Parcelable; import android.support.annotation.Nullable; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v4.os.ResultReceiver; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import com.example.profbola.bakingtime.R; import com.example.profbola.bakingtime.models.Ingredient; import com.example.profbola.bakingtime.models.Recipe; import com.example.profbola.bakingtime.models.Step; import com.example.profbola.bakingtime.provider.RecipeContract; import com.example.profbola.bakingtime.services.RecipeService; import com.example.profbola.bakingtime.utils.RecipeConstants; import com.example.profbola.bakingtime.utils.RecipePagerAdapter; import java.util.List; import static com.example.profbola.bakingtime.utils.RecipeConstants.RecipeDetailsConstants.*; public class RecipeDetailActivity extends AppCompatActivity implements IngredientsFragment.OnIngredientSelected, StepsFragment.OnVideoPlayerSelected, LoaderManager.LoaderCallbacks<Cursor> { private Toolbar toolbar; private TabLayout tabLayout; private ViewPager viewPager; private IngredientsFragment mIngredientsFragment; private StepsFragment mStepsFragment; private FullDetailsFragment mFullDetailsFragment; private boolean mTwoPane; private Recipe mRecipe; private List<Ingredient> mIngredients; private List<Step> mSteps; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.recipe_detail_activity); if (findViewById(R.id.recipe_full_view) != null) { mTwoPane = true; mFullDetailsFragment = new FullDetailsFragment(); getSupportFragmentManager().beginTransaction() .add(R.id.recipe_full_view, mFullDetailsFragment) .commit(); } else { mTwoPane = false; } if (savedInstanceState == null) { // FIXME: 7/13/2017 Add NULL Guard Intent intent = getIntent(); if (intent != null && intent.hasExtra(RecipeConstants.RECIPE)) { Recipe recipe = (Recipe) getIntent().getExtras().get(RecipeConstants.RECIPE); // FIXME: 7/8/2017 Register Loaders mRecipe = recipe; mIngredientsFragment = new IngredientsFragment(); mStepsFragment = new StepsFragment(); setUpLoaders(); } } toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setTitle(mRecipe.name); getSupportActionBar().setDisplayHomeAsUpEnabled(true); if (mTwoPane) { // We are in Tablet view getSupportFragmentManager() .beginTransaction() .add(R.id.steps_fragment, mStepsFragment) .add(R.id.ingrediens_fragment, mIngredientsFragment) .commit(); } else { initViewPager(); } } private void setUpViewPager(IngredientsFragment ingredientsFragment, StepsFragment stepsFragment) { RecipePagerAdapter adapter = new RecipePagerAdapter(getSupportFragmentManager()); //TODO: Add the fragments adapter.addFragment(ingredientsFragment, INGREDIENT_TAB); adapter.addFragment(stepsFragment, STEP_TAB); viewPager.setAdapter(adapter); } private void initViewPager() { viewPager = (ViewPager) findViewById(R.id.viewPager); setUpViewPager(mIngredientsFragment, mStepsFragment); tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setupWithViewPager(viewPager, true); } @Override public void ingredientClicked(Ingredient ingredient) { routeToFragmentOrActivity(ingredient, INGREDIENTS_KEY); } @Override public void videoClicked(Step step) { routeToFragmentOrActivity(step, STEP_KEY); } private void routeToFragmentOrActivity(Parcelable object, String type) { if (mTwoPane) { FullDetailsFragment newFragment = new FullDetailsFragment(); Bundle bundle = new Bundle(); bundle.putParcelable(type, object); newFragment.setArguments(bundle); getSupportFragmentManager().beginTransaction() .replace(R.id.recipe_full_view, newFragment) .commit(); } else { Intent intent = new Intent(this, FullDetailActivity.class); intent.putExtra(type, object); startActivity(intent); } } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { int recipeId = mRecipe.id; switch (id) { case STEP_LOADER_ID: Uri STEP_URI = RecipeContract.StepEntry.CONTENT_URI(recipeId); String sortOrder = RecipeContract.StepEntry.COLUMN_ID + " ASC"; return createQueryCursor(STEP_URI, sortOrder); case INGREDIENT_LOADER_ID: Uri INGREDIENT_URI = RecipeContract.IngredientEntry.CONTENT_URI(recipeId); return createQueryCursor(INGREDIENT_URI, null); default: throw new RuntimeException("Loader Not Implemented: " + id); } } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { switch (loader.getId()) { case INGREDIENT_LOADER_ID: // mIngredientsFragment = new IngredientsFragment(); List<Ingredient> ingredients = Ingredient.convertCursor(data); if (ingredients != null) deliverDataToIngredientFragment(ingredients); break; case STEP_LOADER_ID: // mStepsFragment = new StepsFragment(); List<Step> steps = Step.convertCursor(data); if (steps != null) deliverDataToStepFragment(steps); break; default: throw new RuntimeException("Loader Not Implemented: " + loader.getId()); } // FIXME: 7/8/2017 SetUp Fragments } @Override public void onLoaderReset(Loader<Cursor> loader) { } private CursorLoader createQueryCursor(Uri contentUri, String sortOrder) { return new CursorLoader(this, contentUri, null, null, null, sortOrder); } private void setUpLoaders() { getSupportLoaderManager().initLoader(STEP_LOADER_ID, null, this); getSupportLoaderManager().initLoader(INGREDIENT_LOADER_ID, null, this); } private void deliverDataToIngredientFragment(List<Ingredient> ingredients) { Object fragment; if (mTwoPane) { fragment = getSupportFragmentManager().findFragmentById(R.id.ingrediens_fragment); } else { fragment = viewPager.getAdapter().instantiateItem(viewPager, 0); } if (checkFragment(fragment, IngredientsFragment.class)) { mIngredientsFragment = (IngredientsFragment) fragment; mIngredientsFragment.addData(ingredients.toArray(new Ingredient[ingredients.size()])); mIngredients = ingredients; } } private void deliverDataToStepFragment(List<Step> steps) { Object fragment; if (mTwoPane) { fragment = getSupportFragmentManager().findFragmentById(R.id.steps_fragment); } else { fragment = viewPager.getAdapter().instantiateItem(viewPager, 1); } if (checkFragment(fragment, StepsFragment.class)) { mStepsFragment = (StepsFragment) fragment; mStepsFragment.addData(steps.toArray(new Step[steps.size()])); mSteps = steps; } } private boolean checkFragment(Object fragmentToCheck, Class<? extends Fragment> klass) { return klass.isInstance(fragmentToCheck); } }
package com.googlecode.iptableslog; public class Iptables { public static final String[] CELL_INTERFACES = { "rmnet+", "ppp+", "pdp+" }; public static final String[] WIFI_INTERFACES = { "eth+", "wlan+", "tiwlan+", "athwlan+" }; public static boolean startLog() { if(checkLog() == true) return false; for(String iface : CELL_INTERFACES) { ShellCommand command = new ShellCommand(new String[] { "su", "-c", "iptables -I OUTPUT 1 -o " + iface + " -j LOG --log-prefix \"[IptablesLogEntry]\" --log-uid" }); command.start(); while(command.checkForExit() == false) try { Thread.sleep(100); } catch (Exception e) { e.printStackTrace(); } command = new ShellCommand(new String[] { "su", "-c", "iptables -I INPUT 1 -i " + iface + " -j LOG --log-prefix \"[IptablesLogEntry]\" --log-uid" }); command.start(); while(command.checkForExit() == false) try { Thread.sleep(100); } catch (Exception e) { e.printStackTrace(); } } for(String iface : WIFI_INTERFACES) { ShellCommand command = new ShellCommand(new String[] { "su", "-c", "iptables -I OUTPUT 1 -o " + iface + " -j LOG --log-prefix \"[IptablesLogEntry]\" --log-uid" }); command.start(); while(command.checkForExit() == false) try { Thread.sleep(100); } catch (Exception e) { e.printStackTrace(); } command = new ShellCommand(new String[] { "su", "-c", "iptables -I INPUT 1 -i " + iface + " -j LOG --log-prefix \"[IptablesLogEntry]\" --log-uid" }); command.start(); while(command.checkForExit() == false) try { Thread.sleep(100); } catch (Exception e) { e.printStackTrace(); } } return true; } public static boolean stopLog() { if(checkLog() == false) return false; for(String iface : CELL_INTERFACES) { ShellCommand command = new ShellCommand(new String[] { "su", "-c", "iptables -D INPUT 1" }); command.start(); while(command.checkForExit() == false) try { Thread.sleep(100); } catch (Exception e) { e.printStackTrace(); } command = new ShellCommand(new String[] { "su", "-c", "iptables -D OUTPUT 1" }); command.start(); while(command.checkForExit() == false) try { Thread.sleep(100); } catch (Exception e) { e.printStackTrace(); } } for(String iface : WIFI_INTERFACES) { ShellCommand command = new ShellCommand(new String[] { "su", "-c", "iptables -D INPUT 1" }); command.start(); while(command.checkForExit() == false) try { Thread.sleep(100); } catch (Exception e) { e.printStackTrace(); } command = new ShellCommand(new String[] { "su", "-c", "iptables -D OUTPUT 1" }); command.start(); while(command.checkForExit() == false) try { Thread.sleep(100); } catch (Exception e) { e.printStackTrace(); } } return true; } public static boolean checkLog() { ShellCommand command = new ShellCommand(new String[] { "su", "-c", "iptables -L" }); command.start(); String result = command.readStdout(); command.finish(); return result.indexOf("[IptablesLogEntry]", 0) == -1 ? false : true; } }
package com.shamanland.facebook.likebutton; import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.os.Build; import android.os.Bundle; import android.os.Message; import android.text.Html; import android.util.Base64; import android.view.SoundEffectConstants; import android.webkit.WebChromeClient; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.FrameLayout; import java.io.ByteArrayOutputStream; import java.net.URLEncoder; import java.util.LinkedList; public class FacebookLikeActivity extends Activity { public static final String APP_ID = "app.id"; public static final String URL = "url"; public static final String TITLE = "title"; public static final String TEXT = "text"; public static final String PICTURE = "picture"; private FrameLayout mFrame; private final LinkedList<WebView> mWindows; private final WebChromeClient mWebChromeClient; private final WebViewClient mWebViewClient; public Context getContext() { return this; } public FacebookLikeActivity() { mWindows = new LinkedList<WebView>(); mWebChromeClient = new WebChromeClient() { @Override public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) { WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj; transport.setWebView(createWindow()); resultMsg.sendToTarget(); return true; } @Override public void onCloseWindow(WebView window) { removeWindow(window); } }; mWebViewClient = new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } }; } @Override protected void onCreate(Bundle state) { super.onCreate(state); mFrame = new FrameLayout(getContext()); setContentView(mFrame); String appId = getIntent().getStringExtra(APP_ID); String url = getIntent().getStringExtra(URL); String title = getIntent().getStringExtra(TITLE); String text = getIntent().getStringExtra(TEXT); Bitmap picture = getIntent().getParcelableExtra(PICTURE); StringBuilder sb = new StringBuilder(); sb.append("<!DOCTYPE html>"); sb.append("<html>"); sb.append("<body>"); if (title != null) { sb.append("<h1>"); sb.append(escapeHtml(title)); sb.append("</h1>"); } if (picture != null) { String picture64 = bitmapToBase64(picture); if (picture64 != null) { sb.append("<img "); sb.append("style='float:left;margin:4px;'"); sb.append("src='data:image/png;base64,").append(picture64).append("'"); sb.append("/>"); } } if (text != null) { sb.append("<p>"); sb.append(escapeHtml(text)); sb.append("</p>"); } if (url != null) { sb.append("<iframe "); sb.append("style='display:block;clear:both;border:none;overflow:hidden;'"); sb.append("src=' sb.append("?href=").append(URLEncoder.encode(url)); sb.append("&layout=standard"); sb.append("&action=like"); sb.append("&show_faces=true"); sb.append("&share=true"); if (appId != null) { sb.append("&appId=").append(appId); } sb.append("'"); sb.append("scrolling='no'"); sb.append("frameborder='0'"); sb.append("allowTransparency='true'"); sb.append("></iframe>"); } sb.append("</body>"); sb.append("</html>"); createWindow().loadDataWithBaseURL(url, sb.toString(), "text/html", "utf-8", null); } protected WebView createWindow() { WebView window = new WebView(getContext()); window.getSettings().setJavaScriptEnabled(true); window.getSettings().setSupportMultipleWindows(true); window.setWebChromeClient(mWebChromeClient); window.setWebViewClient(mWebViewClient); mWindows.add(window); mFrame.addView(window); return window; } protected boolean removeWindow(WebView window) { if (mWindows.size() > 1) { mWindows.remove(window); mFrame.removeView(window); return true; } else { window.stopLoading(); window.loadDataWithBaseURL("about:blank", "<html></html>", "text/html", "utf-8", null); return false; } } @Override public void onBackPressed() { boolean handled = false; WebView window = mWindows.peekLast(); if (window != null) { if (window.canGoBack()) { window.goBack(); handled = true; } else { handled = removeWindow(window); } } if (handled) { mFrame.playSoundEffect(SoundEffectConstants.CLICK); } else { super.onBackPressed(); } } public static String escapeHtml(String unsecure) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { return Html.fromHtml(unsecure).toString(); } else { return Html.escapeHtml(unsecure); } } public static String bitmapToBase64(Bitmap picture) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); picture.compress(Bitmap.CompressFormat.PNG, 100, baos); return Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT); } catch (Throwable ex) { return null; } } }
package org.zstack.test; import org.springframework.beans.factory.annotation.Autowire; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Configurable; import org.zstack.appliancevm.APIListApplianceVmMsg; import org.zstack.appliancevm.APIListApplianceVmReply; import org.zstack.appliancevm.ApplianceVmInventory; import org.zstack.billing.*; import org.zstack.core.Platform; import org.zstack.core.cloudbus.CloudBus; import org.zstack.core.cloudbus.CloudBusEventListener; import org.zstack.core.componentloader.ComponentLoader; import org.zstack.core.config.*; import org.zstack.core.db.DatabaseFacade; import org.zstack.core.db.SimpleQuery; import org.zstack.core.db.SimpleQuery.Op; import org.zstack.header.allocator.APIGetCpuMemoryCapacityMsg; import org.zstack.header.allocator.APIGetCpuMemoryCapacityReply; import org.zstack.header.allocator.APIGetHostAllocatorStrategiesMsg; import org.zstack.header.allocator.APIGetHostAllocatorStrategiesReply; import org.zstack.header.apimediator.APIIsReadyToGoMsg; import org.zstack.header.apimediator.ApiMediatorConstant; import org.zstack.header.cluster.*; import org.zstack.header.configuration.*; import org.zstack.header.console.APIRequestConsoleAccessEvent; import org.zstack.header.console.APIRequestConsoleAccessMsg; import org.zstack.header.console.ConsoleInventory; import org.zstack.header.exception.CloudRuntimeException; import org.zstack.header.host.*; import org.zstack.header.identity.*; import org.zstack.header.identity.PolicyInventory.Statement; import org.zstack.header.image.*; import org.zstack.header.managementnode.*; import org.zstack.header.message.APIReply; import org.zstack.header.message.Event; import org.zstack.header.network.l2.*; import org.zstack.header.network.l3.*; import org.zstack.header.network.service.*; import org.zstack.header.query.*; import org.zstack.header.search.*; import org.zstack.header.simulator.APIAddSimulatorHostMsg; import org.zstack.header.simulator.ChangeVmStateOnSimulatorHostMsg; import org.zstack.header.simulator.RemoveVmOnSimulatorMsg; import org.zstack.header.simulator.SimulatorDetails; import org.zstack.header.simulator.storage.backup.APIAddSimulatorBackupStorageMsg; import org.zstack.header.simulator.storage.backup.SimulatorBackupStorageConstant; import org.zstack.header.simulator.storage.backup.SimulatorBackupStorageDetails; import org.zstack.header.simulator.storage.primary.APIAddSimulatorPrimaryStorageMsg; import org.zstack.header.simulator.storage.primary.SimulatorPrimaryStorageConstant; import org.zstack.header.simulator.storage.primary.SimulatorPrimaryStorageDetails; import org.zstack.header.storage.backup.*; import org.zstack.header.storage.primary.*; import org.zstack.header.storage.snapshot.*; import org.zstack.header.tag.*; import org.zstack.header.vm.*; import org.zstack.header.volume.*; import org.zstack.header.volume.APIGetVolumeFormatReply.VolumeFormatReplyStruct; import org.zstack.header.zone.*; import org.zstack.kvm.APIAddKVMHostMsg; import org.zstack.kvm.APIUpdateKVMHostMsg; import org.zstack.kvm.KVMHostInventory; import org.zstack.license.*; import org.zstack.network.securitygroup.*; import org.zstack.network.securitygroup.APIAddSecurityGroupRuleMsg.SecurityGroupRuleAO; import org.zstack.network.service.eip.*; import org.zstack.network.service.lb.*; import org.zstack.network.service.portforwarding.*; import org.zstack.network.service.vip.*; import org.zstack.network.service.virtualrouter.*; import org.zstack.portal.managementnode.ManagementNodeManager; import org.zstack.storage.backup.sftp.APIReconnectSftpBackupStorageEvent; import org.zstack.storage.backup.sftp.APIReconnectSftpBackupStorageMsg; import org.zstack.storage.backup.sftp.APIUpdateSftpBackupStorageMsg; import org.zstack.storage.backup.sftp.SftpBackupStorageInventory; import org.zstack.storage.ceph.backup.*; import org.zstack.storage.ceph.primary.*; import org.zstack.storage.primary.iscsi.APIUpdateIscsiFileSystemBackendPrimaryStorageMsg; import org.zstack.storage.primary.iscsi.IscsiFileSystemBackendPrimaryStorageInventory; import org.zstack.storage.primary.local.*; import org.zstack.utils.CollectionUtils; import org.zstack.utils.TimeUtils; import org.zstack.utils.Utils; import org.zstack.utils.data.SizeUnit; import org.zstack.utils.function.Function; import org.zstack.utils.gson.JSONObjectUtil; import org.zstack.utils.logging.CLogger; import java.util.*; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import static org.zstack.utils.CollectionDSL.list; @Configurable(preConstruction = true, autowire = Autowire.BY_TYPE) public class Api implements CloudBusEventListener { private static final CLogger logger = Utils.getLogger(Api.class); private static ComponentLoader loader; private ManagementNodeManager mgr; private SessionInventory adminSession; private int timeout = 15; @Autowired private CloudBus bus; @Autowired private DatabaseFacade dbf; static { loader = Platform.getComponentLoader(); } private void start() { mgr.startNode(); } public void prepare() { try { adminSession = this.loginAsAdmin(); } catch (ApiSenderException e1) { throw new CloudRuntimeException(e1); } } public void startServer() { mgr = loader.getComponent(ManagementNodeManager.class); start(); final CountDownLatch count = new CountDownLatch(1); APIIsReadyToGoMsg msg = new APIIsReadyToGoMsg(); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setManagementNodeId(Platform.getManagementServerId()); msg.setTimeout(TimeUnit.MINUTES.toMillis(2)); bus.call(msg); logger.info("Server is running ..."); prepare(); } public void stopServer() { ManagementNodeExitMsg msg = new ManagementNodeExitMsg(); msg.setServiceId(bus.makeLocalServiceId(ManagementNodeConstant.SERVICE_ID)); bus.send(msg); } public void stopServerTilManagementNodeDisappear(final String mgmtUuid, long timeout) { stopServer(); class Result { boolean success; } final Result res = new Result(); TimeUtils.loopExecuteUntilTimeoutIgnoreException(timeout, 1, TimeUnit.SECONDS, new Callable<Boolean>() { @Override public Boolean call() throws Exception { SimpleQuery<ManagementNodeVO> q = dbf.createQuery(ManagementNodeVO.class); q.add(ManagementNodeVO_.uuid, Op.EQ, mgmtUuid); ManagementNodeVO vo = q.find(); res.success = vo == null; return res.success; } }); if (!res.success) { throw new RuntimeException(String.format("failed to stop management server[uuid:%s] after %s secs", mgmtUuid, timeout)); } } public ApiSender getApiSender() { return new ApiSender(); } public List<HostInventory> getMigrationTargetHost(String vmUuid) throws ApiSenderException { APIGetVmMigrationCandidateHostsMsg msg = new APIGetVmMigrationCandidateHostsMsg(); msg.setVmInstanceUuid(vmUuid); msg.setSession(adminSession); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIGetVmMigrationCandidateHostsReply reply = sender.call(msg, APIGetVmMigrationCandidateHostsReply.class); return reply.getInventories(); } public VolumeSnapshotInventory createSnapshot(String volUuid) throws ApiSenderException { return createSnapshot(volUuid, null); } public VolumeSnapshotInventory createSnapshot(String volUuid, SessionInventory session) throws ApiSenderException { APICreateVolumeSnapshotMsg msg = new APICreateVolumeSnapshotMsg(); msg.setSession(session == null ? adminSession : session); msg.setName("Snapshot-" + volUuid); msg.setDescription("Test snapshot"); msg.setVolumeUuid(volUuid); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APICreateVolumeSnapshotEvent evt = sender.send(msg, APICreateVolumeSnapshotEvent.class); return evt.getInventory(); } public ImageInventory createTemplateFromSnapshot(String snapshotUuid) throws ApiSenderException { return createTemplateFromSnapshot(snapshotUuid, (SessionInventory) null); } public ImageInventory createTemplateFromSnapshot(String snapshotUuid, SessionInventory session) throws ApiSenderException { return createTemplateFromSnapshot(snapshotUuid, (List) null, session); } public VolumeInventory createDataVolumeFromSnapshot(String snapshotUuid) throws ApiSenderException { return createDataVolumeFromSnapshot(snapshotUuid, (SessionInventory) null); } public VolumeInventory createDataVolumeFromSnapshot(String snapshotUuid, SessionInventory session) throws ApiSenderException { return createDataVolumeFromSnapshot(snapshotUuid, null, session); } public VolumeInventory createDataVolumeFromSnapshot(String snapshotUuid, String priUuid) throws ApiSenderException { return createDataVolumeFromSnapshot(snapshotUuid, priUuid, null); } public VolumeInventory createDataVolumeFromSnapshot(String snapshotUuid, String priUuid, SessionInventory session) throws ApiSenderException { APICreateDataVolumeFromVolumeSnapshotMsg msg = new APICreateDataVolumeFromVolumeSnapshotMsg(); msg.setSession(session == null ? adminSession : session); msg.setPrimaryStorageUuid(priUuid); msg.setName("volume-form-snapshot" + snapshotUuid); msg.setVolumeSnapshotUuid(snapshotUuid); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APICreateDataVolumeFromVolumeSnapshotEvent evt = sender.send(msg, APICreateDataVolumeFromVolumeSnapshotEvent.class); return evt.getInventory(); } public ImageInventory createTemplateFromSnapshot(String snapshotUuid, List<String> backupStorageUuids) throws ApiSenderException { return createTemplateFromSnapshot(snapshotUuid, backupStorageUuids, null); } public ImageInventory createTemplateFromSnapshot(String snapshotUuid, List<String> backupStorageUuids, SessionInventory session) throws ApiSenderException { APICreateRootVolumeTemplateFromVolumeSnapshotMsg msg = new APICreateRootVolumeTemplateFromVolumeSnapshotMsg(); msg.setSession(session == null ? adminSession : session); msg.setBackupStorageUuids(backupStorageUuids); msg.setSnapshotUuid(snapshotUuid); msg.setName(String.format("image-from-snapshot-%s", snapshotUuid)); msg.setGuestOsType("CentOS"); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APICreateRootVolumeTemplateFromVolumeSnapshotEvent evt = sender.send(msg, APICreateRootVolumeTemplateFromVolumeSnapshotEvent.class); return evt.getInventory(); } public ImageInventory createTemplateFromSnapshot(String snapshotUuid, String backupStorageUuid) throws ApiSenderException { return createTemplateFromSnapshot(snapshotUuid, Arrays.asList(backupStorageUuid)); } public void deleteSnapshot(String snapshotUuid) throws ApiSenderException { deleteSnapshot(snapshotUuid, null); } public void deleteSnapshot(String snapshotUuid, SessionInventory session) throws ApiSenderException { APIDeleteVolumeSnapshotMsg msg = new APIDeleteVolumeSnapshotMsg(); msg.setSession(session == null ? adminSession : session); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setUuid(snapshotUuid); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); sender.send(msg, APIDeleteVolumeSnapshotEvent.class); } public void revertVolumeToSnapshot(String snapshotUuid) throws ApiSenderException { revertVolumeToSnapshot(snapshotUuid, null); } public void revertVolumeToSnapshot(String snapshotUuid, SessionInventory session) throws ApiSenderException { APIRevertVolumeFromSnapshotMsg msg = new APIRevertVolumeFromSnapshotMsg(); msg.setSession(session == null ? adminSession : session); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setUuid(snapshotUuid); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); sender.send(msg, APIRevertVolumeFromSnapshotEvent.class); } public List<ZoneInventory> createZones(int num) throws ApiSenderException { ApiSender sender = new ApiSender(); sender.setTimeout(timeout); List<ZoneInventory> ret = new ArrayList<ZoneInventory>(); for (int i = 0; i < num; i++) { APICreateZoneMsg msg = new APICreateZoneMsg(); msg.setSession(adminSession); msg.setName("Zone-" + i); msg.setDescription("Test Zone"); APICreateZoneEvent e = sender.send(msg, APICreateZoneEvent.class); ret.add(e.getInventory()); } return ret; } public List<L2VlanNetworkInventory> listL2VlanNetworks(List<String> uuids) throws ApiSenderException { APIListL2VlanNetworkMsg msg = new APIListL2VlanNetworkMsg(); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setSession(adminSession); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIListL2VlanNetworkReply reply = sender.call(msg, APIListL2VlanNetworkReply.class); return reply.getInventories(); } public List<ZoneInventory> listZones(List<String> uuids) throws ApiSenderException { APIListZonesMsg msg = new APIListZonesMsg(uuids); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setSession(adminSession); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIListZonesReply reply = sender.call(msg, APIListZonesReply.class); return reply.getInventories(); } public void deleteZone(String uuid) throws ApiSenderException { ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIDeleteZoneMsg msg = new APIDeleteZoneMsg(uuid); msg.setSession(adminSession); sender.send(msg, APIDeleteZoneEvent.class); } public ZoneInventory changeZoneState(String uuid, ZoneStateEvent evt) throws ApiSenderException { ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIChangeZoneStateMsg msg = new APIChangeZoneStateMsg(uuid, evt.toString()); msg.setSession(adminSession); APIChangeZoneStateEvent ret = sender.send(msg, APIChangeZoneStateEvent.class); return ret.getInventory(); } public void deleteAllZones() throws ApiSenderException { List<ZoneInventory> allZones = listZones(null); for (ZoneInventory zone : allZones) { deleteZone(zone.getUuid()); } } public List<ClusterInventory> createClusters(int num, String zoneUuid) throws ApiSenderException { ApiSender sender = new ApiSender(); sender.setTimeout(timeout); List<ClusterInventory> ret = new ArrayList<ClusterInventory>(); for (int i = 0; i < num; i++) { APICreateClusterMsg msg = new APICreateClusterMsg(); msg.setClusterName("Cluster-" + i); msg.setDescription("Test Cluster"); msg.setHypervisorType("Simulator"); msg.setZoneUuid(zoneUuid); msg.setSession(adminSession); APICreateClusterEvent evt = sender.send(msg, APICreateClusterEvent.class); ret.add(evt.getInventory()); } return ret; } public List<ClusterInventory> listClusters(List<String> uuids) throws ApiSenderException { return listClusters(0, -1, uuids); } public List<ClusterInventory> listClusters(int offset, int length, List<String> uuids) throws ApiSenderException { APIListClusterMsg msg = new APIListClusterMsg(uuids); msg.setSession(adminSession); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setOffset(offset); msg.setLength(length); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIListClusterReply reply = sender.call(msg, APIListClusterReply.class); return reply.getInventories(); } public ClusterInventory changeClusterState(String uuid, ClusterStateEvent evt) throws ApiSenderException { ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIChangeClusterStateMsg msg = new APIChangeClusterStateMsg(uuid, evt.toString()); msg.setSession(adminSession); APIChangeClusterStateEvent e = sender.send(msg, APIChangeClusterStateEvent.class); return e.getInventory(); } public void asyncChangeClusterState(String uuid, ClusterStateEvent evt) throws InterruptedException { APIChangeClusterStateMsg msg = new APIChangeClusterStateMsg(uuid, evt.toString()); msg.setSession(adminSession); bus.send(msg); } public void asyncDeleteCluster(String uuid) throws InterruptedException { APIDeleteClusterMsg msg = new APIDeleteClusterMsg(uuid); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setSession(adminSession); bus.send(msg); } public void deleteCluster(String uuid) throws ApiSenderException { ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIDeleteClusterMsg msg = new APIDeleteClusterMsg(uuid); msg.setSession(adminSession); sender.send(msg, APIDeleteClusterEvent.class); } public List<HostInventory> createHost(int num, String clusterUuid) throws ApiSenderException { ApiSender sender = new ApiSender(); sender.setTimeout(timeout); List<HostInventory> rets = new ArrayList<HostInventory>(); for (int i = 0; i < num; i++) { APIAddSimulatorHostMsg msg = new APIAddSimulatorHostMsg(); msg.setClusterUuid(clusterUuid); msg.setDescription("Test Host"); msg.setManagementIp("10.0.0." + i); msg.setMemoryCapacity(SizeUnit.GIGABYTE.toByte(8)); msg.setCpuCapacity(2400 * 4); msg.setName("Host-" + i); msg.setSession(adminSession); APIAddHostEvent e = sender.send(msg, APIAddHostEvent.class); rets.add(e.getInventory()); } return rets; } public HostInventory changeHostState(String uuid, HostStateEvent evt) throws ApiSenderException { ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIChangeHostStateMsg msg = new APIChangeHostStateMsg(uuid, evt.toString()); msg.setSession(adminSession); sender.setTimeout(60); // for maintenance mode which takes longer time APIChangeHostStateEvent e = sender.send(msg, APIChangeHostStateEvent.class); return e.getInventory(); } public void asyncChangeHostState(String uuid, HostStateEvent evt) { APIChangeHostStateMsg msg = new APIChangeHostStateMsg(uuid, evt.toString()); msg.setSession(adminSession); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); bus.send(msg); } public List<HostInventory> listHosts(List<String> uuids) throws ApiSenderException { return listHosts(0, -1, uuids); } public List<HostInventory> listHosts(int offset, int length, List<String> uuids) throws ApiSenderException { APIListHostMsg msg = new APIListHostMsg(uuids); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setOffset(offset); msg.setSession(adminSession); msg.setLength(length); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIListHostReply reply = sender.call(msg, APIListHostReply.class); return reply.getInventories(); } public void deleteHost(String uuid) throws ApiSenderException { ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIDeleteHostMsg msg = new APIDeleteHostMsg(uuid); msg.setSession(adminSession); sender.send(msg, APIDeleteHostEvent.class); } public HostInventory maintainHost(String uuid) throws ApiSenderException { return changeHostState(uuid, HostStateEvent.maintain); } public List<HostInventory> createSimulator(int num, String clusterUuid, SimulatorDetails details) throws ApiSenderException { ApiSender sender = new ApiSender(); sender.setTimeout(timeout); List<HostInventory> rets = new ArrayList<HostInventory>(); for (int i = 0; i < num; i++) { APIAddSimulatorHostMsg msg = new APIAddSimulatorHostMsg(); msg.setClusterUuid(clusterUuid); msg.setDescription("Test Host"); msg.setManagementIp("10.0.0." + i); msg.setSession(adminSession); msg.setName("Host-" + i); details.fillAPIAddSimulatorHostMsg(msg); APIAddHostEvent e = sender.send(msg, APIAddHostEvent.class); rets.add(e.getInventory()); } return rets; } public List<PrimaryStorageInventory> createSimulatoPrimaryStorage(int num, SimulatorPrimaryStorageDetails details) throws ApiSenderException { ApiSender sender = new ApiSender(); sender.setTimeout(timeout); List<PrimaryStorageInventory> rets = new ArrayList<PrimaryStorageInventory>(); for (int i = 0; i < num; i++) { APIAddSimulatorPrimaryStorageMsg msg = new APIAddSimulatorPrimaryStorageMsg(); msg.setUrl(details.getUrl() + "-" + i); msg.setType("SimulatorPrimaryStorage"); msg.setName("SimulatorPrimaryStorage-" + i); msg.setDescription("Test Primary Storage"); msg.setSession(adminSession); msg.setTotalCapacity(details.getTotalCapacity()); msg.setAvailableCapacity(details.getAvailableCapacity()); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setZoneUuid(details.getZoneUuid()); APIAddPrimaryStorageEvent e = sender.send(msg, APIAddPrimaryStorageEvent.class); rets.add(e.getInventory()); } return rets; } public List<PrimaryStorageInventory> listPrimaryStorage(List<String> uuids) throws ApiSenderException { return listPrimaryStorage(0, -1, uuids); } public List<PrimaryStorageInventory> listPrimaryStorage(int offset, int length, List<String> uuids) throws ApiSenderException { APIListPrimaryStorageMsg msg = new APIListPrimaryStorageMsg(uuids); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setSession(adminSession); msg.setOffset(offset); msg.setLength(length); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIListPrimaryStorageReply reply = sender.call(msg, APIListPrimaryStorageReply.class); return reply.getInventories(); } public void asyncChangePrimaryStorageState(String uuid, PrimaryStorageStateEvent evt) { APIChangePrimaryStorageStateMsg msg = new APIChangePrimaryStorageStateMsg(uuid, evt.toString()); msg.setSession(adminSession); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); bus.send(msg); } public PrimaryStorageInventory changePrimaryStorageState(String uuid, PrimaryStorageStateEvent event) throws ApiSenderException { ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIChangePrimaryStorageStateMsg msg = new APIChangePrimaryStorageStateMsg(uuid, event.toString()); msg.setSession(adminSession); APIChangePrimaryStorageStateEvent e = sender.send(msg, APIChangePrimaryStorageStateEvent.class); return e.getInventory(); } public void asyncDeletePrimaryStorage(String uuid) { APIDeletePrimaryStorageMsg msg = new APIDeletePrimaryStorageMsg(uuid); msg.setSession(adminSession); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); bus.send(msg); } public void deletePrimaryStorage(String uuid) throws ApiSenderException { ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIDeletePrimaryStorageMsg msg = new APIDeletePrimaryStorageMsg(uuid); msg.setSession(adminSession); sender.send(msg, APIDeletePrimaryStorageEvent.class); } public void asyncAttachPrimaryStorage(String clusterUuid, String uuid) throws InterruptedException { APIAttachPrimaryStorageToClusterMsg msg = new APIAttachPrimaryStorageToClusterMsg(clusterUuid, uuid); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setSession(adminSession); bus.send(msg); } public PrimaryStorageInventory attachPrimaryStorage(String clusterUuid, String uuid) throws ApiSenderException { ApiSender sender = new ApiSender(); sender.setTimeout(10000); APIAttachPrimaryStorageToClusterMsg msg = new APIAttachPrimaryStorageToClusterMsg(clusterUuid, uuid); msg.setSession(adminSession); APIAttachPrimaryStorageToClusterEvent e = sender.send(msg, APIAttachPrimaryStorageToClusterEvent.class); return e.getInventory(); } public void asyncDetachPrimaryStorage(String uuid) throws InterruptedException { APIDetachPrimaryStorageFromClusterMsg msg = new APIDetachPrimaryStorageFromClusterMsg(uuid); msg.setSession(adminSession); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); bus.send(msg); } public PrimaryStorageInventory detachPrimaryStorage(String uuid, String clusterUuid) throws ApiSenderException { ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIDetachPrimaryStorageFromClusterMsg msg = new APIDetachPrimaryStorageFromClusterMsg(uuid); msg.setSession(adminSession); msg.setClusterUuid(clusterUuid); APIDetachPrimaryStorageFromClusterEvent e = sender.send(msg, APIDetachPrimaryStorageFromClusterEvent.class); return e.getInventory(); } public List<BackupStorageInventory> createSimulatorBackupStorage(int num, SimulatorBackupStorageDetails details) throws ApiSenderException { ApiSender sender = new ApiSender(); sender.setTimeout(timeout); List<BackupStorageInventory> rets = new ArrayList<BackupStorageInventory>(); for (int i = 0; i < num; i++) { APIAddSimulatorBackupStorageMsg msg = new APIAddSimulatorBackupStorageMsg(); msg.setSession(adminSession); msg.setName("SimulatoryBackupStorage-" + i); msg.setUrl(details.getUrl() + "-" + i); msg.setType(SimulatorBackupStorageConstant.SIMULATOR_BACKUP_STORAGE_TYPE); msg.setDescription("Test Backup Storage"); msg.setTotalCapacity(details.getTotalCapacity()); msg.setAvailableCapacity(details.getTotalCapacity() - details.getUsedCapacity()); APIAddBackupStorageEvent e = sender.send(msg, APIAddBackupStorageEvent.class); rets.add(e.getInventory()); } return rets; } public List<BackupStorageInventory> listBackupStorage(List<String> uuids) throws ApiSenderException { return listBackupStorage(0, -1, uuids); } public List<BackupStorageInventory> listBackupStorage(int offset, int length, List<String> uuids) throws ApiSenderException { APIListBackupStorageMsg msg = new APIListBackupStorageMsg(uuids); msg.setSession(adminSession); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setOffset(offset); msg.setLength(length); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIListBackupStorageReply reply = sender.call(msg, APIListBackupStorageReply.class); return reply.getInventories(); } public void asyncChangeBackupStorageState(String uuid, BackupStorageStateEvent evt) { APIChangeBackupStorageStateMsg msg = new APIChangeBackupStorageStateMsg(uuid, evt.toString()); msg.setSession(adminSession); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); bus.send(msg); } public BackupStorageInventory changeBackupStorageState(String uuid, BackupStorageStateEvent event) throws ApiSenderException { ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIChangeBackupStorageStateMsg msg = new APIChangeBackupStorageStateMsg(uuid, event.toString()); msg.setSession(adminSession); APIChangeBackupStorageStateEvent e = sender.send(msg, APIChangeBackupStorageStateEvent.class); return e.getInventory(); } public void asyncDeleteBackupStorage(String uuid) { APIDeleteBackupStorageMsg msg = new APIDeleteBackupStorageMsg(uuid); msg.setSession(adminSession); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); bus.send(msg); } public void deleteBackupStorage(String uuid) throws ApiSenderException { ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIDeleteBackupStorageMsg msg = new APIDeleteBackupStorageMsg(uuid); msg.setSession(adminSession); sender.send(msg, APIDeleteBackupStorageEvent.class); } public void asyncAttachBackupStorage(String zoneUuid, String uuid) throws InterruptedException { APIAttachBackupStorageToZoneMsg msg = new APIAttachBackupStorageToZoneMsg(zoneUuid, uuid); msg.setSession(adminSession); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); bus.send(msg); } public BackupStorageInventory attachBackupStorage(String zoneUuid, String uuid) throws ApiSenderException { ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIAttachBackupStorageToZoneMsg msg = new APIAttachBackupStorageToZoneMsg(zoneUuid, uuid); msg.setSession(adminSession); APIAttachBackupStorageToZoneEvent e = sender.send(msg, APIAttachBackupStorageToZoneEvent.class); return e.getInventory(); } public void asyncDetachBackupStorage(String uuid) throws InterruptedException { APIDetachBackupStorageFromZoneMsg msg = new APIDetachBackupStorageFromZoneMsg(uuid); msg.setSession(adminSession); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); bus.send(msg); } public BackupStorageInventory detachBackupStorage(String uuid, String zoneUuid) throws ApiSenderException { ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIDetachBackupStorageFromZoneMsg msg = new APIDetachBackupStorageFromZoneMsg(uuid); msg.setSession(adminSession); msg.setZoneUuid(zoneUuid); APIDetachBackupStorageFromZoneEvent e = sender.send(msg, APIDetachBackupStorageFromZoneEvent.class); return e.getInventory(); } public ImageInventory addImage(ImageInventory inv, String...bsUuids) throws ApiSenderException { return addImage(inv, null, bsUuids); } public ImageInventory addImage(ImageInventory inv, SessionInventory session, String...bsUuids) throws ApiSenderException { ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIAddImageMsg msg = new APIAddImageMsg(); msg.setResourceUuid(inv.getUuid()); msg.setSession(session == null ? adminSession : session); msg.setDescription(inv.getDescription()); msg.setMediaType(inv.getMediaType()); msg.setGuestOsType(inv.getGuestOsType()); msg.setFormat(inv.getFormat()); msg.setName(inv.getName()); for (String bsUuid : bsUuids) { msg.getBackupStorageUuids().add(bsUuid); } msg.setUrl(inv.getUrl()); msg.setType(ImageConstant.ZSTACK_IMAGE_TYPE); APIAddImageEvent e = sender.send(msg, APIAddImageEvent.class); return e.getInventory(); } public void deleteImage(String uuid, List<String> bsUuids) throws ApiSenderException { deleteImage(uuid, bsUuids, null); } public void deleteImage(String uuid, List<String> bsUuids, SessionInventory session) throws ApiSenderException { ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIDeleteImageMsg msg = new APIDeleteImageMsg(uuid); msg.setBackupStorageUuids(bsUuids); msg.setSession(session == null ? adminSession : session); sender.send(msg, APIDeleteImageEvent.class); } public void deleteImage(String uuid, SessionInventory session) throws ApiSenderException { deleteImage(uuid, null, session); } public void deleteImage(String uuid) throws ApiSenderException { deleteImage(uuid, null, null); } public List<ImageInventory> listImage(List<String> uuids) throws ApiSenderException { return listImage(0, -1, uuids); } public List<ImageInventory> listImage(int offset, int length, List<String> uuids) throws ApiSenderException { APIListImageMsg msg = new APIListImageMsg(uuids); msg.setSession(adminSession); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setOffset(offset); msg.setLength(length); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIListImageReply reply = sender.call(msg, APIListImageReply.class); return reply.getInventories(); } public InstanceOfferingInventory changeInstanceOfferingState(String uuid, InstanceOfferingStateEvent sevt) throws ApiSenderException { return changeInstanceOfferingState(uuid, sevt, null); } public InstanceOfferingInventory changeInstanceOfferingState(String uuid, InstanceOfferingStateEvent sevt, SessionInventory session) throws ApiSenderException { APIChangeInstanceOfferingStateMsg msg = new APIChangeInstanceOfferingStateMsg(); msg.setUuid(uuid); msg.setStateEvent(sevt.toString()); msg.setSession(session == null ? adminSession : session); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIChangeInstanceOfferingStateEvent evt = sender.send(msg, APIChangeInstanceOfferingStateEvent.class); return evt.getInventory(); } public InstanceOfferingInventory addInstanceOffering(InstanceOfferingInventory inv) throws ApiSenderException { return addInstanceOffering(inv, null); } public InstanceOfferingInventory addInstanceOffering(InstanceOfferingInventory inv, SessionInventory session) throws ApiSenderException { ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APICreateInstanceOfferingMsg msg = new APICreateInstanceOfferingMsg(); msg.setSession(session == null ? adminSession : session); msg.setName(inv.getName()); msg.setCpuNum(inv.getCpuNum()); msg.setCpuSpeed(inv.getCpuSpeed()); msg.setMemorySize(inv.getMemorySize()); msg.setDescription(inv.getDescription()); msg.setAllocatorStrategy(inv.getAllocatorStrategy()); APICreateInstanceOfferingEvent e = sender.send(msg, APICreateInstanceOfferingEvent.class); return e.getInventory(); } public List<InstanceOfferingInventory> listInstanceOffering(List<String> uuids) throws ApiSenderException { return listInstanceOffering(0, -1, uuids); } public List<InstanceOfferingInventory> listInstanceOffering(int offset, int length, List<String> uuids) throws ApiSenderException { APIListInstanceOfferingMsg msg = new APIListInstanceOfferingMsg(uuids); msg.setSession(adminSession); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setOffset(offset); msg.setLength(length); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIListInstanceOfferingReply reply = sender.call(msg, APIListInstanceOfferingReply.class); return reply.getInventories(); } public void deleteInstanceOffering(String uuid) throws ApiSenderException { deleteInstanceOffering(uuid, null); } public void deleteInstanceOffering(String uuid, SessionInventory session) throws ApiSenderException { ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIDeleteInstanceOfferingMsg msg = new APIDeleteInstanceOfferingMsg(uuid); msg.setSession(session == null ? adminSession : session); sender.send(msg, APIDeleteInstanceOfferingEvent.class); } public DiskOfferingInventory addDiskOffering(DiskOfferingInventory inv) throws ApiSenderException { ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APICreateDiskOfferingMsg msg = new APICreateDiskOfferingMsg(); msg.setSession(adminSession); msg.setName(inv.getName()); msg.setDiskSize(inv.getDiskSize()); msg.setDescription(inv.getDescription()); APICreateDiskOfferingEvent e = sender.send(msg, APICreateDiskOfferingEvent.class); return e.getInventory(); } public List<DiskOfferingInventory> listDiskOffering(List<String> uuids) throws ApiSenderException { return listDiskOffering(0, -1, uuids); } public List<DiskOfferingInventory> listDiskOffering(int offset, int length, List<String> uuids) throws ApiSenderException { APIListDiskOfferingMsg msg = new APIListDiskOfferingMsg(uuids); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setSession(adminSession); msg.setOffset(offset); msg.setLength(length); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIListDiskOfferingReply reply = sender.call(msg, APIListDiskOfferingReply.class); return reply.getInventories(); } public void deleteDiskOffering(String uuid) throws ApiSenderException { deleteDiskOffering(uuid, null); } public void deleteDiskOffering(String uuid, SessionInventory session) throws ApiSenderException { ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIDeleteDiskOfferingMsg msg = new APIDeleteDiskOfferingMsg(uuid); msg.setSession(session == null ? adminSession : session); sender.send(msg, APIDeleteDiskOfferingEvent.class); } public VolumeInventory createDataVolume(String name, String diskOfferingUuid) throws ApiSenderException { return createDataVolume(name, diskOfferingUuid, null); } public VolumeInventory createDataVolume(String name, String diskOfferingUuid, SessionInventory session) throws ApiSenderException { ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APICreateDataVolumeMsg msg = new APICreateDataVolumeMsg(); msg.setSession(session == null ? adminSession : session); msg.setName(name); msg.setDiskOfferingUuid(diskOfferingUuid); APICreateDataVolumeEvent e = sender.send(msg, APICreateDataVolumeEvent.class); return e.getInventory(); } public VolumeInventory changeVolumeState(String uuid, VolumeStateEvent stateEvent) throws ApiSenderException { return changeVolumeState(uuid, stateEvent, null); } public VolumeInventory changeVolumeState(String uuid, VolumeStateEvent stateEvent, SessionInventory session) throws ApiSenderException { APIChangeVolumeStateMsg msg = new APIChangeVolumeStateMsg(); msg.setSession(session == null ? adminSession : session); msg.setUuid(uuid); msg.setStateEvent(stateEvent.toString()); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIChangeVolumeStateEvent evt = sender.send(msg, APIChangeVolumeStateEvent.class); return evt.getInventory(); } public List<VolumeInventory> listVolume(List<String> uuids) throws ApiSenderException { return listVolume(0, -1, uuids); } public List<VolumeInventory> listVolume(int offset, int length, List<String> uuids) throws ApiSenderException { APIListVolumeMsg msg = new APIListVolumeMsg(uuids); msg.setSession(adminSession); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setOffset(offset); msg.setLength(length); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIListVolumeReply reply = sender.call(msg, APIListVolumeReply.class); return reply.getInventories(); } public void deleteDataVolume(String uuid) throws ApiSenderException { deleteDataVolume(uuid, null); } public void deleteDataVolume(String uuid, SessionInventory session) throws ApiSenderException { ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIDeleteDataVolumeMsg msg = new APIDeleteDataVolumeMsg(); msg.setSession(session == null ? adminSession : session); msg.setUuid(uuid); sender.send(msg, APIDeleteDataVolumeEvent.class); } public GlobalConfigInventory[] listGlobalConfig(Long ids[]) throws ApiSenderException { return listGlobalConfig(0, -1, ids); } public GlobalConfigInventory[] listGlobalConfig(int offset, int length, Long[] ids) throws ApiSenderException { APIListGlobalConfigMsg msg = new APIListGlobalConfigMsg(); List<Long> idArr = new ArrayList<Long>(); if (ids != null) { Collections.addAll(idArr, ids); } msg.setIds(idArr); msg.setSession(adminSession); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setOffset(offset); msg.setLength(length); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIListGlobalConfigReply reply = sender.call(msg, APIListGlobalConfigReply.class); return reply.getInventories(); } public GlobalConfigInventory updateGlobalConfig(GlobalConfigInventory inv) throws ApiSenderException { ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIUpdateGlobalConfigMsg msg = new APIUpdateGlobalConfigMsg(); msg.setSession(adminSession); msg.setCategory(inv.getCategory()); msg.setName(inv.getName()); msg.setValue(inv.getValue()); APIUpdateGlobalConfigEvent e = sender.send(msg, APIUpdateGlobalConfigEvent.class); return e.getInventory(); } public L2NetworkInventory createNoVlanL2Network(String zoneUuid, String iface) throws ApiSenderException { ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APICreateL2NoVlanNetworkMsg msg = new APICreateL2NoVlanNetworkMsg(); msg.setSession(adminSession); msg.setName("TestL2Network"); msg.setDescription("test"); msg.setZoneUuid(zoneUuid); msg.setPhysicalInterface(iface); msg.setType(L2NetworkConstant.L2_NO_VLAN_NETWORK_TYPE); APICreateL2NetworkEvent e = sender.send(msg, APICreateL2NetworkEvent.class); return e.getInventory(); } public List<L2NetworkInventory> listL2Network(List<String> uuids) throws ApiSenderException { return listL2Network(0, -1, uuids); } public List<L2NetworkInventory> listL2Network(int offset, int length, List<String> uuids) throws ApiSenderException { APIListL2NetworkMsg msg = new APIListL2NetworkMsg(uuids); msg.setSession(adminSession); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setOffset(offset); msg.setLength(length); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIListL2NetworkReply reply = sender.call(msg, APIListL2NetworkReply.class); return reply.getInventories(); } public void deleteL2Network(String uuid) throws ApiSenderException { ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIDeleteL2NetworkMsg msg = new APIDeleteL2NetworkMsg(); msg.setSession(adminSession); msg.setUuid(uuid); sender.send(msg, APIDeleteL2NetworkEvent.class); } public L2NetworkInventory attachL2NetworkToCluster(String l2NetworkUuid, String clusterUuid) throws ApiSenderException { ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIAttachL2NetworkToClusterMsg msg = new APIAttachL2NetworkToClusterMsg(); msg.setSession(adminSession); msg.setL2NetworkUuid(l2NetworkUuid); msg.setClusterUuid(clusterUuid); APIAttachL2NetworkToClusterEvent evt = sender.send(msg, APIAttachL2NetworkToClusterEvent.class); return evt.getInventory(); } public void detachL2NetworkFromCluster(String l2NetworkUuid, String clusterUuid) throws ApiSenderException { ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIDetachL2NetworkFromClusterMsg msg = new APIDetachL2NetworkFromClusterMsg(); msg.setSession(adminSession); msg.setL2NetworkUuid(l2NetworkUuid); msg.setClusterUuid(clusterUuid); sender.send(msg, APIDetachL2NetworkFromClusterEvent.class); } public L3NetworkInventory createL3BasicNetwork(String l2NetworkUuid) throws ApiSenderException { return createL3BasicNetwork(l2NetworkUuid, null); } public L3NetworkInventory createL3BasicNetwork(String l2NetworkUuid, SessionInventory session) throws ApiSenderException { APICreateL3NetworkMsg msg = new APICreateL3NetworkMsg(); msg.setSession(session == null ? adminSession : session); msg.setL2NetworkUuid(l2NetworkUuid); msg.setType(L3NetworkConstant.L3_BASIC_NETWORK_TYPE); msg.setName("Test-L3Network"); msg.setDescription("Test"); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APICreateL3NetworkEvent e = sender.send(msg, APICreateL3NetworkEvent.class); return e.getInventory(); } public L3NetworkInventory changeL3NetworkState(String uuid, L3NetworkStateEvent sevnt) throws ApiSenderException { return changeL3NetworkState(uuid, sevnt, null); } public L3NetworkInventory changeL3NetworkState(String uuid, L3NetworkStateEvent sevnt, SessionInventory session) throws ApiSenderException { APIChangeL3NetworkStateMsg msg = new APIChangeL3NetworkStateMsg(); msg.setUuid(uuid); msg.setStateEvent(sevnt.toString()); msg.setSession(session == null ? adminSession : session); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIChangeL3NetworkStateEvent e = sender.send(msg, APIChangeL3NetworkStateEvent.class); return e.getInventory(); } public void deleteL3Network(String uuid) throws ApiSenderException { deleteL3Network(uuid, null); } public void deleteL3Network(String uuid, SessionInventory session) throws ApiSenderException { APIDeleteL3NetworkMsg msg = new APIDeleteL3NetworkMsg(uuid); msg.setSession(session == null ? adminSession : session); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); sender.send(msg, APIDeleteL3NetworkEvent.class); } public List<L3NetworkInventory> listL3Network(List<String> uuids) throws ApiSenderException { return listL3Network(0, -1, uuids); } public List<L3NetworkInventory> listL3Network(int offset, int length, List<String> uuids) throws ApiSenderException { APIListL3NetworkMsg msg = new APIListL3NetworkMsg(uuids); msg.setSession(adminSession); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setOffset(offset); msg.setLength(length); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIListL3NetworkReply reply = sender.call(msg, APIListL3NetworkReply.class); return reply.getInventories(); } public APIGetIpAddressCapacityReply getIpAddressCapacity(List<String> iprUuids, List<String> l3Uuids, List<String> zoneUuids) throws ApiSenderException { APIGetIpAddressCapacityMsg msg = new APIGetIpAddressCapacityMsg(); msg.setSession(adminSession); msg.setIpRangeUuids(iprUuids); msg.setL3NetworkUuids(l3Uuids); msg.setZoneUuids(zoneUuids); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); return sender.call(msg, APIGetIpAddressCapacityReply.class); } public APIGetIpAddressCapacityReply getIpAddressCapacityByAll() throws ApiSenderException { return getIpAddressCapacityByAll(null); } public APIGetIpAddressCapacityReply getIpAddressCapacityByAll(SessionInventory session) throws ApiSenderException { APIGetIpAddressCapacityMsg msg = new APIGetIpAddressCapacityMsg(); msg.setSession(session == null ? adminSession : session); msg.setAll(true); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); return sender.call(msg, APIGetIpAddressCapacityReply.class); } public IpRangeInventory addIpRangeByCidr(String l3NetworkUuid, String cidr) throws ApiSenderException { return addIpRangeByCidr(l3NetworkUuid, cidr, null); } public IpRangeInventory addIpRangeByCidr(String l3NetworkUuid, String cidr, SessionInventory session) throws ApiSenderException { APIAddIpRangeByNetworkCidrMsg msg = new APIAddIpRangeByNetworkCidrMsg(); msg.setSession(session == null ? adminSession : session); msg.setL3NetworkUuid(l3NetworkUuid); msg.setNetworkCidr(cidr); msg.setName("TestIpRange"); msg.setDescription("test"); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIAddIpRangeByNetworkCidrEvent e = sender.send(msg, APIAddIpRangeByNetworkCidrEvent.class); return e.getInventory(); } public IpRangeInventory addIpRange(String l3NetworkUuid, String startIp, String endIp, String gateway, String netmask) throws ApiSenderException { return addIpRange(l3NetworkUuid, startIp, endIp, gateway, netmask, null); } public IpRangeInventory addIpRange(String l3NetworkUuid, String startIp, String endIp, String gateway, String netmask, SessionInventory session) throws ApiSenderException { APIAddIpRangeMsg msg = new APIAddIpRangeMsg(); msg.setSession(session == null ? adminSession : session); msg.setL3NetworkUuid(l3NetworkUuid); msg.setStartIp(startIp); msg.setEndIp(endIp); msg.setNetmask(netmask); msg.setGateway(gateway); msg.setName("TestIpRange"); msg.setDescription("test"); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIAddIpRangeEvent e = sender.send(msg, APIAddIpRangeEvent.class); return e.getInventory(); } public List<FreeIpInventory> getFreeIp(String l3Uuid, String ipRangeUuid) throws ApiSenderException { return getFreeIp(l3Uuid, ipRangeUuid, 100); } public List<FreeIpInventory> getFreeIp(String l3Uuid, String ipRangeUuid, int limit) throws ApiSenderException { return getFreeIp(l3Uuid, ipRangeUuid, limit, null); } public boolean checkIpAvailability(String l3Uuid, String ip) throws ApiSenderException { return checkIpAvailability(l3Uuid, ip, null); } public boolean checkIpAvailability(String l3Uuid, String ip, SessionInventory session) throws ApiSenderException { APICheckIpAvailabilityMsg msg = new APICheckIpAvailabilityMsg(); msg.setL3NetworkUuid(l3Uuid); msg.setIp(ip); msg.setSession(session == null ? adminSession : session); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APICheckIpAvailabilityReply rely = sender.call(msg, APICheckIpAvailabilityReply.class); return rely.isAvailable(); } public List<FreeIpInventory> getFreeIp(String l3Uuid, String ipRangeUuid, int limit, SessionInventory session) throws ApiSenderException { APIGetFreeIpMsg msg = new APIGetFreeIpMsg(); msg.setSession(session == null ? adminSession : session); msg.setL3NetworkUuid(l3Uuid); msg.setIpRangeUuid(ipRangeUuid); msg.setLimit(limit); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIGetFreeIpReply reply = sender.call(msg, APIGetFreeIpReply.class); return reply.getInventories(); } public List<IpRangeInventory> listIpRange(List<String> uuids) throws ApiSenderException { return listIpRange(0, -1, uuids); } public List<IpRangeInventory> listIpRange(int offset, int length, List<String> uuids) throws ApiSenderException { APIListIpRangeMsg msg = new APIListIpRangeMsg(uuids); msg.setSession(adminSession); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setOffset(offset); msg.setLength(length); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIListIpRangeReply reply = sender.call(msg, APIListIpRangeReply.class); return reply.getInventories(); } public void deleteIpRange(String uuid) throws ApiSenderException { deleteIpRange(uuid, null); } public void deleteIpRange(String uuid, SessionInventory session) throws ApiSenderException { APIDeleteIpRangeMsg msg = new APIDeleteIpRangeMsg(uuid); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); msg.setSession(session == null ? adminSession : session); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); sender.send(msg, APIDeleteIpRangeEvent.class); } public L3NetworkInventory removeDnsFromL3Network(String dns, String l3NetworkUuid) throws ApiSenderException { return removeDnsFromL3Network(dns, l3NetworkUuid, null); } public L3NetworkInventory removeDnsFromL3Network(String dns, String l3NetworkUuid, SessionInventory session) throws ApiSenderException { APIRemoveDnsFromL3NetworkMsg msg = new APIRemoveDnsFromL3NetworkMsg(); msg.setSession(session == null ? adminSession : session); msg.setDns(dns); msg.setL3NetworkUuid(l3NetworkUuid); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIRemoveDnsFromL3NetworkEvent evt = sender.send(msg, APIRemoveDnsFromL3NetworkEvent.class); return evt.getInventory(); } public ZoneInventory createZoneByFullConfig(ZoneInventory inv) throws ApiSenderException { APICreateZoneMsg msg = new APICreateZoneMsg(); msg.setSession(adminSession); msg.setName(inv.getName()); msg.setDescription(inv.getDescription()); msg.setType(inv.getType()); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APICreateZoneEvent evt = sender.send(msg, APICreateZoneEvent.class); return evt.getInventory(); } public ClusterInventory createClusterByFullConfig(ClusterInventory inv) throws ApiSenderException { APICreateClusterMsg msg = new APICreateClusterMsg(); msg.setSession(adminSession); msg.setClusterName(inv.getName()); msg.setDescription(inv.getDescription()); msg.setHypervisorType(inv.getHypervisorType()); msg.setType(inv.getType()); msg.setZoneUuid(inv.getZoneUuid()); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APICreateClusterEvent evt = sender.send(msg, APICreateClusterEvent.class); return evt.getInventory(); } public HostInventory addHostByFullConfig(HostInventory inv) throws ApiSenderException { APIAddSimulatorHostMsg msg = new APIAddSimulatorHostMsg(); msg.setSession(adminSession); msg.setClusterUuid(inv.getClusterUuid()); msg.setDescription(inv.getDescription()); msg.setName(inv.getName()); msg.setManagementIp(inv.getManagementIp()); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setMemoryCapacity(inv.getAvailableMemoryCapacity()); msg.setCpuCapacity(inv.getAvailableCpuCapacity()); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIAddHostEvent evt = sender.send(msg, APIAddHostEvent.class); return evt.getInventory(); } public APIGetPrimaryStorageCapacityReply getPrimaryStorageCapacityByAll() throws ApiSenderException { APIGetPrimaryStorageCapacityMsg msg = new APIGetPrimaryStorageCapacityMsg(); msg.setSession(adminSession); msg.setAll(true); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); return sender.call(msg, APIGetPrimaryStorageCapacityReply.class); } public APIGetPrimaryStorageCapacityReply getPrimaryStorageCapacity(List<String> zoneUuids, List<String> clusterUuids, List<String> psUuids) throws ApiSenderException { APIGetPrimaryStorageCapacityMsg msg = new APIGetPrimaryStorageCapacityMsg(); msg.setSession(adminSession); msg.setZoneUuids(zoneUuids); msg.setClusterUuids(clusterUuids); msg.setPrimaryStorageUuids(psUuids); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); return sender.call(msg, APIGetPrimaryStorageCapacityReply.class); } public PrimaryStorageInventory addPrimaryStorageByFullConfig(PrimaryStorageInventory inv) throws ApiSenderException { APIAddSimulatorPrimaryStorageMsg msg = new APIAddSimulatorPrimaryStorageMsg(); msg.setSession(adminSession); msg.setName(inv.getName()); msg.setDescription(inv.getDescription()); msg.setType(inv.getType()); msg.setUrl(inv.getUrl()); msg.setTotalCapacity(inv.getTotalCapacity()); msg.setAvailableCapacity(inv.getAvailableCapacity()); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setType(SimulatorPrimaryStorageConstant.SIMULATOR_PRIMARY_STORAGE_TYPE); msg.setZoneUuid(inv.getZoneUuid()); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIAddPrimaryStorageEvent evt = sender.send(msg, APIAddPrimaryStorageEvent.class); return evt.getInventory(); } public APIGetBackupStorageCapacityReply getBackupStorageCapacityByAll() throws ApiSenderException { APIGetBackupStorageCapacityMsg msg = new APIGetBackupStorageCapacityMsg(); msg.setSession(adminSession); msg.setAll(true); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); return sender.call(msg, APIGetBackupStorageCapacityReply.class); } public APIGetBackupStorageCapacityReply getBackupStorageCapacity(List<String> zoneUuids, List<String> bsUuids) throws ApiSenderException { APIGetBackupStorageCapacityMsg msg = new APIGetBackupStorageCapacityMsg(); msg.setSession(adminSession); msg.setBackupStorageUuids(bsUuids); msg.setZoneUuids(zoneUuids); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); return sender.call(msg, APIGetBackupStorageCapacityReply.class); } public BackupStorageInventory addBackupStorageByFullConfig(BackupStorageInventory inv) throws ApiSenderException { APIAddSimulatorBackupStorageMsg msg = new APIAddSimulatorBackupStorageMsg(); msg.setSession(adminSession); msg.setName(inv.getName()); msg.setDescription(inv.getDescription()); msg.setTotalCapacity(inv.getTotalCapacity()); msg.setUrl(inv.getUrl()); msg.setAvailableCapacity(inv.getAvailableCapacity()); msg.setType(SimulatorBackupStorageConstant.SIMULATOR_BACKUP_STORAGE_TYPE); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIAddBackupStorageEvent evt = sender.send(msg, APIAddBackupStorageEvent.class); return evt.getInventory(); } public ImageInventory addImageByFullConfig(ImageInventory inv, String bsUuid) throws ApiSenderException { return addImageByFullConfig(inv, bsUuid, null); } public ImageInventory addImageByFullConfig(ImageInventory inv, String bsUuid, SessionInventory session) throws ApiSenderException { APIAddImageMsg msg = new APIAddImageMsg(); msg.setSession(session == null ? adminSession : session); msg.getBackupStorageUuids().add(bsUuid); msg.setDescription(inv.getDescription()); msg.setMediaType(inv.getMediaType()); msg.setGuestOsType(inv.getGuestOsType()); msg.setFormat(inv.getFormat()); msg.setPlatform(inv.getPlatform()); msg.setType(inv.getType()); msg.setName(inv.getName()); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setUrl(inv.getUrl()); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIAddImageEvent evt = sender.send(msg, APIAddImageEvent.class); return evt.getInventory(); } public L2VlanNetworkInventory createL2VlanNetworkByFullConfig(L2VlanNetworkInventory inv) throws ApiSenderException { APICreateL2VlanNetworkMsg msg = new APICreateL2VlanNetworkMsg(); msg.setSession(adminSession); msg.setDescription(inv.getDescription()); msg.setName(inv.getName()); msg.setPhysicalInterface(inv.getPhysicalInterface()); msg.setType(inv.getType()); msg.setZoneUuid(inv.getZoneUuid()); msg.setVlan(inv.getVlan()); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APICreateL2NetworkEvent evt = sender.send(msg, APICreateL2NetworkEvent.class); return (L2VlanNetworkInventory) evt.getInventory(); } public L2NetworkInventory createL2NetworkByFullConfig(L2NetworkInventory inv) throws ApiSenderException { APICreateL2NoVlanNetworkMsg msg = new APICreateL2NoVlanNetworkMsg(); msg.setSession(adminSession); msg.setDescription(inv.getDescription()); msg.setName(inv.getName()); msg.setPhysicalInterface(inv.getPhysicalInterface()); msg.setType(inv.getType()); msg.setZoneUuid(inv.getZoneUuid()); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APICreateL2NetworkEvent evt = sender.send(msg, APICreateL2NetworkEvent.class); return evt.getInventory(); } public L3NetworkInventory createL3NetworkByFullConfig(L3NetworkInventory inv) throws ApiSenderException { return createL3NetworkByFullConfig(inv, adminSession); } public L3NetworkInventory createL3NetworkByFullConfig(L3NetworkInventory inv, SessionInventory session) throws ApiSenderException { APICreateL3NetworkMsg msg = new APICreateL3NetworkMsg(); msg.setSession(session); msg.setDescription(inv.getDescription()); msg.setL2NetworkUuid(inv.getL2NetworkUuid()); msg.setName(inv.getName()); msg.setDnsDomain(inv.getDnsDomain()); msg.setType(inv.getType()); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APICreateL3NetworkEvent evt = sender.send(msg, APICreateL3NetworkEvent.class); return evt.getInventory(); } public IpRangeInventory addIpRangeByFullConfig(IpRangeInventory inv, SessionInventory session) throws ApiSenderException { APIAddIpRangeMsg msg = new APIAddIpRangeMsg(); msg.setSession(session); msg.setL3NetworkUuid(inv.getL3NetworkUuid()); msg.setStartIp(inv.getStartIp()); msg.setEndIp(inv.getEndIp()); msg.setNetmask(inv.getNetmask()); msg.setGateway(inv.getGateway()); msg.setName(inv.getName()); msg.setDescription(inv.getDescription()); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIAddIpRangeEvent e = sender.send(msg, APIAddIpRangeEvent.class); return e.getInventory(); } public IpRangeInventory addIpRangeByFullConfig(IpRangeInventory inv) throws ApiSenderException { return addIpRangeByFullConfig(inv, adminSession); } public DiskOfferingInventory addDiskOfferingByFullConfig(DiskOfferingInventory inv) throws ApiSenderException { return addDiskOfferingByFullConfig(inv, null); } public DiskOfferingInventory addDiskOfferingByFullConfig(DiskOfferingInventory inv, SessionInventory session) throws ApiSenderException { ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APICreateDiskOfferingMsg msg = new APICreateDiskOfferingMsg(); msg.setSession(session == null ? adminSession : session); msg.setName(inv.getName()); msg.setDiskSize(inv.getDiskSize()); msg.setDescription(inv.getDescription()); msg.setAllocationStrategy(inv.getAllocatorStrategy()); APICreateDiskOfferingEvent e = sender.send(msg, APICreateDiskOfferingEvent.class); return e.getInventory(); } public VmInstanceInventory createVmFromClone(VmInstanceInventory toClone) throws ApiSenderException { APICreateVmInstanceMsg msg = new APICreateVmInstanceMsg(); msg.setSession(adminSession); msg.setName(String.format("clone-%s", toClone.getName())); msg.setImageUuid(toClone.getImageUuid()); msg.setDataDiskOfferingUuids(CollectionUtils.transformToList(toClone.getAllVolumes(), new Function<String, VolumeInventory>() { @Override public String call(VolumeInventory arg) { if (!arg.getType().equals(VolumeType.Root.toString())) { return arg.getDiskOfferingUuid(); } return null; } })); msg.setL3NetworkUuids(CollectionUtils.transformToList(toClone.getVmNics(), new Function<String, VmNicInventory>() { @Override public String call(VmNicInventory arg) { return arg.getL3NetworkUuid(); } })); msg.setDefaultL3NetworkUuid(toClone.getDefaultL3NetworkUuid()); msg.setType(toClone.getType()); msg.setInstanceOfferingUuid(toClone.getInstanceOfferingUuid()); msg.setDescription(String.format("clone from vm[uuid:%s]", toClone.getUuid())); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APICreateVmInstanceEvent evt = sender.send(msg, APICreateVmInstanceEvent.class); return evt.getInventory(); } public VmInstanceInventory createVmByFullConfig(VmInstanceInventory inv, String rootDiskOfferingUuid, List<String> l3NetworkUuids, List<String> diskOfferingUuids, SessionInventory session) throws ApiSenderException { APICreateVmInstanceMsg msg = new APICreateVmInstanceMsg(); msg.setClusterUuid(inv.getClusterUuid()); if (diskOfferingUuids != null) { msg.setDataDiskOfferingUuids(diskOfferingUuids); } msg.setSession(session); msg.setDescription(inv.getDescription()); msg.setHostUuid(inv.getHostUuid()); msg.setImageUuid(inv.getImageUuid()); msg.setInstanceOfferingUuid(inv.getInstanceOfferingUuid()); msg.setL3NetworkUuids(l3NetworkUuids); msg.setName(inv.getName()); msg.setType(inv.getType()); msg.setZoneUuid(inv.getZoneUuid()); msg.setHostUuid(inv.getHostUuid()); msg.setClusterUuid(inv.getClusterUuid()); msg.setRootDiskOfferingUuid(rootDiskOfferingUuid); msg.setDefaultL3NetworkUuid(inv.getDefaultL3NetworkUuid()); if (msg.getL3NetworkUuids().size() > 1 && msg.getDefaultL3NetworkUuid() == null) { msg.setDefaultL3NetworkUuid(msg.getL3NetworkUuids().get(0)); } ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APICreateVmInstanceEvent evt = sender.send(msg, APICreateVmInstanceEvent.class); return evt.getInventory(); } public VmInstanceInventory changeInstanceOffering(String vmUuid, String instanceOfferingUuid) throws ApiSenderException { APIChangeInstanceOfferingMsg msg = new APIChangeInstanceOfferingMsg(); msg.setVmInstanceUuid(vmUuid); msg.setInstanceOfferingUuid(instanceOfferingUuid); msg.setSession(adminSession); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIChangeInstanceOfferingEvent evt = sender.send(msg, APIChangeInstanceOfferingEvent.class); return evt.getInventory(); } public VmInstanceInventory createVmByFullConfig(VmInstanceInventory inv, String rootDiskOfferingUuid, List<String> l3NetworkUuids, List<String> diskOfferingUuids) throws ApiSenderException { return createVmByFullConfig(inv, rootDiskOfferingUuid, l3NetworkUuids, diskOfferingUuids, adminSession); } public List<VmInstanceInventory> listVmInstances(List<String> uuids) throws ApiSenderException { APIListVmInstanceMsg msg = new APIListVmInstanceMsg(uuids); msg.setSession(adminSession); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIListVmInstanceReply reply = sender.call(msg, APIListVmInstanceReply.class); return reply.getInventories(); } public VmInstanceInventory stopVmInstance(String uuid) throws ApiSenderException { return stopVmInstance(uuid, null); } public VmInstanceInventory stopVmInstance(String uuid, SessionInventory session) throws ApiSenderException { APIStopVmInstanceMsg msg = new APIStopVmInstanceMsg(); msg.setSession(session == null ? adminSession : session); msg.setUuid(uuid); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIStopVmInstanceEvent evt = sender.send(msg, APIStopVmInstanceEvent.class); return evt.getInventory(); } public VmInstanceInventory rebootVmInstance(String uuid) throws ApiSenderException { return rebootVmInstance(uuid, null); } public VmInstanceInventory rebootVmInstance(String uuid, SessionInventory session) throws ApiSenderException { APIRebootVmInstanceMsg msg = new APIRebootVmInstanceMsg(); msg.setSession(session == null ? adminSession : session); msg.setUuid(uuid); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIRebootVmInstanceEvent evt = sender.send(msg, APIRebootVmInstanceEvent.class); return evt.getInventory(); } public void destroyVmInstance(String uuid) throws ApiSenderException { destroyVmInstance(uuid, null); } public void destroyVmInstance(String uuid, SessionInventory session) throws ApiSenderException { APIDestroyVmInstanceMsg msg = new APIDestroyVmInstanceMsg(); msg.setSession(session == null ? adminSession : session); msg.setUuid(uuid); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); sender.send(msg, APIDestroyVmInstanceEvent.class); } public VmInstanceInventory startVmInstance(String uuid) throws ApiSenderException { return startVmInstance(uuid, null); } public VmInstanceInventory startVmInstance(String uuid, SessionInventory session) throws ApiSenderException { APIStartVmInstanceMsg msg = new APIStartVmInstanceMsg(); msg.setSession(session == null ? adminSession : session); msg.setUuid(uuid); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIStartVmInstanceEvent evt = sender.send(msg, APIStartVmInstanceEvent.class); return evt.getInventory(); } public VmInstanceInventory migrateVmInstance(String vmUuid, String destHostUuid) throws ApiSenderException { return migrateVmInstance(vmUuid, destHostUuid, null); } public VmInstanceInventory migrateVmInstance(String vmUuid, String destHostUuid, SessionInventory session) throws ApiSenderException { APIMigrateVmMsg msg = new APIMigrateVmMsg(); msg.setVmUuid(vmUuid); msg.setSession(session == null ? adminSession : session); msg.setHostUuid(destHostUuid); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIMigrateVmEvent evt = sender.send(msg, APIMigrateVmEvent.class); return evt.getInventory(); } public List<VmInstanceInventory> getDataVolumeCandidateVmForAttaching(String volUuid) throws ApiSenderException { return getDataVolumeCandidateVmForAttaching(volUuid, null); } public List<VmInstanceInventory> getDataVolumeCandidateVmForAttaching(String volUuid, SessionInventory session) throws ApiSenderException { APIGetDataVolumeAttachableVmMsg msg = new APIGetDataVolumeAttachableVmMsg(); msg.setVolumeUuid(volUuid); msg.setSession(session == null ? adminSession : session); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIGetDataVolumeAttachableVmReply reply = sender.call(msg, APIGetDataVolumeAttachableVmReply.class); return reply.getInventories(); } public List<VolumeInventory> getVmAttachableVolume(String vmUuid) throws ApiSenderException { return getVmAttachableVolume(vmUuid, null); } public List<VolumeInventory> getVmAttachableVolume(String vmUuid, SessionInventory session) throws ApiSenderException { APIGetVmAttachableDataVolumeMsg msg = new APIGetVmAttachableDataVolumeMsg(); msg.setVmInstanceUuid(vmUuid); msg.setSession(session == null ? adminSession : session); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIGetVmAttachableDataVolumeReply reply = sender.call(msg, APIGetVmAttachableDataVolumeReply.class); return reply.getInventories(); } public VolumeInventory attachVolumeToVm(String vmUuid, String volumeUuid) throws ApiSenderException { return attachVolumeToVm(vmUuid, volumeUuid, null); } public VolumeInventory attachVolumeToVm(String vmUuid, String volumeUuid, SessionInventory session) throws ApiSenderException { APIAttachDataVolumeToVmMsg msg = new APIAttachDataVolumeToVmMsg(); msg.setSession(session == null ? adminSession : session); msg.setVmUuid(vmUuid); msg.setVolumeUuid(volumeUuid); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIAttachDataVolumeToVmEvent evt = sender.send(msg, APIAttachDataVolumeToVmEvent.class); return evt.getInventory(); } public VolumeInventory createDataVolumeFromTemplate(String imageUuid, String primaryStorageUuid) throws ApiSenderException { return createDataVolumeFromTemplate(imageUuid, primaryStorageUuid, null); } public VolumeInventory createDataVolumeFromTemplate(String imageUuid, String primaryStorageUuid, SessionInventory session) throws ApiSenderException { APICreateDataVolumeFromVolumeTemplateMsg msg = new APICreateDataVolumeFromVolumeTemplateMsg(); msg.setPrimaryStorageUuid(primaryStorageUuid); msg.setImageUuid(imageUuid); msg.setSession(session == null ? adminSession : session); msg.setName("data"); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APICreateDataVolumeFromVolumeTemplateEvent evt = sender.send(msg, APICreateDataVolumeFromVolumeTemplateEvent.class); return evt.getInventory(); } public ImageInventory addDataVolumeTemplateFromDataVolume(String volUuid, List<String> bsUuids) throws ApiSenderException { return addDataVolumeTemplateFromDataVolume(volUuid, bsUuids, null); } public ImageInventory addDataVolumeTemplateFromDataVolume(String volUuid, List<String> bsUuids, SessionInventory session) throws ApiSenderException { APICreateDataVolumeTemplateFromVolumeMsg msg = new APICreateDataVolumeTemplateFromVolumeMsg(); msg.setName("data-vol"); msg.setVolumeUuid(volUuid); msg.setSession(session == null ? adminSession : session); msg.setBackupStorageUuids(bsUuids); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APICreateDataVolumeTemplateFromVolumeEvent evt = sender.send(msg, APICreateDataVolumeTemplateFromVolumeEvent.class); return evt.getInventory(); } public List<VolumeFormatReplyStruct> getVolumeFormats() throws ApiSenderException { APIGetVolumeFormatMsg msg = new APIGetVolumeFormatMsg(); msg.setSession(adminSession); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIGetVolumeFormatReply reply = sender.call(msg, APIGetVolumeFormatReply.class); return reply.getFormats(); } public VolumeInventory detachVolumeFromVm(String volumeUuid) throws ApiSenderException { return detachVolumeFromVm(volumeUuid, null); } public VolumeInventory detachVolumeFromVm(String volumeUuid, SessionInventory session) throws ApiSenderException { APIDetachDataVolumeFromVmMsg msg = new APIDetachDataVolumeFromVmMsg(); msg.setSession(session == null ? adminSession : session); msg.setUuid(volumeUuid); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIDetachDataVolumeFromVmEvent evt = sender.send(msg, APIDetachDataVolumeFromVmEvent.class); return evt.getInventory(); } public SessionInventory loginAsAdmin() throws ApiSenderException { return loginByAccount(AccountConstant.INITIAL_SYSTEM_ADMIN_NAME, AccountConstant.INITIAL_SYSTEM_ADMIN_PASSWORD); } public SessionInventory loginByAccount(String accountName, String password) throws ApiSenderException { APILogInByAccountMsg msg = new APILogInByAccountMsg(); msg.setAccountName(accountName); msg.setPassword(password); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APILogInReply reply = sender.call(msg, APILogInReply.class); return reply.getInventory(); } public SessionInventory loginByUserAccountName(String userName, String password, String accountName) throws ApiSenderException { APILogInByUserMsg msg = new APILogInByUserMsg(); msg.setAccountName(accountName); msg.setUserName(userName); msg.setPassword(password); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APILogInReply reply = sender.call(msg, APILogInReply.class); return reply.getInventory(); } public SessionInventory loginByUser(String userName, String password, String accountUuid) throws ApiSenderException { APILogInByUserMsg msg = new APILogInByUserMsg(); msg.setAccountUuid(accountUuid); msg.setUserName(userName); msg.setPassword(password); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APILogInReply reply = sender.call(msg, APILogInReply.class); return reply.getInventory(); } public void logout(String sessionUuid) throws ApiSenderException { APILogOutMsg msg = new APILogOutMsg(); msg.setSessionUuid(sessionUuid); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); sender.call(msg, APILogOutReply.class); } public boolean validateSession(String sessionUuid) throws ApiSenderException { APIValidateSessionMsg msg = new APIValidateSessionMsg(); msg.setSessionUuid(sessionUuid); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIValidateSessionReply reply = sender.call(msg, APIValidateSessionReply.class); return reply.isValidSession(); } public AccountInventory createAccount(String name, String password) throws ApiSenderException { APICreateAccountMsg msg = new APICreateAccountMsg(); msg.setSession(adminSession); msg.setName(name); msg.setPassword(password); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APICreateAccountEvent evt = sender.send(msg, APICreateAccountEvent.class); return evt.getInventory(); } public QuotaInventory updateQuota(String identityUuid, String name, long value) throws ApiSenderException { APIUpdateQuotaMsg msg = new APIUpdateQuotaMsg(); msg.setIdentityUuid(identityUuid); msg.setName(name); msg.setValue(value); msg.setSession(adminSession); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIUpdateQuotaEvent evt = sender.send(msg, APIUpdateQuotaEvent.class); return evt.getInventory(); } public QuotaInventory getQuota(String name, String accountUuid, SessionInventory session) throws ApiSenderException { APIQueryQuotaMsg msg = new APIQueryQuotaMsg(); msg.addQueryCondition("name", QueryOp.EQ, name); msg.addQueryCondition("identityUuid", QueryOp.EQ, accountUuid); msg.setSession(session == null ? adminSession : session); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIQueryQuotaReply r = sender.call(msg, APIQueryQuotaReply.class); return r.getInventories().isEmpty() ? null : r.getInventories().get(0); } public List<Quota.QuotaUsage> getQuotaUsage(String accountUuid, SessionInventory session) throws ApiSenderException { APIGetAccountQuotaUsageMsg msg = new APIGetAccountQuotaUsageMsg(); if (accountUuid != null) { msg.setUuid(accountUuid); msg.setSession(adminSession); } else { msg.setUuid(session.getAccountUuid()); msg.setSession(session); } ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIGetAccountQuotaUsageReply reply = sender.call(msg, APIGetAccountQuotaUsageReply.class); return reply.getUsages(); } public List<ManagementNodeInventory> listManagementNodes() throws ApiSenderException { APIListManagementNodeMsg msg = new APIListManagementNodeMsg(); msg.setSession(adminSession); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIListManagementNodeReply reply = sender.call(msg, APIListManagementNodeReply.class); return reply.getInventories(); } public List<AccountInventory> listAccount(List<String> uuids) throws ApiSenderException { APIListAccountMsg msg = new APIListAccountMsg(uuids); msg.setSession(adminSession); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIListAccountReply reply = sender.call(msg, APIListAccountReply.class); return reply.getInventories(); } public AccountInventory resetAccountPassword(String uuid, String password, SessionInventory session) throws ApiSenderException { APIUpdateAccountMsg msg = new APIUpdateAccountMsg(); msg.setSession(session); msg.setPassword(password); msg.setUuid(uuid); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIUpdateAccountEvent evt = sender.send(msg, APIUpdateAccountEvent.class); return evt.getInventory(); } public UserInventory createUser(String accountUuid, String userName, String password, SessionInventory session) throws ApiSenderException { APICreateUserMsg msg = new APICreateUserMsg(); msg.setSession(session); msg.setName(userName); msg.setPassword(password); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APICreateUserEvent evt = sender.send(msg, APICreateUserEvent.class); return evt.getInventory(); } public void resetUserPassword(String uuid, String password, SessionInventory session) throws ApiSenderException { APIUpdateUserMsg msg = new APIUpdateUserMsg(); msg.setUuid(uuid); msg.setPassword(password); msg.setSession(session); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); sender.send(msg, APIUpdateUserEvent.class); } public PolicyInventory createPolicy(String name, List<Statement> s, SessionInventory session) throws ApiSenderException { APICreatePolicyMsg msg = new APICreatePolicyMsg(); msg.setSession(session); msg.setName(name); msg.setStatements(s); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APICreatePolicyEvent evt = sender.send(msg, APICreatePolicyEvent.class); return evt.getInventory(); } public void attachPolicyToUser(String userUuid, String policyUuid, SessionInventory session) throws ApiSenderException { APIAttachPolicyToUserMsg msg = new APIAttachPolicyToUserMsg(); msg.setSession(session); msg.setUserUuid(userUuid); msg.setPolicyUuid(policyUuid); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); sender.send(msg, APIAttachPolicyToUserEvent.class); } public void detachPolicyFromUser(String userUuid, String policyUuid, SessionInventory session) throws ApiSenderException { APIDetachPolicyFromUserMsg msg = new APIDetachPolicyFromUserMsg(); msg.setSession(session); msg.setUserUuid(userUuid); msg.setPolicyUuid(policyUuid); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); sender.send(msg, APIDetachPolicyFromUserEvent.class); } public void attachPolicyToUser(String accountUuid, String userUuid, String policyUuid, SessionInventory session) throws ApiSenderException { APIAttachPolicyToUserMsg msg = new APIAttachPolicyToUserMsg(); msg.setSession(session); msg.setUserUuid(userUuid); msg.setPolicyUuid(policyUuid); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); sender.send(msg, APIAttachPolicyToUserEvent.class); } public UserGroupInventory createGroup(String accountUuid, String name, SessionInventory session) throws ApiSenderException { APICreateUserGroupMsg msg = new APICreateUserGroupMsg(); msg.setSession(session); msg.setName(name); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APICreateUserGroupEvent evt = sender.send(msg, APICreateUserGroupEvent.class); return evt.getInventory(); } public void deleteGroup(String uuid, SessionInventory session) throws ApiSenderException { APIDeleteUserGroupMsg msg = new APIDeleteUserGroupMsg(); msg.setSession(session); msg.setUuid(uuid); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); sender.send(msg, APIDeleteUserGroupEvent.class); } public void deleteAccount(String uuid, SessionInventory session) throws ApiSenderException { APIDeleteAccountMsg msg = new APIDeleteAccountMsg(); msg.setSession(session == null ? adminSession : session); msg.setUuid(uuid); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); sender.send(msg, APIDeleteAccountEvent.class); } public void deleteUser(String uuid, SessionInventory session) throws ApiSenderException { APIDeleteUserMsg msg = new APIDeleteUserMsg(); msg.setSession(session); msg.setUuid(uuid); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); sender.send(msg, APIDeleteUserEvent.class); } public void deletePolicy(String uuid, SessionInventory session) throws ApiSenderException { APIDeletePolicyMsg msg = new APIDeletePolicyMsg(); msg.setSession(session); msg.setUuid(uuid); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); sender.send(msg, APIDeletePolicyEvent.class); } public void attachPolicyToGroup(String groupUuid, String policyUuid, SessionInventory session) throws ApiSenderException { APIAttachPolicyToUserGroupMsg msg = new APIAttachPolicyToUserGroupMsg(); msg.setGroupUuid(groupUuid); msg.setPolicyUuid(policyUuid); msg.setSession(session); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); sender.send(msg, APIAttachPolicyToUserGroupEvent.class); } public void detachPolicyFromGroup(String groupUuid, String policyUuid, SessionInventory session) throws ApiSenderException { APIDetachPolicyFromUserGroupMsg msg = new APIDetachPolicyFromUserGroupMsg(); msg.setGroupUuid(groupUuid); msg.setPolicyUuid(policyUuid); msg.setSession(session); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); sender.send(msg, APIDetachPolicyFromUserGroupEvent.class); } public void attachPolicyToGroup(String accountUuid, String groupUuid, String policyUuid, SessionInventory session) throws ApiSenderException { APIAttachPolicyToUserGroupMsg msg = new APIAttachPolicyToUserGroupMsg(); msg.setGroupUuid(groupUuid); msg.setPolicyUuid(policyUuid); msg.setSession(session); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); sender.send(msg, APIAttachPolicyToUserGroupEvent.class); } public void addUserToGroup(String userUuid, String groupUuid, SessionInventory session) throws ApiSenderException { APIAddUserToGroupMsg msg = new APIAddUserToGroupMsg(); msg.setUserUuid(userUuid); msg.setGroupUuid(groupUuid); msg.setSession(session); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); sender.send(msg, APIAddUserToGroupEvent.class); } public void removeUserFromGroup(String userUuid, String groupUuid, SessionInventory session) throws ApiSenderException { APIRemoveUserFromGroupMsg msg = new APIRemoveUserFromGroupMsg(); msg.setUserUuid(userUuid); msg.setGroupUuid(groupUuid); msg.setSession(session); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); sender.send(msg, APIRemoveUserFromGroupEvent.class); } public void attachUserToGroup(String accountUuid, String userUuid, String groupUuid, SessionInventory session) throws ApiSenderException { APIAddUserToGroupMsg msg = new APIAddUserToGroupMsg(); msg.setUserUuid(userUuid); msg.setGroupUuid(groupUuid); msg.setSession(session); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); sender.send(msg, APIAddUserToGroupEvent.class); } public void deleteAllIndex() throws ApiSenderException { APIDeleteSearchIndexMsg msg = new APIDeleteSearchIndexMsg(); msg.setSession(adminSession); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); sender.send(msg, APIDeleteSearchIndexEvent.class); } public void generateInventoryQueryDetails() throws ApiSenderException { APIGenerateInventoryQueryDetailsMsg msg = new APIGenerateInventoryQueryDetailsMsg(); msg.setSession(adminSession); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); sender.send(msg, APIGenerateInventoryQueryDetailsEvent.class); } public void generateSqlTrigger() throws ApiSenderException { APISearchGenerateSqlTriggerMsg msg = new APISearchGenerateSqlTriggerMsg(); msg.setSession(adminSession); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); sender.send(msg, APISearchGenerateSqlTriggerEvent.class); } public String search(APISearchMessage msg) throws ApiSenderException { ApiSender sender = new ApiSender(); if (msg.getSession() == null) { msg.setSession(adminSession); } msg.setServiceId(ApiMediatorConstant.SERVICE_ID); sender.setTimeout(timeout); APISearchReply reply = sender.call(msg, APISearchReply.class); return reply.getContent(); } public <T> T query(APIQueryMessage msg, Class<T> replyClass) throws ApiSenderException { return query(msg, replyClass, adminSession); } public <T> T query(APIQueryMessage msg, Class<T> replyClass, SessionInventory session) throws ApiSenderException { msg.setSession(session); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIReply reply = (APIReply) sender.call(msg, APIReply.class); return (T) reply; } public long queryCount(APIQueryMessage msg, SessionInventory session) throws ApiSenderException { msg.setCount(true); msg.setSession(session); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIQueryReply reply = (APIQueryReply) sender.call(msg, APIReply.class); return reply.getTotal(); } public void generateGroovyClass() throws ApiSenderException { APIGenerateGroovyClassMsg msg = new APIGenerateGroovyClassMsg(); msg.setSession(adminSession); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); sender.send(msg, APIGenerateGroovyClassEvent.class); } public void generateSqlForeignKey() throws ApiSenderException { APIGenerateSqlForeignKeyMsg msg = new APIGenerateSqlForeignKeyMsg(); msg.setSession(adminSession); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); sender.send(msg, APIGenerateSqlForeignKeyEvent.class); } public void generateSqlIndex() throws ApiSenderException { APIGenerateSqlIndexMsg msg = new APIGenerateSqlIndexMsg(); msg.setSession(adminSession); ApiSender sender = new ApiSender(); sender.send(msg, APIGenerateSqlIndexEvent.class); } public void generateQueryableFields() throws ApiSenderException { APIGenerateQueryableFieldsMsg msg = new APIGenerateQueryableFieldsMsg(); msg.setSession(adminSession); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); sender.send(msg, APIGenerateQueryableFieldsEvent.class); } public void generateApiJsonTemplate() throws ApiSenderException { APIGenerateApiJsonTemplateMsg msg = new APIGenerateApiJsonTemplateMsg(); msg.setSession(adminSession); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); sender.send(msg, APIGenerateApiJsonTemplateEvent.class); } public void generateTestLinkDocument() throws ApiSenderException { APIGenerateTestLinkDocumentMsg msg = new APIGenerateTestLinkDocumentMsg(); msg.setSession(adminSession); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); sender.send(msg, APIGenerateTestLinkDocumentEvent.class); } public L3NetworkInventory attachNetworkServiceToL3Network(String l3NetworkUuid, String providerUuid, List<String> types) throws ApiSenderException { return attachNetworkServiceToL3Network(l3NetworkUuid, providerUuid, types, null); } public L3NetworkInventory attachNetworkServiceToL3Network(String l3NetworkUuid, String providerUuid, List<String> types, SessionInventory session) throws ApiSenderException { APIAttachNetworkServiceToL3NetworkMsg msg = new APIAttachNetworkServiceToL3NetworkMsg(); Map<String, List<String>> ntypes = new HashMap<String, List<String>>(1); ntypes.put(providerUuid, types); msg.setL3NetworkUuid(l3NetworkUuid); msg.setNetworkServices(ntypes); msg.setSession(session == null ? adminSession : session); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIAttachNetworkServiceToL3NetworkEvent evt = sender.send(msg, APIAttachNetworkServiceToL3NetworkEvent.class); return evt.getInventory(); } public List<NetworkServiceProviderInventory> listNetworkServiceProvider(List<String> uuids) throws ApiSenderException { APIListNetworkServiceProviderMsg msg = new APIListNetworkServiceProviderMsg(); msg.setSession(adminSession); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIListNetworkServiceProviderReply reply = sender.call(msg, APIListNetworkServiceProviderReply.class); return reply.getInventories(); } public L3NetworkInventory addDns(String l3NetworkUuid, String dns) throws ApiSenderException { return addDns(l3NetworkUuid, dns, null); } public L3NetworkInventory addDns(String l3NetworkUuid, String dns, SessionInventory session) throws ApiSenderException { APIAddDnsToL3NetworkMsg msg = new APIAddDnsToL3NetworkMsg(); msg.setL3NetworkUuid(l3NetworkUuid); msg.setDns(dns); msg.setSession(session == null ? adminSession : session); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIAddDnsToL3NetworkEvent evt = sender.send(msg, APIAddDnsToL3NetworkEvent.class); return evt.getInventory(); } public String getInventory(APIGetMessage msg) throws ApiSenderException { msg.setSession(adminSession); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIGetReply reply = sender.call(msg, APIGetReply.class); return reply.getInventory(); } public APIGetCpuMemoryCapacityReply retrieveHostCapacityByAll() throws ApiSenderException { APIGetCpuMemoryCapacityMsg msg = new APIGetCpuMemoryCapacityMsg(); msg.setSession(adminSession); msg.setAll(true); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); return sender.call(msg, APIGetCpuMemoryCapacityReply.class); } public APIGetCpuMemoryCapacityReply retrieveHostCapacity(List<String> zoneUuids, List<String> clusterUuids, List<String> hostUuids) throws ApiSenderException { APIGetCpuMemoryCapacityMsg msg = new APIGetCpuMemoryCapacityMsg(); msg.setSession(adminSession); msg.setHostUuids(hostUuids); msg.setClusterUuids(clusterUuids); msg.setZoneUuids(zoneUuids); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); return sender.call(msg, APIGetCpuMemoryCapacityReply.class); } public SecurityGroupInventory createSecurityGroup(String name) throws ApiSenderException { return createSecurityGroup(name, null); } public SecurityGroupInventory createSecurityGroup(String name, SessionInventory session) throws ApiSenderException { APICreateSecurityGroupMsg msg = new APICreateSecurityGroupMsg(); msg.setName(name); msg.setSession(session == null ? adminSession : session); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APICreateSecurityGroupEvent evt = sender.send(msg, APICreateSecurityGroupEvent.class); return evt.getInventory(); } public SecurityGroupInventory changeSecurityGroupState(String uuid, SecurityGroupStateEvent sevt) throws ApiSenderException { return changeSecurityGroupState(uuid, sevt, null); } public SecurityGroupInventory changeSecurityGroupState(String uuid, SecurityGroupStateEvent sevt, SessionInventory session) throws ApiSenderException { APIChangeSecurityGroupStateMsg msg = new APIChangeSecurityGroupStateMsg(); msg.setStateEvent(sevt.toString()); msg.setUuid(uuid); msg.setSession(session == null ? adminSession : session); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIChangeSecurityGroupStateEvent evt = sender.send(msg, APIChangeSecurityGroupStateEvent.class); return evt.getInventory(); } public SecurityGroupInventory createSecurityGroupByFullConfig(SecurityGroupInventory inv, SessionInventory session) throws ApiSenderException { APICreateSecurityGroupMsg msg = new APICreateSecurityGroupMsg(); msg.setName(inv.getName()); msg.setDescription(inv.getDescription()); msg.setSession(session); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APICreateSecurityGroupEvent evt = sender.send(msg, APICreateSecurityGroupEvent.class); return evt.getInventory(); } public SecurityGroupInventory createSecurityGroupByFullConfig(SecurityGroupInventory inv) throws ApiSenderException { return createSecurityGroupByFullConfig(inv, adminSession); } public SecurityGroupInventory addSecurityGroupRuleByFullConfig(String securityGroupUuid, SecurityGroupRuleAO ao) throws ApiSenderException { List<SecurityGroupRuleAO> aos = new ArrayList<SecurityGroupRuleAO>(1); aos.add(ao); return addSecurityGroupRuleByFullConfig(securityGroupUuid, aos); } public SecurityGroupInventory addSecurityGroupRuleByFullConfig(String securityGroupUuid, List<SecurityGroupRuleAO> aos) throws ApiSenderException { return addSecurityGroupRuleByFullConfig(securityGroupUuid, aos, adminSession); } public List<VmNicInventory> getCandidateVmNicFromSecurityGroup(String sgUuid) throws ApiSenderException { return getCandidateVmNicFromSecurityGroup(sgUuid, null); } public List<VmNicInventory> getCandidateVmNicFromSecurityGroup(String sgUuid, SessionInventory session) throws ApiSenderException { APIGetCandidateVmNicForSecurityGroupMsg msg = new APIGetCandidateVmNicForSecurityGroupMsg(); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setSecurityGroupUuid(sgUuid); msg.setSession(session == null ? adminSession : session); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIGetCandidateVmNicForSecurityGroupReply reply = sender.call(msg, APIGetCandidateVmNicForSecurityGroupReply.class); return reply.getInventories(); } public SecurityGroupInventory addSecurityGroupRuleByFullConfig(String securityGroupUuid, List<SecurityGroupRuleAO> aos, SessionInventory session) throws ApiSenderException { APIAddSecurityGroupRuleMsg msg = new APIAddSecurityGroupRuleMsg(); msg.setRules(aos); msg.setSecurityGroupUuid(securityGroupUuid); msg.setSession(session); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIAddSecurityGroupRuleEvent evt = sender.send(msg, APIAddSecurityGroupRuleEvent.class); return evt.getInventory(); } public SecurityGroupInventory removeSecurityGroupRule(String ruleUuid) throws ApiSenderException { List<String> ruleUuids = new ArrayList<String>(); ruleUuids.add(ruleUuid); return removeSecurityGroupRule(ruleUuids); } public SecurityGroupInventory removeSecurityGroupRule(List<String> ruleUuids) throws ApiSenderException { return removeSecurityGroupRule(ruleUuids, null); } public SecurityGroupInventory removeSecurityGroupRule(List<String> ruleUuids, SessionInventory session) throws ApiSenderException { APIDeleteSecurityGroupRuleMsg msg = new APIDeleteSecurityGroupRuleMsg(); msg.setRuleUuids(ruleUuids); msg.setSession(session == null ? adminSession : session); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIDeleteSecurityGroupRuleEvent evt = sender.send(msg, APIDeleteSecurityGroupRuleEvent.class); return evt.getInventory(); } public void removeVmNicFromSecurityGroup(String securityGroupUuid, String vmNicUuid) throws ApiSenderException { removeVmNicFromSecurityGroup(securityGroupUuid, vmNicUuid, null); } public void removeVmNicFromSecurityGroup(String securityGroupUuid, String vmNicUuid, SessionInventory session) throws ApiSenderException { APIDeleteVmNicFromSecurityGroupMsg msg = new APIDeleteVmNicFromSecurityGroupMsg(); msg.setSecurityGroupUuid(securityGroupUuid); msg.setVmNicUuids(Arrays.asList(vmNicUuid)); msg.setSession(session == null ? adminSession : session); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); sender.send(msg, APIDeleteVmNicFromSecurityGroupEvent.class); } public void addVmNicToSecurityGroup(String securityGroupUuid, String vmNicUuid) throws ApiSenderException { List<String> nicUuids = new ArrayList<String>(); nicUuids.add(vmNicUuid); addVmNicToSecurityGroup(securityGroupUuid, nicUuids); } public void addVmNicToSecurityGroup(String securityGroupUuid, List<String> vmNicUuids) throws ApiSenderException { addVmNicToSecurityGroup(securityGroupUuid, vmNicUuids, null); } public void addVmNicToSecurityGroup(String securityGroupUuid, List<String> vmNicUuids, SessionInventory session) throws ApiSenderException { APIAddVmNicToSecurityGroupMsg msg = new APIAddVmNicToSecurityGroupMsg(); msg.setSecurityGroupUuid(securityGroupUuid); msg.setSession(session == null ? adminSession : session); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setVmNicUuids(vmNicUuids); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); sender.send(msg, APIAddVmNicToSecurityGroupEvent.class); } public SecurityGroupInventory attachSecurityGroupToL3Network(String securityGroupUuid, String l3NetworkUuid) throws ApiSenderException { return attachSecurityGroupToL3Network(securityGroupUuid, l3NetworkUuid, null); } public SecurityGroupInventory attachSecurityGroupToL3Network(String securityGroupUuid, String l3NetworkUuid, SessionInventory session) throws ApiSenderException { APIAttachSecurityGroupToL3NetworkMsg msg = new APIAttachSecurityGroupToL3NetworkMsg(); msg.setL3NetworkUuid(l3NetworkUuid); msg.setSecurityGroupUuid(securityGroupUuid); msg.setSession(session == null ? adminSession : session); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIAttachSecurityGroupToL3NetworkEvent evt = sender.send(msg, APIAttachSecurityGroupToL3NetworkEvent.class); return evt.getInventory(); } public SecurityGroupInventory detachSecurityGroupFromL3Network(String securityGroupUuid, String l3NetworkUuid) throws ApiSenderException { return detachSecurityGroupFromL3Network(securityGroupUuid, l3NetworkUuid, null); } public SecurityGroupInventory detachSecurityGroupFromL3Network(String securityGroupUuid, String l3NetworkUuid, SessionInventory session) throws ApiSenderException { APIDetachSecurityGroupFromL3NetworkMsg msg = new APIDetachSecurityGroupFromL3NetworkMsg(); msg.setL3NetworkUuid(l3NetworkUuid); msg.setSecurityGroupUuid(securityGroupUuid); msg.setSession(session == null ? adminSession : session); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIDetachSecurityGroupFromL3NetworkEvent evt = sender.send(msg, APIDetachSecurityGroupFromL3NetworkEvent.class); return evt.getInventory(); } public void deleteSecurityGroup(String securityGroupUuid) throws ApiSenderException { deleteSecurityGroup(securityGroupUuid, null); } public void deleteSecurityGroup(String securityGroupUuid, SessionInventory session) throws ApiSenderException { APIDeleteSecurityGroupMsg msg = new APIDeleteSecurityGroupMsg(); msg.setUuid(securityGroupUuid); msg.setSession(session == null ? adminSession : session); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); sender.send(msg, APIDeleteSecurityGroupEvent.class); } public void reconnectPrimaryStorage(String psUuid) throws ApiSenderException { APIReconnectPrimaryStorageMsg msg = new APIReconnectPrimaryStorageMsg(); msg.setUuid(psUuid); msg.setSession(adminSession); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); sender.send(msg, APIReconnectPrimaryStorageEvent.class); } public void reconnectHost(String hostUuid) throws ApiSenderException { APIReconnectHostMsg msg = new APIReconnectHostMsg(); msg.setUuid(hostUuid); msg.setSession(adminSession); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); sender.send(msg, APIReconnectHostEvent.class); } public SftpBackupStorageInventory reconnectSftpBackupStorage(String bsUuid) throws ApiSenderException { APIReconnectSftpBackupStorageMsg msg = new APIReconnectSftpBackupStorageMsg(); msg.setSession(adminSession); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setUuid(bsUuid); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIReconnectSftpBackupStorageEvent evt = sender.send(msg, APIReconnectSftpBackupStorageEvent.class); return evt.getInventory(); } public ImageInventory createTemplateFromRootVolume(String name, String rootVolumeUuid, List<String> backupStorageUuids) throws ApiSenderException { return createTemplateFromRootVolume(name, rootVolumeUuid, backupStorageUuids, null); } public ImageInventory createTemplateFromRootVolume(String name, String rootVolumeUuid, List<String> backupStorageUuids, SessionInventory session) throws ApiSenderException { APICreateRootVolumeTemplateFromRootVolumeMsg msg = new APICreateRootVolumeTemplateFromRootVolumeMsg(); msg.setName(name); msg.setBackupStorageUuids(backupStorageUuids); msg.setRootVolumeUuid(rootVolumeUuid); msg.setGuestOsType("test"); msg.setSession(session == null ? adminSession : session); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APICreateRootVolumeTemplateFromRootVolumeEvent evt = sender.send(msg, APICreateRootVolumeTemplateFromRootVolumeEvent.class); return evt.getInventory(); } public ImageInventory createTemplateFromRootVolume(String name, String rootVolumeUuid, String backupStorageUuid) throws ApiSenderException { return createTemplateFromRootVolume(name, rootVolumeUuid, backupStorageUuid, null); } public ImageInventory createTemplateFromRootVolume(String name, String rootVolumeUuid, String backupStorageUuid, SessionInventory session) throws ApiSenderException { return createTemplateFromRootVolume(name, rootVolumeUuid, Arrays.asList(backupStorageUuid), session); } public List<VmNicInventory> listVmNic(List<String> uuids) throws ApiSenderException { APIListVmNicMsg msg = new APIListVmNicMsg(); msg.setSession(adminSession); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setUuids(uuids); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIListVmNicReply reply = sender.call(msg, APIListVmNicReply.class); return reply.getInventories(); } public List<SecurityGroupInventory> listSecurityGroup(List<String> uuids) throws ApiSenderException { APIListSecurityGroupMsg msg = new APIListSecurityGroupMsg(); msg.setSession(adminSession); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setUuids(uuids); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIListSecurityGroupReply reply = sender.call(msg, APIListSecurityGroupReply.class); return reply.getInventories(); } public void removeVmFromSimulatorHost(String hostUuid, String vmUuid) { RemoveVmOnSimulatorMsg msg = new RemoveVmOnSimulatorMsg(); msg.setHostUuid(hostUuid); msg.setVmUuid(vmUuid); bus.makeTargetServiceIdByResourceUuid(msg, HostConstant.SERVICE_ID, hostUuid); bus.call(msg); } public void changeVmStateOnSimulatorHost(String hostUuid, String vmUuid, VmInstanceState state) { ChangeVmStateOnSimulatorHostMsg msg = new ChangeVmStateOnSimulatorHostMsg(); msg.setHostUuid(hostUuid); msg.setVmState(state.toString()); msg.setVmUuid(vmUuid); bus.makeTargetServiceIdByResourceUuid(msg, HostConstant.SERVICE_ID, hostUuid); bus.call(msg); } public VipInventory acquireIp(String l3NetworkUuid, String requiredIp) throws ApiSenderException { return acquireIp(l3NetworkUuid, requiredIp, null); } public VipInventory acquireIp(String l3NetworkUuid, String requiredIp, SessionInventory session) throws ApiSenderException { APICreateVipMsg msg = new APICreateVipMsg(); msg.setName("vip"); msg.setL3NetworkUuid(l3NetworkUuid); msg.setSession(session == null ? adminSession : session); msg.setRequiredIp(requiredIp); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APICreateVipEvent evt = sender.send(msg, APICreateVipEvent.class); return evt.getInventory(); } public VipInventory acquireIp(String l3NetworkUuid) throws ApiSenderException { return acquireIp(l3NetworkUuid, (SessionInventory) null); } public VipInventory acquireIp(String l3NetworkUuid, SessionInventory session) throws ApiSenderException { return acquireIp(l3NetworkUuid, null, session); } public VipInventory changeVipSate(String uuid, VipStateEvent sevt) throws ApiSenderException { return changeVipSate(uuid, sevt, null); } public VipInventory changeVipSate(String uuid, VipStateEvent sevt, SessionInventory session) throws ApiSenderException { APIChangeVipStateMsg msg = new APIChangeVipStateMsg(); msg.setStateEvent(sevt.toString()); msg.setUuid(uuid); msg.setSession(session == null ? adminSession : session); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIChangeVipStateEvent evt = sender.send(msg, APIChangeVipStateEvent.class); return evt.getInventory(); } public void releaseIp(String ipUuid) throws ApiSenderException { releaseIp(ipUuid, null); } public void releaseIp(String ipUuid, SessionInventory session) throws ApiSenderException { APIDeleteVipMsg msg = new APIDeleteVipMsg(); msg.setUuid(ipUuid); msg.setSession(session == null ? adminSession : session); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); sender.send(msg, APIDeleteVipEvent.class); } public PortForwardingRuleInventory changePortForwardingRuleState(String uuid, PortForwardingRuleStateEvent sevt) throws ApiSenderException { return changePortForwardingRuleState(uuid, sevt, null); } public PortForwardingRuleInventory changePortForwardingRuleState(String uuid, PortForwardingRuleStateEvent sevt, SessionInventory session) throws ApiSenderException { APIChangePortForwardingRuleStateMsg msg = new APIChangePortForwardingRuleStateMsg(); msg.setUuid(uuid); msg.setStateEvent(sevt.toString()); msg.setSession(session == null ? adminSession : session); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIChangePortForwardingRuleStateEvent evt = sender.send(msg, APIChangePortForwardingRuleStateEvent.class); return evt.getInventory(); } public PortForwardingRuleInventory createPortForwardingRuleByFullConfig(PortForwardingRuleInventory rule) throws ApiSenderException { return createPortForwardingRuleByFullConfig(rule, null); } public PortForwardingRuleInventory createPortForwardingRuleByFullConfig(PortForwardingRuleInventory rule, SessionInventory session) throws ApiSenderException { APICreatePortForwardingRuleMsg msg = new APICreatePortForwardingRuleMsg(); msg.setName(rule.getName()); msg.setDescription(rule.getDescription()); msg.setAllowedCidr(rule.getAllowedCidr()); msg.setPrivatePortEnd(rule.getPrivatePortEnd()); msg.setPrivatePortStart(rule.getPrivatePortStart()); msg.setVipUuid(rule.getVipUuid()); msg.setVipPortEnd(rule.getVipPortEnd()); msg.setVipPortStart(rule.getVipPortStart()); msg.setVmNicUuid(rule.getVmNicUuid()); msg.setProtocolType(rule.getProtocolType()); msg.setSession(session == null ? adminSession : session); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APICreatePortForwardingRuleEvent evt = sender.send(msg, APICreatePortForwardingRuleEvent.class); return evt.getInventory(); } public void revokePortForwardingRule(String ruleUuid) throws ApiSenderException { revokePortForwardingRule(ruleUuid, null); } public void revokePortForwardingRule(String ruleUuid, SessionInventory session) throws ApiSenderException { APIDeletePortForwardingRuleMsg msg = new APIDeletePortForwardingRuleMsg(); msg.setSession(session == null ? adminSession : session); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setUuid(ruleUuid); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); sender.send(msg, APIDeletePortForwardingRuleEvent.class); } public PortForwardingRuleInventory attachPortForwardingRule(String ruleUuid, String vmNicUuid) throws ApiSenderException { return attachPortForwardingRule(ruleUuid, vmNicUuid, null); } public PortForwardingRuleInventory attachPortForwardingRule(String ruleUuid, String vmNicUuid, SessionInventory session) throws ApiSenderException { APIAttachPortForwardingRuleMsg msg = new APIAttachPortForwardingRuleMsg(); msg.setSession(session == null ? adminSession : session); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setRuleUuid(ruleUuid); msg.setVmNicUuid(vmNicUuid); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIAttachPortForwardingRuleEvent evt = sender.send(msg, APIAttachPortForwardingRuleEvent.class); return evt.getInventory(); } public PortForwardingRuleInventory detachPortForwardingRule(String ruleUuid) throws ApiSenderException { return detachPortForwardingRule(ruleUuid, null); } public PortForwardingRuleInventory detachPortForwardingRule(String ruleUuid, SessionInventory session) throws ApiSenderException { APIDetachPortForwardingRuleMsg msg = new APIDetachPortForwardingRuleMsg(); msg.setSession(session == null ? adminSession : session); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setUuid(ruleUuid); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIDetachPortForwardingRuleEvent evt = sender.send(msg, APIDetachPortForwardingRuleEvent.class); return evt.getInventory(); } public List<PortForwardingRuleInventory> listPortForwardingRules(List<String> uuids) throws ApiSenderException { APIListPortForwardingRuleMsg msg = new APIListPortForwardingRuleMsg(uuids); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setSession(adminSession); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIListPortForwardingRuleReply reply = sender.call(msg, APIListPortForwardingRuleReply.class); return reply.getInventories(); } public List<VmNicInventory> getPortForwardingAttachableNics(String ruleUuid) throws ApiSenderException { APIGetPortForwardingAttachableVmNicsMsg msg = new APIGetPortForwardingAttachableVmNicsMsg(); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setSession(adminSession); msg.setRuleUuid(ruleUuid); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIGetPortForwardingAttachableVmNicsReply reply = sender.call(msg, APIGetPortForwardingAttachableVmNicsReply.class); return reply.getInventories(); } public List<VmNicSecurityGroupRefInventory> listVmNicSecurityGroupRef(List<String> uuids) throws ApiSenderException { APIListVmNicInSecurityGroupMsg msg = new APIListVmNicInSecurityGroupMsg(); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setSession(adminSession); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIListVmNicInSecurityGroupReply reply = sender.call(msg, APIListVmNicInSecurityGroupReply.class); return reply.getInventories(); } public List<String> getHypervisorTypes() throws ApiSenderException { APIGetHypervisorTypesMsg msg = new APIGetHypervisorTypesMsg(); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setSession(adminSession); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIGetHypervisorTypesReply reply = sender.call(msg, APIGetHypervisorTypesReply.class); return reply.getHypervisorTypes(); } public Map<String, List<String>> getNetworkServiceTypes() throws ApiSenderException { APIGetNetworkServiceTypesMsg msg = new APIGetNetworkServiceTypesMsg(); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setSession(adminSession); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIGetNetworkServiceTypesReply reply = sender.call(msg, APIGetNetworkServiceTypesReply.class); return reply.getServiceAndProviderTypes(); } public List<String> getL2NetworkTypes() throws ApiSenderException { APIGetL2NetworkTypesMsg msg = new APIGetL2NetworkTypesMsg(); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setSession(adminSession); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIGetL2NetworkTypesReply reply = sender.call(msg, APIGetL2NetworkTypesReply.class); return reply.getL2NetworkTypes(); } public List<String> getL3NetworkTypes() throws ApiSenderException { return getL3NetworkTypes(null); } public List<String> getL3NetworkTypes(SessionInventory session) throws ApiSenderException { APIGetL3NetworkTypesMsg msg = new APIGetL3NetworkTypesMsg(); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setSession(session == null ? adminSession : session); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIGetL3NetworkTypesReply reply = sender.call(msg, APIGetL3NetworkTypesReply.class); return reply.getL3NetworkTypes(); } public List<String> getPrimaryStorageTypes() throws ApiSenderException { APIGetPrimaryStorageTypesMsg msg = new APIGetPrimaryStorageTypesMsg(); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setSession(adminSession); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIGetPrimaryStorageTypesReply reply = sender.call(msg, APIGetPrimaryStorageTypesReply.class); return reply.getPrimaryStorageTypes(); } public List<String> getBackupStorageTypes() throws ApiSenderException { APIGetBackupStorageTypesMsg msg = new APIGetBackupStorageTypesMsg(); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setSession(adminSession); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIGetBackupStorageTypesReply reply = sender.call(msg, APIGetBackupStorageTypesReply.class); return reply.getBackupStorageTypes(); } public ImageInventory changeImageState(String uuid, ImageStateEvent evt, SessionInventory session) throws ApiSenderException { APIChangeImageStateMsg msg = new APIChangeImageStateMsg(); msg.setUuid(uuid); msg.setStateEvent(evt.toString()); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setSession(session == null ? adminSession : session); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIChangeImageStateEvent revt = sender.send(msg, APIChangeImageStateEvent.class); return revt.getInventory(); } public ImageInventory changeImageState(String uuid, ImageStateEvent evt) throws ApiSenderException { return changeImageState(uuid, evt, null); } public List<String> getHostAllocatorStrategies() throws ApiSenderException { APIGetHostAllocatorStrategiesMsg msg = new APIGetHostAllocatorStrategiesMsg(); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setSession(adminSession); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIGetHostAllocatorStrategiesReply reply = sender.call(msg, APIGetHostAllocatorStrategiesReply.class); return reply.getHostAllocatorStrategies(); } public List<String> getPrimaryStorageAllocatorStrategies() throws ApiSenderException { APIGetPrimaryStorageAllocatorStrategiesMsg msg = new APIGetPrimaryStorageAllocatorStrategiesMsg(); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setSession(adminSession); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIGetPrimaryStorageAllocatorStrategiesReply reply = sender.call(msg, APIGetPrimaryStorageAllocatorStrategiesReply.class); return reply.getPrimaryStorageAllocatorStrategies(); } public DiskOfferingInventory changeDiskOfferingState(String uuid, DiskOfferingStateEvent sevt) throws ApiSenderException { return changeDiskOfferingState(uuid, sevt, null); } public DiskOfferingInventory changeDiskOfferingState(String uuid, DiskOfferingStateEvent sevt, SessionInventory session) throws ApiSenderException { APIChangeDiskOfferingStateMsg msg = new APIChangeDiskOfferingStateMsg(); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setSession(session == null ? adminSession : session); msg.setUuid(uuid); msg.setStateEvent(sevt.toString()); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIChangeDiskOfferingStateEvent evt = sender.send(msg, APIChangeDiskOfferingStateEvent.class); return evt.getInventory(); } public VmInstanceInventory attachNic(String vmUuid, String l3Uuid) throws ApiSenderException { APIAttachL3NetworkToVmMsg msg = new APIAttachL3NetworkToVmMsg(); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setSession(adminSession); msg.setVmInstanceUuid(vmUuid); msg.setL3NetworkUuid(l3Uuid); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIAttachL3NetworkToVmEvent evt = sender.send(msg, APIAttachL3NetworkToVmEvent.class); return evt.getInventory(); } public List<L3NetworkInventory> getVmAttachableL3Networks(String vmUuid) throws ApiSenderException { return getVmAttachableL3Networks(vmUuid, null); } public List<L3NetworkInventory> getVmAttachableL3Networks(String vmUuid, SessionInventory session) throws ApiSenderException { APIGetVmAttachableL3NetworkMsg msg = new APIGetVmAttachableL3NetworkMsg(); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setSession(session == null ? adminSession : session); msg.setVmInstanceUuid(vmUuid); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIGetVmAttachableL3NetworkReply reply = sender.call(msg, APIGetVmAttachableL3NetworkReply.class); return reply.getInventories(); } public VmInstanceInventory detachNic(String nicUuid) throws ApiSenderException { return detachNic(nicUuid, null); } public VmInstanceInventory detachNic(String niUuid, SessionInventory session) throws ApiSenderException { APIDetachL3NetworkFromVmMsg msg = new APIDetachL3NetworkFromVmMsg(); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setSession(session == null ? adminSession : session); msg.setVmNicUuid(niUuid); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIDetachL3NetworkFromVmEvent evt = sender.send(msg, APIDetachL3NetworkFromVmEvent.class); return evt.getInventory(); } public ConsoleInventory getConsole(String vmUuid) throws ApiSenderException { APIRequestConsoleAccessMsg msg = new APIRequestConsoleAccessMsg(); msg.setVmInstanceUuid(vmUuid); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setSession(adminSession); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIRequestConsoleAccessEvent evt = sender.send(msg, APIRequestConsoleAccessEvent.class); return evt.getInventory(); } public EipInventory createEip(String name, String vipUuid, String vmNicUuid) throws ApiSenderException { return createEip(name, vipUuid, vmNicUuid, null); } public EipInventory createEip(String name, String vipUuid, String vmNicUuid, SessionInventory session) throws ApiSenderException { APICreateEipMsg msg = new APICreateEipMsg(); msg.setName(name); msg.setDescription(name); msg.setVipUuid(vipUuid); msg.setVmNicUuid(vmNicUuid); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setSession(session == null ? adminSession : session); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APICreateEipEvent evt = sender.send(msg, APICreateEipEvent.class); return evt.getInventory(); } public void removeEip(String eipUuid) throws ApiSenderException { removeEip(eipUuid, null); } public void removeEip(String eipUuid, SessionInventory session) throws ApiSenderException { APIDeleteEipMsg msg = new APIDeleteEipMsg(); msg.setUuid(eipUuid); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setSession(session == null ? adminSession : session); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); sender.send(msg, APIDeleteEipEvent.class); } public EipInventory attachEip(String eipUuid, String vmNicUuid) throws ApiSenderException { return attachEip(eipUuid, vmNicUuid, null); } public EipInventory attachEip(String eipUuid, String vmNicUuid, SessionInventory session) throws ApiSenderException { APIAttachEipMsg msg = new APIAttachEipMsg(); msg.setVmNicUuid(vmNicUuid); msg.setEipUuid(eipUuid); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setSession(session == null ? adminSession : session); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIAttachEipEvent evt = sender.send(msg, APIAttachEipEvent.class); return evt.getInventory(); } public EipInventory changeEipState(String eipUuid, EipStateEvent sevt) throws ApiSenderException { return changeEipState(eipUuid, sevt, null); } public EipInventory changeEipState(String eipUuid, EipStateEvent sevt, SessionInventory session) throws ApiSenderException { APIChangeEipStateMsg msg = new APIChangeEipStateMsg(); msg.setUuid(eipUuid); msg.setStateEvent(sevt.toString()); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setSession(session == null ? adminSession : session); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIChangeEipStateEvent evt = sender.send(msg, APIChangeEipStateEvent.class); return evt.getInventory(); } public EipInventory detachEip(String eipUuid) throws ApiSenderException { return detachEip(eipUuid, null); } public EipInventory detachEip(String eipUuid, SessionInventory session) throws ApiSenderException { APIDetachEipMsg msg = new APIDetachEipMsg(); msg.setUuid(eipUuid); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setSession(session == null ? adminSession : session); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIDetachEipEvent evt = sender.send(msg, APIDetachEipEvent.class); return evt.getInventory(); } public List<VmNicInventory> getEipAttachableVmNicsByEipUuid(String eipUuid) throws ApiSenderException { return getEipAttachableVmNics(eipUuid, null); } public List<VmNicInventory> getEipAttachableVmNicsByVipUuid(String vipUuid) throws ApiSenderException { return getEipAttachableVmNics(null, vipUuid); } private List<VmNicInventory> getEipAttachableVmNics(String eipUuid, String vipUuid) throws ApiSenderException { APIGetEipAttachableVmNicsMsg msg = new APIGetEipAttachableVmNicsMsg(); msg.setEipUuid(eipUuid); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setVipUuid(vipUuid); msg.setSession(adminSession); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIGetEipAttachableVmNicsReply reply = sender.call(msg, APIGetEipAttachableVmNicsReply.class); return reply.getInventories(); } public List<VolumeSnapshotTreeInventory> getVolumeSnapshotTree(String treeUuid, String volumeUuid) throws ApiSenderException { APIGetVolumeSnapshotTreeMsg msg = new APIGetVolumeSnapshotTreeMsg(); msg.setVolumeUuid(volumeUuid); msg.setTreeUuid(treeUuid); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setSession(adminSession); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIGetVolumeSnapshotTreeReply reply = sender.call(msg, APIGetVolumeSnapshotTreeReply.class); return reply.getInventories(); } public VolumeSnapshotInventory backupSnapshot(String snapshotUuid) throws ApiSenderException { return backupSnapshot(snapshotUuid, null, null); } public VolumeSnapshotInventory backupSnapshot(String snapshotUuid, String backupStorageUuid) throws ApiSenderException { return backupSnapshot(snapshotUuid, backupStorageUuid, null); } public VolumeSnapshotInventory backupSnapshot(String snapshotUuid, String backupStorageUuid, SessionInventory session) throws ApiSenderException { APIBackupVolumeSnapshotMsg msg = new APIBackupVolumeSnapshotMsg(); msg.setUuid(snapshotUuid); msg.setBackupStorageUuid(backupStorageUuid); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setSession(session == null ? adminSession : session); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIBackupVolumeSnapshotEvent evt = sender.send(msg, APIBackupVolumeSnapshotEvent.class); return evt.getInventory(); } public VolumeSnapshotInventory deleteSnapshotFromBackupStorage(String snapshotUuid, String...bsUuids) throws ApiSenderException { return deleteSnapshotFromBackupStorage(snapshotUuid, null, bsUuids); } public VolumeSnapshotInventory deleteSnapshotFromBackupStorage(String snapshotUuid, SessionInventory session, String...bsUuids) throws ApiSenderException { APIDeleteVolumeSnapshotFromBackupStorageMsg msg = new APIDeleteVolumeSnapshotFromBackupStorageMsg(); msg.setUuid(snapshotUuid); if (bsUuids != null) { msg.setBackupStorageUuids(Arrays.asList(bsUuids)); } else { msg.setBackupStorageUuids(new ArrayList<String>()); } msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setSession(session == null ? adminSession : session); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIDeleteVolumeSnapshotFromBackupStorageEvent evt = sender.send(msg, APIDeleteVolumeSnapshotFromBackupStorageEvent.class); return evt.getInventory(); } private TagInventory createTag(String resourceUuid, String tag, Class entityClass, TagType type) throws ApiSenderException { return createTag(resourceUuid, tag, entityClass, type, null); } private TagInventory createTag(String resourceUuid, String tag, Class entityClass, TagType type, SessionInventory session) throws ApiSenderException { APICreateTagMsg msg; if (type == TagType.System) { msg = new APICreateSystemTagMsg(); } else { msg = new APICreateUserTagMsg(); } msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setSession(session == null ? adminSession : session); msg.setResourceType(entityClass.getSimpleName()); msg.setResourceUuid(resourceUuid); msg.setTag(tag); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); if (type == TagType.System) { APICreateSystemTagEvent evt = sender.send(msg, APICreateSystemTagEvent.class); return evt.getInventory(); } else { APICreateUserTagEvent evt = sender.send(msg, APICreateUserTagEvent.class); return evt.getInventory(); } } public TagInventory createUserTag(String resourceUuid, String tag, Class entitiClass) throws ApiSenderException { return createUserTag(resourceUuid, tag, entitiClass, null); } public TagInventory createUserTag(String resourceUuid, String tag, Class entitiClass, SessionInventory session) throws ApiSenderException { return createTag(resourceUuid, tag, entitiClass, TagType.User, session); } public TagInventory createSystemTag(String resourceUuid, String tag, Class entitiClass) throws ApiSenderException { return createSystemTag(resourceUuid, tag, entitiClass, null); } public TagInventory createSystemTag(String resourceUuid, String tag, Class entitiClass, SessionInventory session) throws ApiSenderException { return createTag(resourceUuid, tag, entitiClass, TagType.System, session); } public TagInventory updateSystemTag(String uuid, String tag, SessionInventory session) throws ApiSenderException { APIUpdateSystemTagMsg msg = new APIUpdateSystemTagMsg(); msg.setUuid(uuid); msg.setTag(tag); msg.setSession(session == null ? adminSession : session); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIUpdateSystemTagEvent evt = sender.send(msg, APIUpdateSystemTagEvent.class); return evt.getInventory(); } public void deleteTag(String tagUuid) throws ApiSenderException { deleteTag(tagUuid, null); } public void deleteTag(String tagUuid, SessionInventory session) throws ApiSenderException { APIDeleteTagMsg msg = new APIDeleteTagMsg(); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setSession(session == null ? adminSession : session); msg.setUuid(tagUuid); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); sender.send(msg, APIDeleteTagEvent.class); } public VolumeInventory backupDataVolume(String volUuid, String backupStorgeUuid) throws ApiSenderException { APIBackupDataVolumeMsg msg = new APIBackupDataVolumeMsg(); msg.setUuid(volUuid); msg.setBackupStorageUuid(backupStorgeUuid); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setSession(adminSession); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIBackupDataVolumeEvent evt = sender.send(msg, APIBackupDataVolumeEvent.class); return evt.getInventory(); } public void generateVOViewSql() throws ApiSenderException { APIGenerateSqlVOViewMsg msg = new APIGenerateSqlVOViewMsg(); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setSession(adminSession); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIGenerateSqlVOViewEvent evt = sender.send(msg, APIGenerateSqlVOViewEvent.class); } public void generateTypeScript() throws ApiSenderException { APIGenerateApiTypeScriptDefinitionMsg msg = new APIGenerateApiTypeScriptDefinitionMsg(); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setSession(adminSession); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); sender.send(msg, APIGenerateApiTypeScriptDefinitionEvent.class); } public ApplianceVmInventory reconnectVirtualRouter(String uuid) throws ApiSenderException { APIReconnectVirtualRouterMsg msg = new APIReconnectVirtualRouterMsg(); msg.setVmInstanceUuid(uuid); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setSession(adminSession); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIReconnectVirtualRouterEvent evt = sender.send(msg, APIReconnectVirtualRouterEvent.class); return evt.getInventory(); } @Override public boolean handleEvent(Event e) { logger.trace(JSONObjectUtil.toJsonString(e)); return false; } public SessionInventory getAdminSession() { return adminSession; } public void setAdminSession(SessionInventory adminSession) { this.adminSession = adminSession; } public List<ApplianceVmInventory> listApplianceVm() throws ApiSenderException { APIListApplianceVmMsg msg = new APIListApplianceVmMsg(); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setSession(adminSession); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIListApplianceVmReply reply = sender.call(msg, APIListApplianceVmReply.class); return reply.getInventories(); } public int getTimeout() { return timeout; } public void setTimeout(int timeout) { this.timeout = timeout; } public static ComponentLoader getLoader() { return loader; } public ZoneInventory updateZone(ZoneInventory inv) throws ApiSenderException { APIUpdateZoneMsg msg = new APIUpdateZoneMsg(); msg.setSession(adminSession); msg.setName(inv.getName()); msg.setDescription(inv.getDescription()); msg.setUuid(inv.getUuid()); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIUpdateZoneEvent evt = sender.send(msg, APIUpdateZoneEvent.class); return evt.getInventory(); } public ClusterInventory updateCluster(ClusterInventory inv) throws ApiSenderException { APIUpdateClusterMsg msg = new APIUpdateClusterMsg(); msg.setSession(adminSession); msg.setName(inv.getName()); msg.setDescription(inv.getDescription()); msg.setUuid(inv.getUuid()); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIUpdateClusterEvent evt = sender.send(msg, APIUpdateClusterEvent.class); return evt.getInventory(); } public HostInventory updateHost(HostInventory inv) throws ApiSenderException { APIUpdateHostMsg msg = new APIUpdateHostMsg(); msg.setSession(adminSession); msg.setName(inv.getName()); msg.setDescription(inv.getDescription()); msg.setUuid(inv.getUuid()); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIUpdateHostEvent evt = sender.send(msg, APIUpdateHostEvent.class); return evt.getInventory(); } public VmInstanceInventory updateVm(VmInstanceInventory inv) throws ApiSenderException { APIUpdateVmInstanceMsg msg = new APIUpdateVmInstanceMsg(); msg.setSession(adminSession); msg.setName(inv.getName()); msg.setDescription(inv.getDescription()); msg.setUuid(inv.getUuid()); msg.setState(inv.getState()); msg.setDefaultL3NetworkUuid(inv.getDefaultL3NetworkUuid()); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIUpdateVmInstanceEvent evt = sender.send(msg, APIUpdateVmInstanceEvent.class); return evt.getInventory(); } public PrimaryStorageInventory updatePrimaryStorage(PrimaryStorageInventory inv) throws ApiSenderException { APIUpdatePrimaryStorageMsg msg = new APIUpdatePrimaryStorageMsg(); msg.setSession(adminSession); msg.setName(inv.getName()); msg.setDescription(inv.getDescription()); msg.setUuid(inv.getUuid()); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIUpdatePrimaryStorageEvent evt = sender.send(msg, APIUpdatePrimaryStorageEvent.class); return evt.getInventory(); } public BackupStorageInventory updateSftpBackupStorage(SftpBackupStorageInventory inv, String password) throws ApiSenderException { APIUpdateSftpBackupStorageMsg msg = new APIUpdateSftpBackupStorageMsg(); msg.setSession(adminSession); msg.setName(inv.getName()); msg.setDescription(inv.getDescription()); msg.setUuid(inv.getUuid()); msg.setUsername(inv.getUsername()); msg.setPassword(password); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIUpdateBackupStorageEvent evt = sender.send(msg, APIUpdateBackupStorageEvent.class); return evt.getInventory(); } public VolumeInventory updateVolume(VolumeInventory inv) throws ApiSenderException { return updateVolume(inv, null); } public VolumeInventory updateVolume(VolumeInventory inv, SessionInventory session) throws ApiSenderException { APIUpdateVolumeMsg msg = new APIUpdateVolumeMsg(); msg.setSession(session == null ? adminSession : session); msg.setName(inv.getName()); msg.setDescription(inv.getDescription()); msg.setUuid(inv.getUuid()); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIUpdateVolumeEvent evt = sender.send(msg, APIUpdateVolumeEvent.class); return evt.getInventory(); } public VolumeSnapshotInventory updateVolumeSnapshot(VolumeSnapshotInventory inv) throws ApiSenderException { return updateVolumeSnapshot(inv, null); } public VolumeSnapshotInventory updateVolumeSnapshot(VolumeSnapshotInventory inv, SessionInventory session) throws ApiSenderException { APIUpdateVolumeSnapshotMsg msg = new APIUpdateVolumeSnapshotMsg(); msg.setSession(session == null ? adminSession : session); msg.setName(inv.getName()); msg.setDescription(inv.getDescription()); msg.setUuid(inv.getUuid()); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIUpdateVolumeSnapshotEvent evt = sender.send(msg, APIUpdateVolumeSnapshotEvent.class); return evt.getInventory(); } public VipInventory updateVip(VipInventory inv) throws ApiSenderException { return updateVip(inv, null); } public VipInventory updateVip(VipInventory inv, SessionInventory session) throws ApiSenderException { APIUpdateVipMsg msg = new APIUpdateVipMsg(); msg.setSession(session == null ? adminSession : session); msg.setName(inv.getName()); msg.setDescription(inv.getDescription()); msg.setUuid(inv.getUuid()); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIUpdateVipEvent evt = sender.send(msg, APIUpdateVipEvent.class); return evt.getInventory(); } public PortForwardingRuleInventory updatePortForwardingRule(PortForwardingRuleInventory inv) throws ApiSenderException { return updatePortForwardingRule(inv, null); } public PortForwardingRuleInventory updatePortForwardingRule(PortForwardingRuleInventory inv, SessionInventory session) throws ApiSenderException { APIUpdatePortForwardingRuleMsg msg = new APIUpdatePortForwardingRuleMsg(); msg.setSession(session == null ? adminSession : session); msg.setName(inv.getName()); msg.setDescription(inv.getDescription()); msg.setUuid(inv.getUuid()); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIUpdatePortForwardingRuleEvent evt = sender.send(msg, APIUpdatePortForwardingRuleEvent.class); return evt.getInventory(); } public SecurityGroupInventory updateSecurityGroup(SecurityGroupInventory inv) throws ApiSenderException { return updateSecurityGroup(inv, null); } public SecurityGroupInventory updateSecurityGroup(SecurityGroupInventory inv, SessionInventory session) throws ApiSenderException { APIUpdateSecurityGroupMsg msg = new APIUpdateSecurityGroupMsg(); msg.setSession(session == null ? adminSession : session); msg.setName(inv.getName()); msg.setDescription(inv.getDescription()); msg.setUuid(inv.getUuid()); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIUpdateSecurityGroupEvent evt = sender.send(msg, APIUpdateSecurityGroupEvent.class); return evt.getInventory(); } public ImageInventory updateImage(ImageInventory inv) throws ApiSenderException { APIUpdateImageMsg msg = new APIUpdateImageMsg(); msg.setSession(adminSession); msg.setName(inv.getName()); msg.setDescription(inv.getDescription()); msg.setUuid(inv.getUuid()); msg.setGuestOsType(inv.getGuestOsType()); msg.setSystem(inv.isSystem()); msg.setFormat(inv.getFormat()); msg.setPlatform(inv.getPlatform()); msg.setMediaType(inv.getMediaType()); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIUpdateImageEvent evt = sender.send(msg, APIUpdateImageEvent.class); return evt.getInventory(); } public EipInventory updateEip(EipInventory inv) throws ApiSenderException { return updateEip(inv, null); } public EipInventory updateEip(EipInventory inv, SessionInventory session) throws ApiSenderException { APIUpdateEipMsg msg = new APIUpdateEipMsg(); msg.setSession(session == null ? adminSession : session); msg.setName(inv.getName()); msg.setDescription(inv.getDescription()); msg.setUuid(inv.getUuid()); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIUpdateEipEvent evt = sender.send(msg, APIUpdateEipEvent.class); return evt.getInventory(); } public DiskOfferingInventory updateDiskOffering(DiskOfferingInventory inv) throws ApiSenderException { return updateDiskOffering(inv, null); } public DiskOfferingInventory updateDiskOffering(DiskOfferingInventory inv, SessionInventory session) throws ApiSenderException { APIUpdateDiskOfferingMsg msg = new APIUpdateDiskOfferingMsg(); msg.setSession(session == null ? adminSession : session); msg.setName(inv.getName()); msg.setDescription(inv.getDescription()); msg.setUuid(inv.getUuid()); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIUpdateDiskOfferingEvent evt = sender.send(msg, APIUpdateDiskOfferingEvent.class); return evt.getInventory(); } public VirtualRouterOfferingInventory createVirtualRouterOffering(VirtualRouterOfferingInventory inv) throws ApiSenderException { return createVirtualRouterOffering(inv, null); } public VirtualRouterOfferingInventory createVirtualRouterOffering(VirtualRouterOfferingInventory inv, SessionInventory session) throws ApiSenderException { APICreateVirtualRouterOfferingMsg msg = new APICreateVirtualRouterOfferingMsg(); msg.setName(inv.getName()); msg.setDescription(inv.getDescription()); msg.setPublicNetworkUuid(inv.getPublicNetworkUuid()); msg.setManagementNetworkUuid(inv.getManagementNetworkUuid()); msg.setZoneUuid(inv.getZoneUuid()); msg.setImageUuid(inv.getImageUuid()); msg.setDefault(inv.isDefault()); msg.setCpuSpeed(inv.getCpuSpeed()); msg.setCpuNum(inv.getCpuNum()); msg.setAllocatorStrategy(inv.getAllocatorStrategy()); msg.setMemorySize(inv.getMemorySize()); msg.setSession(session == null ? adminSession : session); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APICreateInstanceOfferingEvent evt = sender.send(msg, APICreateInstanceOfferingEvent.class); return (VirtualRouterOfferingInventory) evt.getInventory(); } public VirtualRouterOfferingInventory updateVirtualRouterOffering(VirtualRouterOfferingInventory offering) throws ApiSenderException { return updateVirtualRouterOffering(offering, null); } public VirtualRouterOfferingInventory updateVirtualRouterOffering(VirtualRouterOfferingInventory offering, SessionInventory session) throws ApiSenderException { APIUpdateVirtualRouterOfferingMsg msg = new APIUpdateVirtualRouterOfferingMsg(); msg.setSession(session == null ? adminSession : session); msg.setUuid(offering.getUuid()); msg.setName(offering.getName()); msg.setDescription(offering.getDescription()); msg.setIsDefault(offering.isDefault()); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIUpdateInstanceOfferingEvent evt = sender.send(msg, APIUpdateInstanceOfferingEvent.class); return (VirtualRouterOfferingInventory) evt.getInventory(); } public InstanceOfferingInventory updateInstanceOffering(InstanceOfferingInventory inv) throws ApiSenderException { return updateInstanceOffering(inv, null); } public InstanceOfferingInventory updateInstanceOffering(InstanceOfferingInventory inv, SessionInventory session) throws ApiSenderException { APIUpdateInstanceOfferingMsg msg = new APIUpdateInstanceOfferingMsg(); msg.setSession(session == null ? adminSession : session); msg.setName(inv.getName()); msg.setDescription(inv.getDescription()); msg.setUuid(inv.getUuid()); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIUpdateInstanceOfferingEvent evt = sender.send(msg, APIUpdateInstanceOfferingEvent.class); return evt.getInventory(); } public L2NetworkInventory updateL2Network(L2NetworkInventory inv) throws ApiSenderException { APIUpdateL2NetworkMsg msg = new APIUpdateL2NetworkMsg(); msg.setSession(adminSession); msg.setName(inv.getName()); msg.setDescription(inv.getDescription()); msg.setUuid(inv.getUuid()); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIUpdateL2NetworkEvent evt = sender.send(msg, APIUpdateL2NetworkEvent.class); return evt.getInventory(); } public L3NetworkInventory updateL3Network(L3NetworkInventory inv) throws ApiSenderException { return updateL3Network(inv, null); } public L3NetworkInventory updateL3Network(L3NetworkInventory inv, SessionInventory session) throws ApiSenderException { APIUpdateL3NetworkMsg msg = new APIUpdateL3NetworkMsg(); msg.setSession(session == null ? adminSession : session); msg.setName(inv.getName()); msg.setDescription(inv.getDescription()); msg.setUuid(inv.getUuid()); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIUpdateL3NetworkEvent evt = sender.send(msg, APIUpdateL3NetworkEvent.class); return evt.getInventory(); } public IpRangeInventory updateIpRange(IpRangeInventory inv) throws ApiSenderException { APIUpdateIpRangeMsg msg = new APIUpdateIpRangeMsg(); msg.setSession(adminSession); msg.setName(inv.getName()); msg.setDescription(inv.getDescription()); msg.setUuid(inv.getUuid()); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIUpdateIpRangeEvent evt = sender.send(msg, APIUpdateIpRangeEvent.class); return evt.getInventory(); } public KVMHostInventory updateKvmHost(KVMHostInventory inv, String password) throws ApiSenderException { APIUpdateKVMHostMsg msg = new APIUpdateKVMHostMsg(); msg.setSession(adminSession); msg.setName(inv.getName()); msg.setDescription(inv.getDescription()); msg.setUuid(inv.getUuid()); msg.setUsername(inv.getUsername()); msg.setPassword(password); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIUpdateHostEvent evt = sender.send(msg, APIUpdateHostEvent.class); return (KVMHostInventory) evt.getInventory(); } public IscsiFileSystemBackendPrimaryStorageInventory updateIscsiFileSystemPrimaryStorage(IscsiFileSystemBackendPrimaryStorageInventory inv) throws ApiSenderException { APIUpdateIscsiFileSystemBackendPrimaryStorageMsg msg = new APIUpdateIscsiFileSystemBackendPrimaryStorageMsg(); msg.setSession(adminSession); msg.setName(inv.getName()); msg.setDescription(inv.getDescription()); msg.setUuid(inv.getUuid()); msg.setChapUsername(inv.getChapUsername()); msg.setChapPassword(inv.getChapPassword()); msg.setSshUsername(inv.getSshUsername()); msg.setSshPassword(inv.getSshPassword()); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIUpdatePrimaryStorageEvent evt = sender.send(msg, APIUpdatePrimaryStorageEvent.class); return (IscsiFileSystemBackendPrimaryStorageInventory) evt.getInventory(); } public PrimaryStorageInventory syncPrimaryStorageCapacity(String primaryStorageUuid) throws ApiSenderException { APISyncPrimaryStorageCapacityMsg msg = new APISyncPrimaryStorageCapacityMsg(); msg.setPrimaryStorageUuid(primaryStorageUuid); msg.setSession(adminSession); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APISyncPrimaryStorageCapacityEvent evt = sender.send(msg, APISyncPrimaryStorageCapacityEvent.class); return evt.getInventory(); } public void revokeResourceSharing(List<String> resUuids, List<String> accountUuids, boolean toPublic) throws ApiSenderException { revokeResourceSharing(resUuids, accountUuids, toPublic, null); } public void revokeResourceSharing(List<String> resUuids, List<String> accountUuids, boolean toPublic, SessionInventory session) throws ApiSenderException { APIRevokeResourceSharingMsg msg = new APIRevokeResourceSharingMsg(); msg.setResourceUuids(resUuids); msg.setAccountUuids(accountUuids); msg.setToPublic(toPublic); msg.setSession(session == null ? adminSession : session); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); sender.send(msg, APIRevokeResourceSharingEvent.class); } public void revokeAllResourceSharing(List<String> resUuids, SessionInventory session) throws ApiSenderException { APIRevokeResourceSharingMsg msg = new APIRevokeResourceSharingMsg(); msg.setAll(true); msg.setResourceUuids(resUuids); msg.setSession(session == null ? adminSession : session); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); sender.send(msg, APIRevokeResourceSharingEvent.class); } public void shareResource(List<String> resUuids, List<String> accountUuids, boolean toPublic) throws ApiSenderException { shareResource(resUuids, accountUuids, toPublic, null); } public void shareResource(List<String> resUuids, List<String> accountUuids, boolean toPublic, SessionInventory session) throws ApiSenderException { APIShareResourceMsg msg = new APIShareResourceMsg(); msg.setAccountUuids(accountUuids); msg.setResourceUuids(resUuids); msg.setToPublic(toPublic); msg.setSession(session == null ? adminSession : session); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); sender.send(msg, APIShareResourceEvent.class); } public CephBackupStorageInventory addMonToCephBackupStorage(String bsUuid, List<String> monUrls) throws ApiSenderException { APIAddMonToCephBackupStorageMsg msg = new APIAddMonToCephBackupStorageMsg(); msg.setUuid(bsUuid); msg.setMonUrls(monUrls); msg.setSession(adminSession); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIAddMonToCephBackupStorageEvent evt = sender.send(msg, APIAddMonToCephBackupStorageEvent.class); return evt.getInventory(); } public CephPrimaryStorageInventory addMonToCephPrimaryStorage(String psUuid, List<String> monUrls) throws ApiSenderException { APIAddMonToCephPrimaryStorageMsg msg = new APIAddMonToCephPrimaryStorageMsg(); msg.setUuid(psUuid); msg.setMonUrls(monUrls); msg.setSession(adminSession); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIAddMonToCephPrimaryStorageEvent evt = sender.send(msg, APIAddMonToCephPrimaryStorageEvent.class); return evt.getInventory(); } public CephBackupStorageInventory removeMonFromBackupStorage(String bsUuid, List<String> hostnames) throws ApiSenderException { APIRemoveMonFromCephBackupStorageMsg msg = new APIRemoveMonFromCephBackupStorageMsg(); msg.setUuid(bsUuid); msg.setMonHostnames(hostnames); msg.setSession(adminSession); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIRemoveMonFromCephBackupStorageEvent evt = sender.send(msg, APIRemoveMonFromCephBackupStorageEvent.class); return evt.getInventory(); } public CephPrimaryStorageInventory removeMonFromPrimaryStorage(String psUuid, List<String> hostnames) throws ApiSenderException { APIRemoveMonFromCephPrimaryStorageMsg msg = new APIRemoveMonFromCephPrimaryStorageMsg(); msg.setUuid(psUuid); msg.setMonHostnames(hostnames); msg.setSession(adminSession); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIRemoveMonFromCephPrimaryStorageEvent evt = sender.send(msg, APIRemoveMonFromCephPrimaryStorageEvent.class); return evt.getInventory(); } public LoadBalancerInventory createLoadBalancer(String name, String vipUuid, List<String> tags, SessionInventory session) throws ApiSenderException { APICreateLoadBalancerMsg msg = new APICreateLoadBalancerMsg(); msg.setName(name); msg.setVipUuid(vipUuid); msg.setSystemTags(tags); msg.setSession(session == null ? adminSession : session); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APICreateLoadBalancerEvent evt = sender.send(msg, APICreateLoadBalancerEvent.class); return evt.getInventory(); } public LoadBalancerListenerInventory createLoadBalancerListener(LoadBalancerListenerInventory inv, SessionInventory session) throws ApiSenderException { return createLoadBalancerListener(inv, null, session); } public LoadBalancerListenerInventory createLoadBalancerListener(LoadBalancerListenerInventory inv, List<String> sysTags, SessionInventory session) throws ApiSenderException { APICreateLoadBalancerListenerMsg msg = new APICreateLoadBalancerListenerMsg(); msg.setResourceUuid(inv.getUuid()); msg.setLoadBalancerUuid(inv.getLoadBalancerUuid()); msg.setName(inv.getName()); msg.setDescription(inv.getDescription()); msg.setInstancePort(inv.getInstancePort()); msg.setLoadBalancerPort(inv.getLoadBalancerPort()); msg.setProtocol(inv.getProtocol()); msg.setSession(session == null ? adminSession : session); msg.setSystemTags(sysTags); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APICreateLoadBalancerListenerEvent evt = sender.send(msg, APICreateLoadBalancerListenerEvent.class); return evt.getInventory(); } public LoadBalancerInventory refreshLoadBalancer(String uuid) throws ApiSenderException { return refreshLoadBalancer(uuid, null); } public LoadBalancerInventory refreshLoadBalancer(String uuid, SessionInventory session) throws ApiSenderException { APIRefreshLoadBalancerMsg msg = new APIRefreshLoadBalancerMsg(); msg.setUuid(uuid); msg.setSession(session == null ? adminSession : session); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIRefreshLoadBalancerEvent evt = sender.send(msg, APIRefreshLoadBalancerEvent.class); return evt.getInventory(); } public LoadBalancerListenerInventory addVmNicToLoadBalancerListener(String listenerUuid, String nicUuid) throws ApiSenderException { return addVmNicToLoadBalancerListener(listenerUuid, nicUuid, null); } public LoadBalancerListenerInventory addVmNicToLoadBalancerListener(String listenerUuid, String nicUuid, SessionInventory session) throws ApiSenderException { APIAddVmNicToLoadBalancerMsg msg = new APIAddVmNicToLoadBalancerMsg(); msg.setVmNicUuids(list(nicUuid)); msg.setListenerUuid(listenerUuid); msg.setSession(session == null ? adminSession : session); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIAddVmNicToLoadBalancerEvent evt = sender.send(msg, APIAddVmNicToLoadBalancerEvent.class); return evt.getInventory(); } public LoadBalancerInventory removeNicFromLoadBalancerListener(String listenerUuid, String nicUuid, SessionInventory session) throws ApiSenderException { APIRemoveVmNicFromLoadBalancerMsg msg = new APIRemoveVmNicFromLoadBalancerMsg(); msg.setListenerUuid(listenerUuid); msg.setVmNicUuids(list(nicUuid)); msg.setSession(session == null ? adminSession : session); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIRemoveVmNicFromLoadBalancerEvent evt = sender.send(msg, APIRemoveVmNicFromLoadBalancerEvent.class); return evt.getInventory(); } public LoadBalancerInventory deleteLoadBalancerListener(String uuid, SessionInventory session) throws ApiSenderException { APIDeleteLoadBalancerListenerMsg msg = new APIDeleteLoadBalancerListenerMsg(); msg.setUuid(uuid); msg.setSession(session == null ? adminSession : session); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIDeleteLoadBalancerListenerEvent evt = sender.send(msg, APIDeleteLoadBalancerListenerEvent.class); return evt.getInventory(); } public void deleteLoadBalancer(String lbUuid, SessionInventory session) throws ApiSenderException { APIDeleteLoadBalancerMsg msg = new APIDeleteLoadBalancerMsg(); msg.setUuid(lbUuid); msg.setSession(session == null ? adminSession : session); ApiSender sender = new ApiSender(); sender.send(msg, APIDeleteLoadBalancerEvent.class); } public APIGetLocalStorageHostDiskCapacityReply getLocalStorageHostCapacity(String psUuid, String huuid) throws ApiSenderException { APIGetLocalStorageHostDiskCapacityMsg msg = new APIGetLocalStorageHostDiskCapacityMsg(); msg.setHostUuid(huuid); msg.setPrimaryStorageUuid(psUuid); msg.setSession(adminSession); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); return sender.call(msg, APIGetLocalStorageHostDiskCapacityReply.class); } public void attachIso(String vmUuid, String isoUuid, SessionInventory session) throws ApiSenderException { APIAttachIsoToVmInstanceMsg msg = new APIAttachIsoToVmInstanceMsg(); msg.setVmInstanceUuid(vmUuid); msg.setIsoUuid(isoUuid); msg.setSession(session == null ? adminSession : session); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); sender.send(msg, APIAttachIsoToVmInstanceEvent.class); } public void detachIso(String vmUuid, SessionInventory session) throws ApiSenderException { APIDetachIsoFromVmInstanceMsg msg = new APIDetachIsoFromVmInstanceMsg(); msg.setVmInstanceUuid(vmUuid); msg.setSession(session == null ? adminSession : session); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); sender.send(msg, APIDetachIsoFromVmInstanceEvent.class); } public VmInstanceInventory recoverVm(String vmUuid, SessionInventory session) throws ApiSenderException { APIRecoverVmInstanceMsg msg = new APIRecoverVmInstanceMsg(); msg.setUuid(vmUuid); msg.setSession(session == null ? adminSession : session); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIRecoverVmInstanceEvent evt = sender.send(msg, APIRecoverVmInstanceEvent.class); return evt.getInventory(); } public void expungeVm(String vmUuid, SessionInventory session) throws ApiSenderException { APIExpungeVmInstanceMsg msg = new APIExpungeVmInstanceMsg(); msg.setUuid(vmUuid); msg.setSession(session == null ? adminSession : session); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); sender.send(msg, APIExpungeVmInstanceEvent.class); } public VolumeInventory recoverVolume(String volUuid, SessionInventory session) throws ApiSenderException { APIRecoverDataVolumeMsg msg = new APIRecoverDataVolumeMsg(); msg.setUuid(volUuid); msg.setSession(session == null ? adminSession : session); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIRecoverDataVolumeEvent evt = sender.send(msg, APIRecoverDataVolumeEvent.class); return evt.getInventory(); } public String getVersion() throws ApiSenderException { APIGetVersionMsg msg = new APIGetVersionMsg(); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIGetVersionReply reply = sender.call(msg, APIGetVersionReply.class); return reply.getVersion(); } public void expungeImage(String imageUuid, List<String> bsUuids, SessionInventory session) throws ApiSenderException { APIExpungeImageMsg msg = new APIExpungeImageMsg(); msg.setImageUuid(imageUuid); msg.setBackupStorageUuids(bsUuids); msg.setSession(session == null ? adminSession : session); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); sender.send(msg, APIExpungeImageEvent.class); } public ImageInventory recoverImage(String imageUuid, List<String> bsUuids, SessionInventory session) throws ApiSenderException { APIRecoverImageMsg msg = new APIRecoverImageMsg(); msg.setImageUuid(imageUuid); msg.setBackupStorageUuids(bsUuids); msg.setSession(session == null ? adminSession : session); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIRecoverImageEvent evt = sender.send(msg, APIRecoverImageEvent.class); return evt.getInventory(); } public void expungeDataVolume(String volumeUuid, SessionInventory session) throws ApiSenderException { APIExpungeDataVolumeMsg msg = new APIExpungeDataVolumeMsg(); msg.setUuid(volumeUuid); msg.setSession(session == null ? adminSession : session); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); sender.send(msg, APIExpungeDataVolumeEvent.class); } public LocalStorageResourceRefInventory localStorageMigrateVolume(String volUuid, String hostUuid, SessionInventory session) throws ApiSenderException { APILocalStorageMigrateVolumeMsg msg = new APILocalStorageMigrateVolumeMsg(); msg.setVolumeUuid(volUuid); msg.setDestHostUuid(hostUuid); msg.setSession(session == null ? adminSession : session); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APILocalStorageMigrateVolumeEvent evt = sender.send(msg, APILocalStorageMigrateVolumeEvent.class); return evt.getInventory(); } public List<HostInventory> getLocalStorageVolumeMigratableHost(String volUuid, SessionInventory session) throws ApiSenderException { APILocalStorageGetVolumeMigratableHostsMsg msg = new APILocalStorageGetVolumeMigratableHostsMsg(); msg.setVolumeUuid(volUuid); msg.setSession(session == null ? adminSession : session); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APILocalStorageGetVolumeMigratableReply reply = sender.call(msg, APILocalStorageGetVolumeMigratableReply.class); return reply.getInventories(); } public VmInstanceInventory setVmBootOrder(String vmUuid, List<String> order, SessionInventory session) throws ApiSenderException { APISetVmBootOrderMsg msg = new APISetVmBootOrderMsg(); msg.setUuid(vmUuid); msg.setBootOrder(order); msg.setSession(session == null ? adminSession : session); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APISetVmBootOrderEvent evt = sender.send(msg, APISetVmBootOrderEvent.class); return evt.getInventory(); } public List<String> getVmBootOrder(String vmUuid, SessionInventory session) throws ApiSenderException { APIGetVmBootOrderMsg msg = new APIGetVmBootOrderMsg(); msg.setUuid(vmUuid); msg.setSession(session == null ? adminSession : session); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIGetVmBootOrderReply reply = sender.call(msg, APIGetVmBootOrderReply.class); return reply.getOrder(); } public LicenseInventory getLicenseInfo() throws ApiSenderException { APIGetLicenseInfoMsg msg = new APIGetLicenseInfoMsg(); msg.setSession(adminSession); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIGetLicenseInfoReply r = sender.call(msg, APIGetLicenseInfoReply.class); return r.getInventory(); } public KVMHostInventory addKvmHost(String name, String mgmtIp, String clusterUuid) throws ApiSenderException { APIAddKVMHostMsg msg = new APIAddKVMHostMsg(); msg.setName(name); msg.setManagementIp(mgmtIp); msg.setClusterUuid(clusterUuid); msg.setUsername("root"); msg.setPassword("password"); msg.setSession(adminSession); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIAddHostEvent evt = sender.send(msg, APIAddHostEvent.class); return (KVMHostInventory) evt.getInventory(); } public Map<String, String> getLicenseCapabilities() throws ApiSenderException { APIGetLicenseCapabilitiesMsg msg = new APIGetLicenseCapabilitiesMsg(); msg.setSession(adminSession); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APIGetLicenseCapabilitiesReply reply = sender.call(msg, APIGetLicenseCapabilitiesReply.class); return reply.getCapabilities(); } public void detachNetworkServicesFromL3Network(String l3Uuid, Map<String, List<String>> services) throws ApiSenderException { APIDetachNetworkServiceFromL3NetworkMsg msg = new APIDetachNetworkServiceFromL3NetworkMsg(); msg.setL3NetworkUuid(l3Uuid); msg.setNetworkServices(services); msg.setSession(adminSession); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); sender.send(msg, APIDetachNetworkServiceFromL3NetworkEvent.class); } public void setHostname(String uuid, String hostname, SessionInventory session) throws ApiSenderException { APISetVmHostnameMsg msg = new APISetVmHostnameMsg(); msg.setUuid(uuid); msg.setHostname(hostname); msg.setSession(session == null ? adminSession : session); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); sender.send(msg, APISetVmHostnameEvent.class); } public void deleteHostname(String uuid, SessionInventory session) throws ApiSenderException { APIDeleteVmHostnameMsg msg = new APIDeleteVmHostnameMsg(); msg.setUuid(uuid); msg.setSession(session == null ? adminSession : session); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); sender.send(msg, APIDeleteVmHostnameEvent.class); } public void setStaticIp(String vmUuid, String l3Uuid, String ip) throws ApiSenderException { APISetVmStaticIpMsg msg = new APISetVmStaticIpMsg(); msg.setVmInstanceUuid(vmUuid); msg.setL3NetworkUuid(l3Uuid); msg.setIp(ip); msg.setSession(adminSession); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); sender.send(msg, APISetVmStaticIpEvent.class); } public void deleteStaticIp(String vmUuid, String l3Uuid) throws ApiSenderException { APIDeleteVmStaticIpMsg msg = new APIDeleteVmStaticIpMsg(); msg.setVmInstanceUuid(vmUuid); msg.setL3NetworkUuid(l3Uuid); msg.setSession(adminSession); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); sender.send(msg, APIDeleteVmStaticIpEvent.class); } public Map<String, String> checkUserPolicy(List<String> apiNames, String userUuid, SessionInventory session) throws ApiSenderException { APICheckApiPermissionMsg msg = new APICheckApiPermissionMsg(); msg.setUserUuid(userUuid); msg.setApiNames(apiNames); msg.setSession(session == null ? adminSession : session); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APICheckApiPermissionReply reply = sender.call(msg, APICheckApiPermissionReply.class); return reply.getInventory(); } public APICalculateAccountSpendingReply calculateSpending(String accountUuid, Long start, Long end, SessionInventory session) throws ApiSenderException { APICalculateAccountSpendingMsg msg = new APICalculateAccountSpendingMsg(); msg.setAccountUuid(accountUuid); msg.setSession(session == null ? adminSession : session); msg.setDateStart(start); msg.setDateEnd(end); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APICalculateAccountSpendingReply reply = sender.call(msg, APICalculateAccountSpendingReply.class); return reply; } public APICalculateAccountSpendingReply calculateSpending(String accountUuid, SessionInventory session) throws ApiSenderException { return calculateSpending(accountUuid, null, null, session); } public PriceInventory createPrice(APICreateResourcePriceMsg msg) throws ApiSenderException { msg.setSession(adminSession); ApiSender sender = new ApiSender(); sender.setTimeout(timeout); APICreateResourcePriceEvent evt = sender.send(msg, APICreateResourcePriceEvent.class); return evt.getInventory(); } }
package com.yueban.architecturedemo.data.model.base; import android.os.Parcel; import android.os.Parcelable; import com.raizlabs.android.dbflow.structure.BaseModel; /** * @author yueban * @date 2017/8/1 * @email fbzhh007@gmail.com */ public class BaseDBModel extends BaseModel implements Parcelable { public static final Creator<BaseDBModel> CREATOR = new Creator<BaseDBModel>() { @Override public BaseDBModel createFromParcel(Parcel source) { return new BaseDBModel(source); } @Override public BaseDBModel[] newArray(int size) { return new BaseDBModel[size]; } }; public BaseDBModel() { } protected BaseDBModel(Parcel in) { } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { } }
package main.reciter.utils; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVPrinter; public class AnalysisCSVWriter { private final CSVFormat format; public AnalysisCSVWriter() { format = CSVFormat.RFC4180.withHeader().withDelimiter(','); } public void write(List<AnalysisObject> list) throws IOException { PrintWriter writer = new PrintWriter("csv_output.csv", "UTF-8"); CSVPrinter printer = new CSVPrinter(writer, format.withDelimiter(',')); printer.printRecord( "Similarity Threshold", "Article ID", "Title", "Journal", "Authors", "Affiliations", "Keywords", "Cluster to which the article was assigned", "Number of articles in the selected cluster", "Cluster ultimately selected in Phase 2 matching", "Status of ReCiter's determination for this article with respect to reference standard"); for (AnalysisObject analysisObject : list) { double similarityThreshold = analysisObject.getSimilarityMeasure(); int articleId = analysisObject.getClusterId(); String title = analysisObject.getReCiterArticle().getArticleTitle().getTitle(); String journal = analysisObject.getReCiterArticle().getJournal().getJournalTitle(); String authors = analysisObject.getReCiterArticle().getArticleCoAuthors().toAuthorCSV(); // String affiliation = analysisObject.getReCiterArticle().getArticleCoAuthors().getAffiliationConcatFormWithComma(); String keywords = analysisObject.getReCiterArticle().getArticleKeywords().getCommaConcatForm(); int clusterId = analysisObject.getClusterId(); int numArticles = analysisObject.getNumArticlesInCluster(); boolean selected = analysisObject.isSelected(); String status = analysisObject.getStatus(); String booleanStatus; if (selected) booleanStatus = "Yes"; else booleanStatus = "No"; printer.printRecord( similarityThreshold, articleId, title, journal, authors, "", keywords, clusterId, numArticles, booleanStatus, status); } printer.close(); writer.close(); } public static void main(String[] args) throws FileNotFoundException, IOException { CSVFormat format = CSVFormat.RFC4180.withHeader().withDelimiter(','); //CSV Write Example using CSVPrinter PrintWriter writer = new PrintWriter("the-file-name.csv", "UTF-8"); CSVPrinter printer = new CSVPrinter(writer, format.withDelimiter(',')); printer.printRecord("ID","Name","Role","Salary"); printer.printRecord("1", "3", "3", "3"); //close the printer printer.close(); writer.close(); } }
package org.ccci.gto.android.common.support.v4.util; import android.view.View; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentActivity; public final class FragmentUtils { private FragmentUtils() {} /** * @deprecated Since v3.7.0, use `findViewById` directly now that it supports a generic type. */ @Nullable @Deprecated public static <T> T findView(@NonNull final Fragment fragment, @NonNull final Class<T> clazz, final int id) { final View root = fragment.getView(); if (root != null) { final View view = root.findViewById(id); if (clazz.isInstance(view)) { return clazz.cast(view); } } return null; } @Nullable public static <T> T getAncestorFragment(@NonNull final Fragment fragment, @NonNull final Class<T> clazz) { Fragment parent = fragment.getParentFragment(); while (parent != null) { if (clazz.isInstance(parent)) { return clazz.cast(parent); } parent = parent.getParentFragment(); } return null; } @Nullable public static <T> T getListener(@NonNull final Fragment fragment, @NonNull final Class<T> clazz) { final Fragment frag = fragment.getParentFragment(); if (clazz.isInstance(frag)) { return clazz.cast(frag); } final FragmentActivity activity = fragment.getActivity(); if (clazz.isInstance(activity)) { return clazz.cast(activity); } return null; } }
package dev.blunch.blunch.activity; import android.content.Intent; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RatingBar; import android.widget.TextView; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.LinkedList; import java.util.List; import dev.blunch.blunch.R; import dev.blunch.blunch.domain.CollaborativeMenu; import dev.blunch.blunch.domain.Dish; import dev.blunch.blunch.domain.User; import dev.blunch.blunch.services.CollaborativeMenuService; import dev.blunch.blunch.services.MenuService; import dev.blunch.blunch.services.ServiceFactory; /** * GetMenuCollaborative Activity * @author albert */ @SuppressWarnings("all") public class GetCollaborativeMenuActivity extends AppCompatActivity { public static final String MENU_ID_KEY = "menuId"; private CollaborativeMenuService collaborativeMenuService; private MenuService menuService; private CollaborativeMenu collaborativeMenu; private List<Dish> suggestedDishes; private List<Dish> offeredDishes; private final String COMA = ","; private TextView userName, localization, hostDishes, suggestions, description, hour, valueCount; private ImageView userPic; private Button join; private RatingBar ratingBar; private Toolbar toolbar; private static String menuId; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_get_collaborative_menu); overridePendingTransition(R.anim.fadein, R.anim.fadeout); toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); if (getIntent().getStringExtra(MENU_ID_KEY) != null) this.menuId = getIntent().getStringExtra(MENU_ID_KEY); collaborativeMenuService = ServiceFactory.getCollaborativeMenuService(getApplicationContext()); menuService = ServiceFactory.getMenuService(getApplicationContext()); collaborativeMenu = collaborativeMenuService.get(GetCollaborativeMenuActivity.this.menuId); suggestedDishes = collaborativeMenuService.getSuggestedDishes(collaborativeMenu.getId()); offeredDishes = collaborativeMenuService.getOfferedDishes(collaborativeMenu.getId()); initialize(); } private void initialize() { userName = (TextView) findViewById(R.id.hostName_getCollaborative); localization = (TextView) findViewById(R.id.hostLocalization_getCollaborative); hostDishes = (TextView) findViewById(R.id.hostDishes_getCollaborative); suggestions = (TextView) findViewById(R.id.suggestions_getCollaborative); description = (TextView) findViewById(R.id.description_getCollaborative); hour = (TextView) findViewById(R.id.hour_getCollaborative); join = (Button) findViewById(R.id.join_getCollaborative); userPic = (ImageView) findViewById(R.id.user_icon); ratingBar = (RatingBar) findViewById(R.id.getValue); valueCount = (TextView) findViewById(R.id.valueCount); findViewById(R.id.valueLayout).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(GetCollaborativeMenuActivity.this, ValorationListActivity.class); intent.putExtra(ValorationListActivity.USER_ID, collaborativeMenu.getAuthor()); startActivity(intent); } }); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); TextView messageCount = (TextView) findViewById(R.id.messagesCount); if(guest() || host()) { long count = menuService.getPendingMessagesCount(this.menuId); if (count > 0) { if (count < 100) messageCount.setText(String.valueOf(count)); else messageCount.setText("+99"); } else messageCount.setVisibility(View.GONE); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(GetCollaborativeMenuActivity.this, ChatActivity.class); intent.putExtra(ChatActivity.MENU_ID, menuId); startActivity(intent); } }); } else{ fab.setVisibility(View.GONE); messageCount.setVisibility(View.GONE); } userName.setText(obtainUserName()); localization.setText(obtainAddress() + ", " + obtainCity()); hostDishes.setText(obtainOfferedDishSingleString()); if (!guest()){ suggestions.setText(obtainSuggestedDishSingleString());} else { suggestions.setVisibility(View.GONE); LinearLayout sug = (LinearLayout) findViewById(R.id.SeSugiere); sug.setVisibility(View.GONE); TextView p = (TextView) findViewById(R.id.offeredTitle_getCollaborative); p.setText("Platos"); Collection<Dish> m = collaborativeMenuService.getMySuggestedDishes(collaborativeMenu.getId()); String sd = ""; for (Dish d : m){ sd += d.getName(); if (d.getAuthor() != null || !d.getAuthor().isEmpty()) sd += " (" + menuService.findUserByEmail(d.getAuthor()).getName().split(" ")[0] + ")"; sd += "\n"; } hostDishes.setText(sd); } description.setText(obtainDescription()); hour.setText(obtainHour()); setRating(); if(host()){ join.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(GetCollaborativeMenuActivity.this, CollaborativePetitionsListActivity.class); intent.putExtra("menuId", menuId); startActivity(intent); } }); join.setText("Peticiones"); } else if(!guest()) { join.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(GetCollaborativeMenuActivity.this, CollaborativeMenuAnswerActivity.class); intent.putExtra("menuId", menuId); startActivity(intent); } }); } else{ join.setVisibility(View.GONE); } userPic.setImageDrawable(getUserPic()); toolbar.setTitle(obtainTitle()); // TODO Set user image: toolbar.setLogo(); setSupportActionBar(toolbar); } private void setRating() { User user = collaborativeMenuService.findUserByEmail(collaborativeMenu.getAuthor()); ratingBar.setRating((float) user.getValorationAverage()); Integer valueCount = user.getValorationNumber(); if (valueCount == 1) this.valueCount.setText("(" + valueCount + " valoración)"); else this.valueCount.setText("(" + valueCount + " valoraciones)"); } private boolean host() { return collaborativeMenuService.imHost(collaborativeMenu.getId()); } private boolean guest() { return collaborativeMenuService.imGuest(collaborativeMenu.getId()); } private Drawable getUserPic() { try { return collaborativeMenuService.findUserByEmail(collaborativeMenu.getAuthor()).getImageRounded(getResources()); } catch (Exception e) { e.printStackTrace(); } return null; } private String obtainUserName() { return collaborativeMenuService.findUserByEmail(collaborativeMenu.getAuthor()).getName(); } private String obtainTitle() { return collaborativeMenu.getName(); } private String obtainAddress() { String[] parts = collaborativeMenu.getLocalization().split(COMA); String result = ""; for (int i = 0; i < parts.length - 1; ++i) { result += parts[i]; } return result; } private String obtainCity() { String[] parts = collaborativeMenu.getLocalization().split(COMA); return parts[parts.length - 1]; } private List<String> obtainSuggestedDishNames() { List<String> list = new LinkedList<>(); for (Dish dish : suggestedDishes) { list.add(dish.getName()); } return list; } private String obtainSuggestedDishSingleString(){ String sd = ""; for (String s : obtainSuggestedDishNames()){ sd += s + "\n"; } if (obtainSuggestedDishNames().size() == 0) { sd = "No quedan platos sugeridos por el huésped"; TextView textView = (TextView) findViewById(R.id.suggestions_getCollaborative); textView.setTypeface(null, Typeface.ITALIC); } return sd; } private List<String> obtainOfferedDishNames() { List<String> list = new LinkedList<>(); for (Dish dish : offeredDishes) { String s = dish.getName(); if (dish.getAuthor() != null || !dish.getAuthor().isEmpty()) s += " (" + menuService.findUserByEmail(dish.getAuthor()).getName().split(" ")[0] + ")"; list.add(s); } return list; } private String obtainOfferedDishSingleString(){ String od= ""; for (String s : obtainOfferedDishNames()){ od += s + "\n"; } return od; } private String obtainDescription() { return "\"" + collaborativeMenu.getDescription() + "\""; } private String obtainHour() { String result = ""; Integer hour, minute; Calendar calendar = Calendar.getInstance(); Date dateStart = collaborativeMenu.getDateStart(); Date dateEnd = collaborativeMenu.getDateEnd(); calendar.setTime(dateStart); String day = String.valueOf(calendar.get(Calendar.DAY_OF_MONTH)); String month = String.valueOf(calendar.get(Calendar.MONTH) + 1); String year = String.valueOf(calendar.get(Calendar.YEAR)); if (calendar.get(Calendar.DAY_OF_MONTH) < 10) day = "0" + day; if (calendar.get(Calendar.MONTH) < 10) month = "0" + month; result += " " + day + "/" + month + "/" + year + "\n"; hour = calendar.get(Calendar.HOUR_OF_DAY); minute = calendar.get(Calendar.MINUTE); if (hour < 10) result += "0"; result += hour + ":"; if (minute < 10) result += "0"; result += minute + " - "; calendar.setTime(dateEnd); hour = calendar.get(Calendar.HOUR_OF_DAY); minute = calendar.get(Calendar.MINUTE); if (hour < 10) result += "0"; result += hour + ":"; if (minute < 10) result += "0"; result += minute; return result; } @Override protected void onRestart() { super.onRestart(); finish(); startActivity(getIntent()); } }
package org.openecard.gui.android.pinmanagement; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.Future; import org.openecard.common.DynamicContext; import org.openecard.gui.ResultStatus; import org.openecard.gui.StepResult; import org.openecard.gui.android.AndroidNavigator; import org.openecard.gui.android.AndroidResult; import org.openecard.gui.android.GuiIfaceReceiver; import org.openecard.gui.definition.InputInfoUnit; import org.openecard.gui.definition.OutputInfoUnit; import org.openecard.gui.definition.Step; import org.openecard.gui.definition.UserConsentDescription; import org.openecard.plugins.pinplugin.GetCardsAndPINStatusAction; import org.openecard.plugins.pinplugin.RecognizedState; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author Sebastian Schuberth * @author Tobias Wich */ public class PINManagementNavigator extends AndroidNavigator { private static final Logger LOG = LoggerFactory.getLogger(PINManagementNavigator.class); private final List<Step> steps; private final GuiIfaceReceiver<PINManagementGuiImpl> ifaceReceiver; private final PINManagementGuiImpl guiService; private int idx = -1; public PINManagementNavigator(UserConsentDescription uc, GuiIfaceReceiver<PINManagementGuiImpl> ifaceReceiver) { this.steps = new ArrayList<>(uc.getSteps()); this.ifaceReceiver = ifaceReceiver; this.guiService = ifaceReceiver.getUiInterface().derefNonblocking(); } @Override public boolean hasNext() { return idx < (steps.size() - 1); } @Override public StepResult current() { // reduce index by one and call next which increases idx by one // --> (-1 + 1 = 0) idx return next(); } @Override public StepResult next() { // if cancel call has been issued, abort the whole process if (this.guiService.isCancelled()) { // prevent index out of bounds int i = idx == -1 ? 0 : idx > steps.size() ? steps.size() - 1 : idx; return new AndroidResult(steps.get(i), ResultStatus.CANCEL, Collections.EMPTY_LIST); } // handle step display idx++; Step pinStep = steps.get(0); return displayAndExecuteBackground(pinStep, () -> { DynamicContext ctx = DynamicContext.getInstance(GetCardsAndPINStatusAction.DYNCTX_INSTANCE_KEY); RecognizedState uiPinState = (RecognizedState) ctx.get(GetCardsAndPINStatusAction.PIN_STATUS); Boolean pinCorrect = (Boolean) ctx.get(GetCardsAndPINStatusAction.PIN_CORRECT); Boolean canCorrect = (Boolean) ctx.get(GetCardsAndPINStatusAction.CAN_CORRECT); Boolean pukCorrect = (Boolean) ctx.get(GetCardsAndPINStatusAction.PUK_CORRECT); if (uiPinState == null || uiPinState == RecognizedState.UNKNOWN) { LOG.error("No pin state received from UI."); return new AndroidResult(pinStep, ResultStatus.CANCEL, Collections.EMPTY_LIST); } // set pin state this.guiService.sendPinStatus(uiPinState); // set result values if any if (pinCorrect != null) { this.guiService.setPinCorrect(pinCorrect); } else if (canCorrect != null) { this.guiService.setCanCorrect(canCorrect); } else if (pukCorrect != null) { this.guiService.setPukCorrect(pukCorrect); } // pin accepted or card blocked if ("success".equals(pinStep.getID())) { return new AndroidResult(pinStep, ResultStatus.OK, Collections.EMPTY_LIST); } else if ("error".equals(pinStep.getID())) { //this.guiService.waitForUserCancel(); return new AndroidResult(pinStep, ResultStatus.CANCEL, Collections.EMPTY_LIST); } // ask user for the pin try { List<OutputInfoUnit> outInfo = this.guiService.getPinResult(pinStep); writeBackValues(pinStep.getInputInfoUnits(), outInfo); return new AndroidResult(pinStep, ResultStatus.OK, outInfo); } catch (InterruptedException ex) { return new AndroidResult(pinStep, ResultStatus.INTERRUPTED, Collections.EMPTY_LIST); } }); } @Override public StepResult previous() { throw new UnsupportedOperationException("Not supported yet."); } @Override public StepResult replaceCurrent(Step step) { steps.set(idx, step); return current(); } @Override public StepResult replaceNext(Step step) { steps.set(idx+1, step); return next(); } @Override public StepResult replacePrevious(Step step) { throw new UnsupportedOperationException("Not supported yet."); } @Override public void setRunningAction(Future<?> action) { // don't care about the action } @Override public void close() { ifaceReceiver.terminate(); } private void writeBackValues(List<InputInfoUnit> inInfo, List<OutputInfoUnit> outInfo) { for (InputInfoUnit infoInUnit : inInfo) { for (OutputInfoUnit infoOutUnit : outInfo) { if (infoInUnit.getID().equals(infoOutUnit.getID())) { infoInUnit.copyContentFrom(infoOutUnit); } } } } }
package com.inet.lib.less; import static com.inet.lib.less.ColorUtils.*; import java.io.IOException; /** * Base expression with value formating. */ abstract class AbstractExpression extends LessObject implements Expression { private String str; /** * Create a new instance. * * @param obj * another LessObject with parse position. * @param str * a string from the parser */ AbstractExpression( LessObject obj, String str ) { super( obj ); this.str = str; } /** * {@inheritDoc} */ @Override public final int getType() { return EXPRESSION; } /** * {@inheritDoc} */ @Override public void appendTo( CssFormatter formatter ) throws IOException { switch( getDataType( formatter ) ) { case BOOLEAN: formatter.append( Boolean.toString( booleanValue( formatter ) ) ); return; case PERCENT: double d = doubleValue( formatter ); formatter.append( d ); formatter.append( '%' ); return; case NUMBER: d = doubleValue( formatter ); formatter.appendValue( d, unit( formatter ) ); return; case COLOR: formatter.appendColor( doubleValue( formatter ), null ); return; case RGBA: double color = doubleValue( formatter ); if( color == 0 && Double.doubleToRawLongBits( color ) == 0 ) { formatter.append( "transparent" ); } else { final double alpha = alpha( color ); if( alpha >= 1 ) { formatter.appendColor( color, null ); } else { formatter.append( "rgba(" ); formatter.append( red( color ) ).append( ',' ).space(); formatter.append( green( color ) ).append( ',' ).space(); formatter.append( blue( color ) ).append( ',' ).space(); formatter.append( alpha ).append( ')' ); } } return; } formatter.append( str ); } /** * {@inheritDoc} */ @Override public String stringValue( CssFormatter formatter ) { try { formatter.addOutput(); appendTo( formatter ); return formatter.releaseOutput(); } catch( IOException ex ) { throw createException( ex ); } } /** * {@inheritDoc} */ @Override public String toString() { return str; } }
package edu.mit.streamjit.impl.compiler; import com.google.common.collect.ImmutableSet; import edu.mit.streamjit.impl.compiler.insts.Instruction; import edu.mit.streamjit.impl.compiler.insts.TerminatorInst; import edu.mit.streamjit.impl.compiler.types.BasicBlockType; import edu.mit.streamjit.util.IntrusiveList; import java.util.Collections; import java.util.Iterator; import java.util.List; /** * * @author Jeffrey Bosboom <jeffreybosboom@gmail.com> * @since 3/6/2013 */ public class BasicBlock extends Value implements Parented<Method> { @IntrusiveList.Previous private BasicBlock previous; @IntrusiveList.Next private BasicBlock next; @ParentedList.Parent private Method parent; private final IntrusiveList<Instruction> instructions = new ParentedList<>(this, Instruction.class); /** * Creates a new, empty BasicBlock not attached to any parent. The Module * is used to get the correct BasicBlockType. * @param module the module this BasicBlock is associated with */ public BasicBlock(Module module) { super(module.types().getBasicBlockType()); } public BasicBlock(Module module, String name) { this(module); setName(name); } @Override public BasicBlockType getType() { return (BasicBlockType)super.getType(); } @Override public Method getParent() { return parent; } public List<Instruction> instructions() { //TODO: figure out how to make this immutable when the parent is //immutable. Note that we add to this list during resolution. return instructions; } public TerminatorInst getTerminator() { if (instructions.isEmpty()) return null; Instruction lastInst = instructions.listIterator(instructions.size()).previous(); return lastInst instanceof TerminatorInst ? (TerminatorInst)lastInst : null; } public Iterable<BasicBlock> predecessors() { return new Iterable<BasicBlock>() { @Override public Iterator<BasicBlock> iterator() { ImmutableSet.Builder<BasicBlock> builder = ImmutableSet.builder(); for (User user : users().elementSet()) if (user instanceof TerminatorInst && ((Instruction)user).getParent() != null) builder.add(((Instruction)user).getParent()); return builder.build().iterator(); } }; } public Iterable<BasicBlock> successors() { TerminatorInst terminator = getTerminator(); return terminator != null ? terminator.successors() : Collections.<BasicBlock>emptyList(); } }
package dev.blunch.blunch.activity; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import dev.blunch.blunch.R; import dev.blunch.blunch.domain.CollaborativeMenu; import dev.blunch.blunch.domain.CollaborativeMenuAnswer; import dev.blunch.blunch.domain.Dish; import dev.blunch.blunch.domain.PaymentMenu; import dev.blunch.blunch.domain.PaymentMenuAnswer; import dev.blunch.blunch.services.CollaborativeMenuService; import dev.blunch.blunch.services.PaymentMenuService; import dev.blunch.blunch.services.ServiceFactory; import dev.blunch.blunch.utils.Repository; public class PaymentPetitionsListActivity extends AppCompatActivity { public static final String ID_PAYMENT_MENU_KEY = "payment_menu_key"; private PaymentMenuService service; private String idMenu; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_payment_petitions_list); final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); View recyclerView = findViewById(R.id.petitions_list); assert recyclerView != null; ((RecyclerView) recyclerView).setAdapter( new SimpleItemRecyclerViewAdapter(new ArrayList<PaymentMenuAnswer>()) ); Intent intent = getIntent(); idMenu = null; if (intent.hasExtra(ID_PAYMENT_MENU_KEY)) { idMenu = intent.getStringExtra(ID_PAYMENT_MENU_KEY); } service = ServiceFactory.getPaymentMenuService(getApplicationContext()); service.setOnChangedListener(new Repository.OnChangedListener() { @Override public void onChanged(EventType type) { if (type.equals(EventType.Full)) { //TODO: posar aixo be quan es tinguin les ids dels menus via intent // PaymentMenu menu = service.get(idMenu); List<PaymentMenu> list= service.getAll(); PaymentMenu menu = service.getAll().get(0); if (menu != null && idMenu == null) { assert toolbar != null; toolbar.setTitle("Petitions for " + menu.getName()); idMenu = menu.getId(); } } } }); service.setPaymentMenuAnswerListener(new Repository.OnChangedListener() { @Override public void onChanged(EventType type) { View recyclerView = findViewById(R.id.petitions_list); assert recyclerView != null; setupRecyclerView((RecyclerView) recyclerView, idMenu); } }); } private void setupRecyclerView(@NonNull RecyclerView recyclerView, String id) { List<PaymentMenuAnswer> petitions = service.getAnswers(id); recyclerView.setAdapter(new SimpleItemRecyclerViewAdapter(petitions)); } public class SimpleItemRecyclerViewAdapter extends RecyclerView.Adapter<SimpleItemRecyclerViewAdapter.ViewHolder> { private final List<PaymentMenuAnswer> mValues; public SimpleItemRecyclerViewAdapter(List<PaymentMenuAnswer> items) { mValues = items; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.petitions_list_content, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(final ViewHolder holder, final int position) { holder.mItem = mValues.get(position); String result = ""; int total = 0; List <Dish> petition = service.getAnswerDishes(holder.mItem.getId()); for (Dish d : petition){ if (d != null) { result += d.getName() + "\n"; total += d.getPrice(); } } holder.mContentView.setText(result); holder.totalView.setText(total+"€"); } private void removeItem(int position) { mValues.remove(position); notifyItemRemoved(position); notifyItemRangeChanged(position, mValues.size()); } @Override public int getItemCount() { return mValues.size(); } public class ViewHolder extends RecyclerView.ViewHolder { public final View mView; public final TextView mContentView; public final TextView totalView; public PaymentMenuAnswer mItem; public ViewHolder(View view) { super(view); mView = view; mContentView = (TextView) view.findViewById(R.id.contentDishes); totalView = (TextView) view.findViewById(R.id.total); } @Override public String toString() { return super.toString() + " '" + mContentView.getText() + "'"; } } } }
package com.peterphi.std.guice.restclient.jaxb.webquery; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlElementRefs; import javax.xml.bind.annotation.XmlType; import java.util.ArrayList; import java.util.List; @XmlType(name = "ConstraintsType") public class WQConstraints implements ConstraintContainer<WQConstraints> { @XmlAttribute public int offset = 0; @XmlAttribute public int limit = 0; @XmlAttribute public boolean computeSize = false; /** * The subclass to constrain the results to */ @XmlAttribute(name = "subclass", required = false) public String subclass = null; /** * The constraints. This group will be implicitly ANDed together */ @XmlElementRefs({@XmlElementRef(type = WQConstraint.class), @XmlElementRef(type = WQGroup.class)}) public List<WQConstraintLine> constraints = new ArrayList<>(); @Override public WQConstraints add(final WQConstraintLine line) { if (line != null) constraints.add(line); return this; } @Override public String toString() { return "WebQueryConstraints{" + "offset=" + offset + ", limit=" + limit + ", computeSize=" + computeSize + ", clazz='" + subclass + '\'' + ", constraints=" + constraints + '}'; } public String toQueryFragment() { StringBuilder sb = new StringBuilder(); toQueryFragment(sb); return sb.toString(); } public void toQueryFragment(StringBuilder sb) { if (constraints.size() > 1) { boolean first = true; for (WQConstraintLine constraint : constraints) { if (!first) sb.append(" AND "); else first = false; constraint.toQueryFragment(sb); } } else if (constraints.size() == 1) { constraints.get(0).toQueryFragment(sb); } } }
package com.kovaciny.primexmodel; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import android.content.Context; import com.kovaciny.database.PrimexDatabaseSchema; import com.kovaciny.database.PrimexSQLiteOpenHelper; import com.kovaciny.helperfunctions.HelperFunction; public class PrimexModel { public PrimexModel(Context context) { mDbHelper = new PrimexSQLiteOpenHelper(context); mLineNumbersList = mDbHelper.getLineNumbers(); if (mLineNumbersList.size() == 0) { throw new RuntimeException("database didn't find any lines"); } mWoNumbersList = mDbHelper.getWoNumbers(); } /* * This section sets up notifying observers about changes. */ public static final String LINE_SPEED_CHANGE_EVENT = "PrimexModel.SPEED_CHANGE"; public static final String SELECTED_LINE_CHANGE_EVENT = "PrimexModel.LINE_CHANGE"; public static final String SELECTED_WO_CHANGE_EVENT = "PrimexModel.WO_CHANGE"; public static final String NEW_WORK_ORDER_EVENT = "PrimexModel.NEW_WORK_ORDER"; public static final String PRODUCT_CHANGE_EVENT = "PrimexModel.NEW_PRODUCT"; public static final String PRODUCTS_PER_MINUTE_CHANGE_EVENT = "PrimexModel.PPM_CHANGE"; public static final String CURRENT_SHEET_COUNT_CHANGE_EVENT = "PrimexModel.SHEET_COUNT_CHANGE"; public static final String TOTAL_SHEET_COUNT_CHANGE_EVENT = "PrimexModel.TOTAL_COUNT_CHANGE"; public static final String CURRENT_SKID_FINISH_TIME_CHANGE_EVENT = "PrimexModel.FINISH_TIME_CHANGE"; public static final String CURRENT_SKID_START_TIME_CHANGE_EVENT = "PrimexModel.START_TIME_CHANGE"; public static final String MINUTES_PER_SKID_CHANGE_EVENT = "PrimexModel.SKID_TIME_CHANGE"; public static final String NUMBER_OF_SKIDS_CHANGE_EVENT = "PrimexModel.NUMBER_OF_SKIDS_CHANGE"; public static final String JOB_FINISH_TIME_CHANGE_EVENT = "PrimexModel.JOB_FINISH_TIME_CHANGE"; public static final String SKID_CHANGE_EVENT = "PrimexModel.SKID_CHANGE"; public static final String TIME_TO_MAXSON_CHANGE_EVENT = "PrimexModel.TIME_TO_MAXSON_CHANGE"; public static final double INCHES_PER_FOOT = 12.0; // Create PropertyChangeSupport to manage listeners and fire events. private final PropertyChangeSupport propChangeSupport = new PropertyChangeSupport(this); // Provide delegating methods to add / remove listeners to / from the support class. public void addPropertyChangeListener(PropertyChangeListener l) { propChangeSupport.addPropertyChangeListener(l); } public void removePropertyChangeListener(PropertyChangeListener l) { propChangeSupport.removePropertyChangeListener(l); } /* * This section holds the different objects and their relation to each other, getters and setters. */ private List<Integer> mLineNumbersList; private List<Integer> mWoNumbersList; private ProductionLine mSelectedLine; private WorkOrder mSelectedWorkOrder; private Skid<Product> mSelectedSkid; private PrimexSQLiteOpenHelper mDbHelper; private Double mProductsPerMinute; private double mMillisToMaxson; private double mNetRate; private double mGrossRate; private long mMinutesPerSkid; public void setSelectedLine (Integer lineNumber) { if (lineNumber == null) throw new NullPointerException("need to select a line"); if (!mLineNumbersList.contains(lineNumber)) throw new NoSuchElementException("Line number not in the list of lines");; int oldLineNumber = hasSelectedLine() ? mSelectedLine.getLineNumber() : -1; if (lineNumber != oldLineNumber) { mSelectedLine = mDbHelper.getLine(lineNumber); int associatedWoNumber = mDbHelper.getWoNumberByLine(lineNumber); if (associatedWoNumber > 0) { setSelectedWorkOrder(associatedWoNumber); } else { //make sure a work order is selected int newWoNumber = mDbHelper.getHighestWoNumber() + 1; addWorkOrder(new WorkOrder(newWoNumber)); setSelectedWorkOrder(newWoNumber); } propChangeSupport.firePropertyChange(SELECTED_LINE_CHANGE_EVENT, oldLineNumber, mSelectedLine.getLineNumber()); } } public void setSelectedWorkOrder(int woNumber) { if (!mWoNumbersList.contains(woNumber)) { throw new NoSuchElementException("Work order number not in the list of work orders, need to add it"); } if (woNumber > 0) { int oldWoNumber = (mSelectedWorkOrder == null) ? 0 : mSelectedWorkOrder.getWoNumber(); WorkOrder lookedUpWo = mDbHelper.getWorkOrder(woNumber); if (lookedUpWo == null) throw new RuntimeException("WorkOrder not found even though it is in woNumbersList"); mSelectedWorkOrder = lookedUpWo; mDbHelper.updateLineWorkOrderLink(mSelectedLine.getLineNumber(), woNumber); List<Skid<Product>> skidList = new ArrayList<Skid<Product>>(); skidList.addAll(mDbHelper.getSkidList(woNumber)); if (!skidList.isEmpty()) mSelectedWorkOrder.setSkidsList(skidList); //this preserves the single-skid list we initialized with changeSkid(mSelectedWorkOrder.getSkidsList().get(0).getSkidNumber()); Product p = mDbHelper.getProduct(woNumber); mSelectedWorkOrder.setProduct(p); propChangeSupport.firePropertyChange(SELECTED_WO_CHANGE_EVENT, oldWoNumber, mSelectedWorkOrder.getWoNumber()); } else throw new IllegalArgumentException("Work order number must be positive"); } //TODO make it so there's not an "add product, add pallet, etc" //imagine a delete work order, a list of work orders and you are at one index of it //don't have a selected skid, it's just your place in the list of skids. protected void addProduct(Product p) { mDbHelper.insertOrReplaceProduct(p, mSelectedWorkOrder.getWoNumber()); } public boolean addWorkOrder(WorkOrder newWo) { if (mDbHelper.insertOrReplaceWorkOrder(newWo) != -1l) { mWoNumbersList.add(newWo.getWoNumber()); propChangeSupport.firePropertyChange(NEW_WORK_ORDER_EVENT, null, newWo); return true; } else return false; } public void setCurrentSpeed (SpeedValues values) { SpeedValues oldValues = mSelectedLine.getSpeedValues(); mSelectedLine.setSpeedValues(values); String[] lineNum = new String[]{String.valueOf(mSelectedLine.getLineNumber())}; mDbHelper.updateColumn(PrimexDatabaseSchema.ProductionLines.TABLE_NAME, PrimexDatabaseSchema.ProductionLines.COLUMN_NAME_SPEED_SETPOINT, PrimexDatabaseSchema.ProductionLines.COLUMN_NAME_LINE_NUMBER + "=?", lineNum, String.valueOf(values.lineSpeedSetpoint)); mDbHelper.updateColumn(PrimexDatabaseSchema.ProductionLines.TABLE_NAME, PrimexDatabaseSchema.ProductionLines.COLUMN_NAME_DIFFERENTIAL_SPEED_SETPOINT, PrimexDatabaseSchema.ProductionLines.COLUMN_NAME_LINE_NUMBER + "=?", lineNum, String.valueOf(values.differentialSpeed)); mDbHelper.updateColumn(PrimexDatabaseSchema.ProductionLines.TABLE_NAME, PrimexDatabaseSchema.ProductionLines.COLUMN_NAME_SPEED_FACTOR, PrimexDatabaseSchema.ProductionLines.COLUMN_NAME_LINE_NUMBER + "=?", lineNum, String.valueOf(values.speedFactor)); //TODO don't use three calls propChangeSupport.firePropertyChange(LINE_SPEED_CHANGE_EVENT, oldValues, values); } public void changeProduct (Product p) { Product oldProduct = mSelectedWorkOrder.getProduct(); mSelectedWorkOrder.setProduct(p); addProduct(p); calculateRates(); calculateTimes(); this.propChangeSupport.firePropertyChange(PRODUCT_CHANGE_EVENT, oldProduct, p); } public void changeSkid(Integer skidNumber) { //TODO this function fires twice in a row. Catch index out of bounds exceptions. Skid<Product> oldSkid = mSelectedSkid; mSelectedSkid = getSelectedWorkOrder().selectSkid(skidNumber); setCurrentCount(mSelectedSkid.getCurrentItems()); setTotalCount(mSelectedSkid.getTotalItems()); mDbHelper.insertOrReplaceSkid(mSelectedSkid, mSelectedWorkOrder.getWoNumber()); propChangeSupport.firePropertyChange(SKID_CHANGE_EVENT, oldSkid, mSelectedSkid); calculateTimes(); } public void saveProduct(Product p) { mDbHelper.insertOrReplaceProduct(p, getSelectedWorkOrder().getWoNumber()); } /* * Saves the selected line number and work order number. */ public void saveState() { if (hasSelectedLine()) { mDbHelper.updateColumn(PrimexDatabaseSchema.ModelState.TABLE_NAME, PrimexDatabaseSchema.ModelState.COLUMN_NAME_SELECTED_LINE, null, null, String.valueOf(getSelectedLine().getLineNumber())); } else { mDbHelper.updateColumn(PrimexDatabaseSchema.ModelState.TABLE_NAME, PrimexDatabaseSchema.ModelState.COLUMN_NAME_SELECTED_LINE, null, null, null); } if (hasSelectedWorkOrder()) { mDbHelper.updateColumn(PrimexDatabaseSchema.ModelState.TABLE_NAME, PrimexDatabaseSchema.ModelState.COLUMN_NAME_SELECTED_WORK_ORDER, null, null, String.valueOf(getSelectedWorkOrder().getWoNumber())); } else { mDbHelper.updateColumn(PrimexDatabaseSchema.ModelState.TABLE_NAME, PrimexDatabaseSchema.ModelState.COLUMN_NAME_SELECTED_WORK_ORDER, null, null, null); } if (hasSelectedProduct()){ saveProduct(mSelectedWorkOrder.getProduct()); } } public void loadState() { String lineNum = mDbHelper.getFieldAsString(PrimexDatabaseSchema.ModelState.TABLE_NAME, PrimexDatabaseSchema.ModelState.COLUMN_NAME_SELECTED_LINE, null); try { if ( (lineNum == null)) { throw new IllegalStateException("line number is null"); } } catch (IllegalStateException e) { setSelectedLine(18); addWorkOrder(new WorkOrder(18)); setSelectedWorkOrder(18); } setSelectedLine(Integer.valueOf(lineNum)); } public void setProductsPerMinute(double spm) { Double oldSpm = mProductsPerMinute; mProductsPerMinute = spm; //TODO this function shouldnt' be allowed! also validity checking. Also this maybe should be for direct setting only? calculateRates(); calculateTimes(); propChangeSupport.firePropertyChange(PRODUCTS_PER_MINUTE_CHANGE_EVENT, oldSpm, spm); } public double getProductsPerMinute() { return mProductsPerMinute; } /* * This function is called whenever relevant properties change. */ protected void calculateRates() { if (hasSelectedProduct()) { Double oldPpm = mProductsPerMinute; mProductsPerMinute = INCHES_PER_FOOT / mSelectedWorkOrder.getProduct().getLength() * mSelectedLine.getLineSpeed(); propChangeSupport.firePropertyChange(PRODUCTS_PER_MINUTE_CHANGE_EVENT, oldPpm, mProductsPerMinute); mNetRate = mProductsPerMinute * mSelectedWorkOrder.getProduct().getWeight(); //TODO gross rate } } public void setCurrentCount (Integer currentCount) { Integer oldCount = mSelectedSkid.getCurrentItems(); mSelectedSkid.setCurrentItems(currentCount); calculateTimes(); propChangeSupport.firePropertyChange(CURRENT_SHEET_COUNT_CHANGE_EVENT, oldCount, currentCount); } public void setTotalCount (Integer totalCount) { Integer oldCount = mSelectedSkid.getTotalItems(); mSelectedSkid.setTotalItems(totalCount); calculateTimes(); propChangeSupport.firePropertyChange(TOTAL_SHEET_COUNT_CHANGE_EVENT, oldCount, totalCount); } public void calculateTimes() { if (mSelectedSkid == null) throw new RuntimeException("Can't calc times without a skid"); if ( (mProductsPerMinute != null) && (mSelectedSkid.getTotalItems() > 0) ) { //TODO this function gets called way too much //calculate total time per skid. long oldMinutes = mSelectedSkid.getMinutesPerSkid(); long newMinutes = mSelectedSkid.calculateMinutesPerSkid(mProductsPerMinute); propChangeSupport.firePropertyChange(MINUTES_PER_SKID_CHANGE_EVENT, oldMinutes, newMinutes); //calculate skid start and finish time Date oldStartTime = mSelectedSkid.getStartTime(); Date newStartTime = mSelectedSkid.calculateStartTime(mProductsPerMinute); Date oldFinishTime = mSelectedSkid.getFinishTime(); Date newFinishTime = mSelectedSkid.calculateFinishTimeWhileRunning(mProductsPerMinute); propChangeSupport.firePropertyChange(CURRENT_SKID_START_TIME_CHANGE_EVENT, oldStartTime, newStartTime); propChangeSupport.firePropertyChange(CURRENT_SKID_FINISH_TIME_CHANGE_EVENT, oldFinishTime, newFinishTime); //calculate job finish times Date oldJobFinishTime = mSelectedWorkOrder.getFinishTime(); Date newJobFinishTime = mSelectedWorkOrder.calculateFinishTimes(mProductsPerMinute); propChangeSupport.firePropertyChange(JOB_FINISH_TIME_CHANGE_EVENT, oldJobFinishTime, newJobFinishTime); } if (mSelectedLine.getLineSpeed() > 0) { double oldMillisToMaxson = mMillisToMaxson; mMillisToMaxson = mSelectedLine.getLineLength() / mSelectedLine.getLineSpeed() * HelperFunction.ONE_MINUTE_IN_MILLIS; propChangeSupport.firePropertyChange(TIME_TO_MAXSON_CHANGE_EVENT, oldMillisToMaxson, mMillisToMaxson); } } public int getDatabaseVersion() { return PrimexSQLiteOpenHelper.DATABASE_VERSION; } public void changeNumberOfSkids(int num) { int oldNum = mSelectedWorkOrder.getNumberOfSkids(); mSelectedWorkOrder.setNumberOfSkids(num); calculateTimes(); //TODO necessary? propChangeSupport.firePropertyChange(NUMBER_OF_SKIDS_CHANGE_EVENT, oldNum, mSelectedWorkOrder.getNumberOfSkids()); } public void closeDb() { mDbHelper.close(); } public boolean hasSelectedLine() { if (mSelectedLine != null) { return true; } else return false; } public boolean hasSelectedWorkOrder(){ if (mSelectedWorkOrder != null) { return true; } else return false; } public boolean hasSelectedProduct() { return mSelectedWorkOrder.hasProduct(); } public ProductionLine getSelectedLine() { return mSelectedLine; } public WorkOrder getSelectedWorkOrder() { return mSelectedWorkOrder; } public List<Integer> getLineNumbers() { return mLineNumbersList; } public List<Integer> getWoNumbers() { return mDbHelper.getWoNumbers(); } public int getHighestWoNumber() { return mDbHelper.getHighestWoNumber(); } public void clearWoNumbers() { mDbHelper.clearWorkOrders(); } }
package edu.mit.streamjit.impl.compiler2; import com.google.common.base.Function; import com.google.common.collect.ContiguousSet; import com.google.common.collect.DiscreteDomain; import com.google.common.collect.FluentIterable; import com.google.common.collect.HashBasedTable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Iterables; import com.google.common.collect.Maps; import com.google.common.collect.Range; import com.google.common.collect.Sets; import com.google.common.collect.Table; import com.google.common.math.IntMath; import com.google.common.math.LongMath; import com.google.common.primitives.Ints; import com.google.common.primitives.Primitives; import edu.mit.streamjit.api.DuplicateSplitter; import edu.mit.streamjit.api.Joiner; import edu.mit.streamjit.api.RoundrobinJoiner; import edu.mit.streamjit.api.RoundrobinSplitter; import edu.mit.streamjit.api.Splitter; import edu.mit.streamjit.api.StreamCompilationFailedException; import edu.mit.streamjit.api.StreamCompiler; import edu.mit.streamjit.api.WeightedRoundrobinJoiner; import edu.mit.streamjit.api.WeightedRoundrobinSplitter; import edu.mit.streamjit.api.Worker; import edu.mit.streamjit.impl.blob.Blob; import edu.mit.streamjit.impl.blob.Blob.Token; import edu.mit.streamjit.impl.blob.Buffer; import edu.mit.streamjit.impl.blob.DrainData; import edu.mit.streamjit.impl.common.BlobHostStreamCompiler; import edu.mit.streamjit.impl.common.Configuration; import edu.mit.streamjit.impl.common.Configuration.IntParameter; import edu.mit.streamjit.impl.common.Configuration.SwitchParameter; import edu.mit.streamjit.impl.common.Workers; import edu.mit.streamjit.impl.compiler.Schedule; import edu.mit.streamjit.impl.compiler2.Compiler2BlobHost.DrainInstruction; import edu.mit.streamjit.impl.compiler2.Compiler2BlobHost.ReadInstruction; import edu.mit.streamjit.impl.compiler2.Compiler2BlobHost.WriteInstruction; import edu.mit.streamjit.test.Benchmark; import edu.mit.streamjit.test.Benchmarker; import edu.mit.streamjit.test.apps.fmradio.FMRadio; import edu.mit.streamjit.test.regression.Reg20131116_104433_226; import edu.mit.streamjit.test.sanity.PipelineSanity; import edu.mit.streamjit.test.sanity.SplitjoinComputeSanity; import edu.mit.streamjit.util.CollectionUtils; import edu.mit.streamjit.util.Combinators; import static edu.mit.streamjit.util.Combinators.*; import static edu.mit.streamjit.util.LookupUtils.findStatic; import edu.mit.streamjit.util.Pair; import edu.mit.streamjit.util.bytecode.Module; import edu.mit.streamjit.util.bytecode.ModuleClassLoader; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.math.RoundingMode; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NavigableSet; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.atomic.AtomicInteger; /** * * @author Jeffrey Bosboom <jeffreybosboom@gmail.com> * @since 9/22/2013 */ public class Compiler2 { public static final ImmutableSet<Class<?>> REMOVABLE_WORKERS = ImmutableSet.<Class<?>>of( RoundrobinSplitter.class, WeightedRoundrobinSplitter.class, DuplicateSplitter.class, RoundrobinJoiner.class, WeightedRoundrobinJoiner.class); private static final MethodHandles.Lookup LOOKUP = MethodHandles.lookup(); private static final AtomicInteger PACKAGE_NUMBER = new AtomicInteger(); private final ImmutableSet<Worker<?, ?>> workers; private final ImmutableSet<ActorArchetype> archetypes; private final NavigableSet<Actor> actors; private ImmutableSortedSet<ActorGroup> groups; private ImmutableSortedSet<WorkerActor> actorsToBeRemoved; private final Configuration config; private final int maxNumCores; private final DrainData initialState; private final ImmutableMap<Token, ImmutableList<Object>> initialStateDataMap; private final Set<Storage> storage; private ImmutableMap<ActorGroup, Integer> externalSchedule; private final Module module = new Module(); private ImmutableMap<ActorGroup, Integer> initSchedule; /** * ConcreteStorage instances used during initialization (bound into the * initialization code). */ private ImmutableMap<Storage, ConcreteStorage> initStorage; /** * ConcreteStorage instances used during the steady-state (bound into the * steady-state code). */ private ImmutableMap<Storage, ConcreteStorage> steadyStateStorage; /** * Code to run the initialization schedule. (Initialization is * single-threaded.) */ private MethodHandle initCode; /** * Code to run the steady state schedule. The blob host takes care of * filling/flushing buffers, adjusting storage and the global barrier. */ private ImmutableList<MethodHandle> steadyStateCode; private final List<ReadInstruction> initReadInstructions = new ArrayList<>(); private final List<WriteInstruction> initWriteInstructions = new ArrayList<>(); private final List<Runnable> migrationInstructions = new ArrayList<>(); private final List<ReadInstruction> readInstructions = new ArrayList<>(); private final List<WriteInstruction> writeInstructions = new ArrayList<>(); private final List<DrainInstruction> drainInstructions = new ArrayList<>(); public Compiler2(Set<Worker<?, ?>> workers, Configuration config, int maxNumCores, DrainData initialState) { this.workers = ImmutableSet.copyOf(workers); Map<Class<?>, ActorArchetype> archetypesBuilder = new HashMap<>(); Map<Worker<?, ?>, WorkerActor> workerActors = new HashMap<>(); for (Worker<?, ?> w : workers) { @SuppressWarnings("unchecked") Class<? extends Worker<?, ?>> wClass = (Class<? extends Worker<?, ?>>)w.getClass(); if (archetypesBuilder.get(wClass) == null) archetypesBuilder.put(wClass, new ActorArchetype(wClass, module)); WorkerActor actor = new WorkerActor(w, archetypesBuilder.get(wClass)); workerActors.put(w, actor); } this.archetypes = ImmutableSet.copyOf(archetypesBuilder.values()); Map<Token, TokenActor> tokenActors = new HashMap<>(); Table<Actor, Actor, Storage> storageTable = HashBasedTable.create(); int[] inputTokenId = new int[]{Integer.MIN_VALUE}, outputTokenId = new int[]{Integer.MAX_VALUE}; for (WorkerActor a : workerActors.values()) a.connect(ImmutableMap.copyOf(workerActors), tokenActors, storageTable, inputTokenId, outputTokenId); this.actors = new TreeSet<>(); this.actors.addAll(workerActors.values()); this.actors.addAll(tokenActors.values()); this.storage = new HashSet<>(storageTable.values()); this.config = config; this.maxNumCores = maxNumCores; this.initialState = initialState; ImmutableMap.Builder<Token, ImmutableList<Object>> initialStateDataMapBuilder = ImmutableMap.builder(); if (initialState != null) { for (Table.Cell<Actor, Actor, Storage> cell : storageTable.cellSet()) { Token tok; if (cell.getRowKey() instanceof TokenActor) tok = ((TokenActor)cell.getRowKey()).token(); else if (cell.getColumnKey() instanceof TokenActor) tok = ((TokenActor)cell.getColumnKey()).token(); else tok = new Token(((WorkerActor)cell.getRowKey()).worker(), ((WorkerActor)cell.getColumnKey()).worker()); ImmutableList<Object> data = initialState.getData(tok); if (data != null && !data.isEmpty()) { initialStateDataMapBuilder.put(tok, data); cell.getValue().initialData().add(Pair.make(data, MethodHandles.identity(int.class))); } } } this.initialStateDataMap = initialStateDataMapBuilder.build(); } public Blob compile() { findRemovals(); fuse(); schedule(); // identityRemoval(); splitterRemoval(); joinerRemoval(); // unbox(); generateArchetypalCode(); createInitCode(); createSteadyStateCode(); return instantiateBlob(); } private void findRemovals() { ImmutableSortedSet.Builder<WorkerActor> builder = ImmutableSortedSet.naturalOrder(); for (WorkerActor a : Iterables.filter(actors, WorkerActor.class)) { SwitchParameter<Boolean> param = config.getParameter("remove"+a.id(), SwitchParameter.class, Boolean.class); if (param != null && param.getValue()) { assert REMOVABLE_WORKERS.contains(a.worker().getClass()) : a; builder.add(a); } } this.actorsToBeRemoved = builder.build(); } /** * Fuses actors into groups as directed by the configuration. */ private void fuse() { List<ActorGroup> actorGroups = new ArrayList<>(); for (Actor a : actors) actorGroups.add(ActorGroup.of(a)); //Fuse as much as possible. just_fused: do { try_fuse: for (Iterator<ActorGroup> it = actorGroups.iterator(); it.hasNext();) { ActorGroup g = it.next(); if (g.isTokenGroup()) continue try_fuse; for (ActorGroup pg : g.predecessorGroups()) if (pg.isTokenGroup()) continue try_fuse; if (g.isPeeking() || g.predecessorGroups().size() > 1) continue try_fuse; for (Storage s : g.inputs()) if (!s.initialData().isEmpty()) continue try_fuse; String paramName = String.format("fuse%d", g.id()); SwitchParameter<Boolean> fuseParam = config.getParameter(paramName, SwitchParameter.class, Boolean.class); if (!fuseParam.getValue()) continue try_fuse; ActorGroup gpred = Iterables.getOnlyElement(g.predecessorGroups()); ActorGroup fusedGroup = ActorGroup.fuse(g, gpred); it.remove(); actorGroups.remove(gpred); actorGroups.add(fusedGroup); continue just_fused; } break; } while (true); this.groups = ImmutableSortedSet.copyOf(actorGroups); } /** * Computes each group's internal schedule and the external schedule. */ private void schedule() { for (ActorGroup g : groups) internalSchedule(g); externalSchedule(); initSchedule(); } private void externalSchedule() { Schedule.Builder<ActorGroup> scheduleBuilder = Schedule.builder(); scheduleBuilder.addAll(groups); for (ActorGroup g : groups) { for (Storage e : g.outputs()) { Actor upstream = Iterables.getOnlyElement(e.upstream()); Actor downstream = Iterables.getOnlyElement(e.downstream()); ActorGroup other = downstream.group(); int upstreamAdjust = g.schedule().get(upstream); int downstreamAdjust = other.schedule().get(downstream); scheduleBuilder.connect(g, other) .push(e.push() * upstreamAdjust) .pop(e.pop() * downstreamAdjust) .peek(e.peek() * downstreamAdjust) .bufferExactly(0); } } scheduleBuilder.multiply(config.getParameter("multiplier", IntParameter.class).getValue()); try { externalSchedule = scheduleBuilder.build().getSchedule(); } catch (Schedule.ScheduleException ex) { throw new StreamCompilationFailedException("couldn't find external schedule", ex); } } /** * Computes the internal schedule for the given group. */ private void internalSchedule(ActorGroup g) { Schedule.Builder<Actor> scheduleBuilder = Schedule.builder(); scheduleBuilder.addAll(g.actors()); for (Storage s : g.internalEdges()) { scheduleBuilder.connect(Iterables.getOnlyElement(s.upstream()), Iterables.getOnlyElement(s.downstream())) .push(s.push()) .pop(s.pop()) .peek(s.peek()) .bufferExactly(0); } try { Schedule<Actor> schedule = scheduleBuilder.build(); g.setSchedule(schedule.getSchedule()); } catch (Schedule.ScheduleException ex) { throw new StreamCompilationFailedException("couldn't find internal schedule for group "+g.id(), ex); } } private void initSchedule() { Schedule.Builder<ActorGroup> scheduleBuilder = Schedule.builder(); scheduleBuilder.addAll(groups); for (Storage s : storage) { if (s.isInternal()) continue; Actor upstream = Iterables.getOnlyElement(s.upstream()), downstream = Iterables.getOnlyElement(s.downstream()); int upstreamAdjust = upstream.group().schedule().get(upstream); int downstreamAdjust = downstream.group().schedule().get(downstream); int throughput, excessPeeks; //TODO: avoid double-buffering token groups here? if (actorsToBeRemoved.contains(downstream) && false) throughput = excessPeeks = 0; else { throughput = s.push() * upstreamAdjust * externalSchedule.get(upstream.group()); excessPeeks = Math.max(s.peek() - s.pop(), 0); } int initialDataSize = Iterables.getOnlyElement(s.initialData(), new Pair<>(ImmutableList.<Object>of(), (MethodHandle)null)).first.size(); scheduleBuilder.connect(upstream.group(), downstream.group()) .push(s.push() * upstreamAdjust) .pop(s.pop() * downstreamAdjust) .peek(s.peek() * downstreamAdjust) .bufferAtLeast(throughput + excessPeeks - initialDataSize); } try { Schedule<ActorGroup> schedule = scheduleBuilder.build(); this.initSchedule = schedule.getSchedule(); } catch (Schedule.ScheduleException ex) { throw new StreamCompilationFailedException("couldn't find init schedule", ex); } } private void splitterRemoval() { for (WorkerActor splitter : actorsToBeRemoved) { if (!(splitter.worker() instanceof Splitter)) continue; List<MethodHandle> transfers = splitterTransferFunctions(splitter); Storage survivor = Iterables.getOnlyElement(splitter.inputs()); //Remove all instances of splitter, not just the first. survivor.downstream().removeAll(ImmutableList.of(splitter)); MethodHandle Sin = Iterables.getOnlyElement(splitter.inputIndexFunctions()); for (int i = 0; i < splitter.outputs().size(); ++i) { Storage victim = splitter.outputs().get(i); MethodHandle t = transfers.get(i); MethodHandle t2 = MethodHandles.filterReturnValue(t, Sin); for (Actor a : victim.downstream()) { List<Storage> inputs = a.inputs(); List<MethodHandle> inputIndices = a.inputIndexFunctions(); for (int j = 0; j < inputs.size(); ++j) if (inputs.get(j).equals(victim)) { inputs.set(j, survivor); inputIndices.set(j, MethodHandles.filterReturnValue(t2, inputIndices.get(j))); survivor.downstream().add(a); } } //TODO: victim initial data storage.remove(victim); } removeActor(splitter); } } /** * Returns transfer functions for the given splitter. * * A splitter has one transfer function for each output that maps logical * output indices to logical input indices (representing the splitter's * distribution pattern). * @param a an actor * @return transfer functions, or null */ private List<MethodHandle> splitterTransferFunctions(WorkerActor a) { assert REMOVABLE_WORKERS.contains(a.worker().getClass()) : a.worker().getClass(); if (a.worker() instanceof RoundrobinSplitter || a.worker() instanceof WeightedRoundrobinSplitter) { int[] weights = new int[a.outputs().size()]; for (int i = 0; i < weights.length; ++i) weights[i] = a.push(i); int[] weightPrefixSum = new int[weights.length + 1]; for (int i = 1; i < weightPrefixSum.length; ++i) weightPrefixSum[i] = weightPrefixSum[i-1] + weights[i-1]; int N = weightPrefixSum[weightPrefixSum.length-1]; //t_x(i) = N(i/w[x]) + sum_0_x-1{w} + (i mod w[x]) //where the first two terms select a "window" and the third is the //index into that window. ImmutableList.Builder<MethodHandle> transfer = ImmutableList.builder(); for (int x = 0; x < a.outputs().size(); ++x) transfer.add(MethodHandles.insertArguments(ROUNDROBIN_TRANSFER_FUNCTION, 0, weights[x], weightPrefixSum[x], N)); return transfer.build(); } else if (a.worker() instanceof DuplicateSplitter) { return Collections.nCopies(a.outputs().size(), MethodHandles.identity(int.class)); } else throw new AssertionError(); } private void joinerRemoval() { for (WorkerActor joiner : actorsToBeRemoved) { if (!(joiner.worker() instanceof Joiner)) continue; List<MethodHandle> transfers = joinerTransferFunctions(joiner); Storage survivor = Iterables.getOnlyElement(joiner.outputs()); //Remove all instances of joiner, not just the first. survivor.upstream().removeAll(ImmutableList.of(joiner)); MethodHandle Jout = Iterables.getOnlyElement(joiner.outputIndexFunctions()); for (int i = 0; i < joiner.inputs().size(); ++i) { Storage victim = joiner.inputs().get(i); MethodHandle t = transfers.get(i); MethodHandle t2 = MethodHandles.filterReturnValue(t, Jout); for (Actor a : victim.upstream()) { List<Storage> outputs = a.outputs(); List<MethodHandle> outputIndices = a.outputIndexFunctions(); for (int j = 0; j < outputs.size(); ++j) if (outputs.get(j).equals(victim)) { outputs.set(j, survivor); outputIndices.set(j, MethodHandles.filterReturnValue(t2, outputIndices.get(j))); survivor.upstream().add(a); } } //TODO: victim initial data storage.remove(victim); } System.out.println("removed "+joiner); removeActor(joiner); } } private List<MethodHandle> joinerTransferFunctions(WorkerActor a) { assert REMOVABLE_WORKERS.contains(a.worker().getClass()) : a.worker().getClass(); if (a.worker() instanceof RoundrobinJoiner || a.worker() instanceof WeightedRoundrobinJoiner) { //TODO: factor out this duplicate code -- all we need is the weights array int[] weights = new int[a.inputs().size()]; for (int i = 0; i < weights.length; ++i) weights[i] = a.pop(i); int[] weightPrefixSum = new int[weights.length + 1]; for (int i = 1; i < weightPrefixSum.length; ++i) weightPrefixSum[i] = weightPrefixSum[i-1] + weights[i-1]; int N = weightPrefixSum[weightPrefixSum.length-1]; //t_x(i) = N(i/w[x]) + sum_0_x-1{w} + (i mod w[x]) //where the first two terms select a "window" and the third is the //index into that window. ImmutableList.Builder<MethodHandle> transfer = ImmutableList.builder(); for (int x = 0; x < a.inputs().size(); ++x) transfer.add(MethodHandles.insertArguments(ROUNDROBIN_TRANSFER_FUNCTION, 0, weights[x], weightPrefixSum[x], N)); return transfer.build(); } else throw new AssertionError(); } private final MethodHandle ROUNDROBIN_TRANSFER_FUNCTION = findStatic(LOOKUP, Compiler2.class, "_roundrobinTransferFunction", int.class, int.class, int.class, int.class, int.class); //TODO: build this directly out of MethodHandles? private static int _roundrobinTransferFunction(int weight, int prefixSum, int N, int i) { return N*(i/weight) + prefixSum + IntMath.mod(i, weight); } /** * Removes an Actor from this compiler's data structures. The Actor should * already have been unlinked from the graph (no incoming edges); this takes * care of removing it from the actors set, its actor group (possibly * removing the group if it's now empty), and the schedule. * @param a the actor to remove */ private void removeActor(Actor a) { assert actors.contains(a) : a; actors.remove(a); ActorGroup g = a.group(); g.remove(a); if (g.actors().isEmpty()) { groups = ImmutableSortedSet.copyOf(Sets.difference(groups, ImmutableSet.of(g))); externalSchedule = ImmutableMap.copyOf(Maps.difference(externalSchedule, ImmutableMap.of(g, 0)).entriesOnlyOnLeft()); } } //<editor-fold defaultstate="collapsed" desc="Unimplemented optimization stuff"> // /** // * Removes Identity instances from the graph, unless doing so would make the // * graph empty. // */ // private void identityRemoval() { // //TODO: remove from group, possibly removing the group if it becomes empty // for (Iterator<Actor> iter = actors.iterator(); iter.hasNext();) { // if (actors.size() == 1) // break; // Actor actor = iter.next(); // if (!actor.archetype().workerClass().equals(Identity.class)) // continue; // iter.remove(); // assert actor.predecessors().size() == 1 && actor.successors().size() == 1; // Object upstream = actor.predecessors().get(0), downstream = actor.successors().get(0); // if (upstream instanceof Actor) // replace(((Actor)upstream).successors(), actor, downstream); // if (downstream instanceof Actor) // replace(((Actor)downstream).predecessors(), actor, upstream); // //No index function changes required for Identity actors. // private static int replace(List<Object> list, Object target, Object replacement) { // int replacements = 0; // for (int i = 0; i < list.size(); ++i) // if (Objects.equals(list.get(0), target)) { // list.set(i, replacement); // ++replacements; // return replacements; // /** // * Symbolically unboxes a Storage if its common type is a wrapper type and // * all the connected Actors support unboxing. // */ // private void unbox() { // next_storage: for (Storage s : storage) { // Class<?> commonType = s.commonType(); // if (!Primitives.isWrapperType(commonType)) continue; // for (Object o : s.upstream()) // if (o instanceof Actor && !((Actor)o).archetype().canUnboxOutput()) // continue next_storage; // for (Object o : s.downstream()) // if (o instanceof Actor && !((Actor)o).archetype().canUnboxInput()) // continue next_storage; // s.setType(Primitives.unwrap(s.commonType())); //</editor-fold> private void generateArchetypalCode() { String packageName = "compiler"+PACKAGE_NUMBER.getAndIncrement(); ModuleClassLoader mcl = new ModuleClassLoader(module); for (ActorArchetype archetype : archetypes) archetype.generateCode(packageName, mcl); } private void createInitCode() { ImmutableMap<Actor, ImmutableList<MethodHandle>> indexFxnBackup = adjustOutputIndexFunctions(new Function<Storage, Set<Integer>>() { @Override public Set<Integer> apply(Storage input) { return input.indicesLiveBeforeInit(); } }); computeLiveness(); this.initStorage = createExternalStorage(MapConcreteStorage.initFactory()); initReadInstructions.add(new InitDataReadInstruction(initStorage, initialStateDataMap)); /** * During init, all (nontoken) groups are assigned to the same Core in * topological order (via the ordering on ActorGroups). At the same * time we build the token init schedule information required by the * blob host. */ Core initCore = new Core(storage, initStorage, MapConcreteStorage.initFactory()); for (ActorGroup g : groups) if (!g.isTokenGroup()) initCore.allocate(g, Range.closedOpen(0, initSchedule.get(g))); else { assert g.actors().size() == 1; TokenActor ta = (TokenActor)g.actors().iterator().next(); assert g.schedule().get(ta) == 1; ConcreteStorage storage = initStorage.get(Iterables.getOnlyElement(ta.isInput() ? g.outputs() : g.inputs())); int executions = initSchedule.get(g); if (ta.isInput()) initReadInstructions.add(new TokenReadInstruction(g, storage, executions)); else initWriteInstructions.add(new TokenWriteInstruction(g, storage, executions)); } this.initCode = initCore.code(); restoreOutputIndexFunctions(indexFxnBackup); } private void createSteadyStateCode() { for (Actor a : actors) { for (int i = 0; i < a.outputs().size(); ++i) { Storage s = a.outputs().get(i); if (s.isInternal()) continue; int itemsWritten = a.push(i) * initSchedule.get(a.group()) * a.group().schedule().get(a); a.outputIndexFunctions().set(i, MethodHandles.filterArguments( a.outputIndexFunctions().get(i), 0, Combinators.add(MethodHandles.identity(int.class), itemsWritten))); } for (int i = 0; i < a.inputs().size(); ++i) { Storage s = a.inputs().get(i); if (s.isInternal()) continue; int itemsRead = a.pop(i) * initSchedule.get(a.group()) * a.group().schedule().get(a); a.inputIndexFunctions().set(i, MethodHandles.filterArguments( a.inputIndexFunctions().get(i), 0, Combinators.add(MethodHandles.identity(int.class), itemsRead))); } } for (Storage s : storage) s.computeSteadyStateRequirements(externalSchedule); this.steadyStateStorage = createExternalStorage(CircularArrayConcreteStorage.factory()); List<Core> ssCores = new ArrayList<>(maxNumCores); for (int i = 0; i < maxNumCores; ++i) ssCores.add(new Core(storage, steadyStateStorage, CircularArrayConcreteStorage.factory())); for (ActorGroup g : groups) if (!g.isTokenGroup()) allocateGroup(g, ssCores); else { assert g.actors().size() == 1; TokenActor ta = (TokenActor)g.actors().iterator().next(); assert g.schedule().get(ta) == 1; ConcreteStorage storage = steadyStateStorage.get(Iterables.getOnlyElement(ta.isInput() ? g.outputs() : g.inputs())); int executions = externalSchedule.get(g); if (ta.isInput()) readInstructions.add(new TokenReadInstruction(g, storage, executions)); else writeInstructions.add(new TokenWriteInstruction(g, storage, executions)); } ImmutableList.Builder<MethodHandle> steadyStateCodeBuilder = ImmutableList.builder(); for (Core c : ssCores) if (!c.isEmpty()) steadyStateCodeBuilder.add(c.code()); this.steadyStateCode = steadyStateCodeBuilder.build(); /** * Create migration instructions: Runnables that move live items from * initialization to steady-state storage. */ for (Storage s : initStorage.keySet()) migrationInstructions.add(new MigrationInstruction( s, initStorage.get(s), steadyStateStorage.get(s))); createDrainInstructions(); } /** * Allocates executions of the given group to the given cores (i.e., * performs data-parallel fission). * @param g the group to fiss * @param cores the cores to fiss over, subject to the configuration */ private void allocateGroup(ActorGroup g, List<Core> cores) { Range<Integer> toBeAllocated = Range.closedOpen(0, externalSchedule.get(g)); for (int core = 0; core < cores.size() && !toBeAllocated.isEmpty(); ++core) { String name = String.format("node%dcore%diter", g.id(), core); IntParameter parameter = config.getParameter(name, IntParameter.class); if (parameter == null || parameter.getValue() == 0) continue; //If the node is stateful, we must put all allocations on the //same core. Arbitrarily pick the first core with an allocation. //(If no cores have an allocation, we'll put them on core 0 below.) int min = toBeAllocated.lowerEndpoint(); Range<Integer> allocation = g.isStateful() ? toBeAllocated : toBeAllocated.intersection(Range.closedOpen(min, min + parameter.getValue())); cores.get(core).allocate(g, allocation); toBeAllocated = Range.closedOpen(allocation.upperEndpoint(), toBeAllocated.upperEndpoint()); } //If we have iterations left over not assigned to a core, //arbitrarily put them on core 0. if (!toBeAllocated.isEmpty()) cores.get(0).allocate(g, toBeAllocated); } /** * Create drain instructions, which collect live items from steady-state * storage when draining. */ private void createDrainInstructions() { for (Actor a : actors) { for (int i = 0; i < a.inputs().size(); ++i) { Storage s = a.inputs().get(i); if (s.isInternal()) continue; ImmutableSortedSet<Integer> liveIndices = s.indicesLiveDuringSteadyState(); ImmutableSortedSet.Builder<Integer> drainableIndicesBuilder = ImmutableSortedSet.naturalOrder(); for (int logicalIndex = 0; ; ++logicalIndex) { int physicalIndex = a.translateInputIndex(i, logicalIndex); if (liveIndices.contains(physicalIndex)) drainableIndicesBuilder.add(physicalIndex); else break; //TODO: assumes strong monotonicity. maybe needs to look at SS iteration units? } ImmutableSortedSet<Integer> drainableIndices = drainableIndicesBuilder.build(); if (drainableIndices.isEmpty()) continue; //If the indices are contiguous, minimize storage by storing them as a range. if (drainableIndices.last() - drainableIndices.first() + 1 == drainableIndices.size()) drainableIndices = ContiguousSet.create(Range.closed(drainableIndices.first(), drainableIndices.last()), DiscreteDomain.integers()); Token token; if (a instanceof WorkerActor) { Worker<?, ?> w = ((WorkerActor)a).worker(); token = a.id() == 0 ? Token.createOverallInputToken(w) : new Token(Workers.getPredecessors(w).get(i), w); } else token = ((TokenActor)a).token(); drainInstructions.add(new XDrainInstruction(token, steadyStateStorage.get(s), drainableIndices)); } } } //<editor-fold defaultstate="collapsed" desc="Output index function adjust/restore"> /** * Adjust output index functions to avoid overwriting items in external * storage. For any actor writing to external storage, we find the * first item that doesn't hit the live index set and add that many * (making that logical item 0 for writers). * @param liveIndexExtractor a function that computes the relevant live * index set for the given external storage * @return the old output index functions, to be restored later */ private ImmutableMap<Actor, ImmutableList<MethodHandle>> adjustOutputIndexFunctions(Function<Storage, Set<Integer>> liveIndexExtractor) { ImmutableMap.Builder<Actor, ImmutableList<MethodHandle>> backup = ImmutableMap.builder(); for (Actor a : actors) { backup.put(a, ImmutableList.copyOf(a.outputIndexFunctions())); for (int i = 0; i < a.outputs().size(); ++i) { Storage s = a.outputs().get(i); if (s.isInternal()) continue; Set<Integer> liveIndices = liveIndexExtractor.apply(s); assert liveIndices != null : s +" "+liveIndexExtractor; int offset = 0; while (liveIndices.contains(a.translateOutputIndex(i, offset))) ++offset; //Check future indices are also open (e.g., that we aren't //alternating hole/not-hole). for (int check = 0; check < 100; ++check) assert !liveIndices.contains(a.translateOutputIndex(i, offset + check)) : check; a.outputIndexFunctions().set(i, Combinators.add(a.outputIndexFunctions().get(i), offset)); } } return backup.build(); } /** * Restores output index functions from a backup returned from * {@link #adjustOutputIndexFunctions(com.google.common.base.Function)}. * @param backup the backup to restore */ private void restoreOutputIndexFunctions(ImmutableMap<Actor, ImmutableList<MethodHandle>> backup) { for (Actor a : actors) { ImmutableList<MethodHandle> oldFxns = backup.get(a); assert oldFxns != null : "no backup for "+a; assert oldFxns.size() == a.outputIndexFunctions().size() : "backup for "+a+" is wrong size"; Collections.copy(a.outputIndexFunctions(), oldFxns); } } //</editor-fold> private ImmutableMap<Storage, ConcreteStorage> createExternalStorage(StorageFactory factory) { ImmutableMap.Builder<Storage, ConcreteStorage> builder = ImmutableMap.builder(); for (Storage s : storage) if (!s.isInternal()) builder.put(s, factory.make(s)); return builder.build(); } /** * Computes liveness information based on the schedules. */ private void computeLiveness() { /** * Compute post-initialization liveness (data items written during init * that will be read in a future steady-state iteration). These are the * items that must be moved into steady-state storage. We compute by * building the written physical indices during the init schedule * (including initial data items), then building the read physical * indices for future steady-state executions and taking the * intersection. */ Map<Storage, Set<Integer>> initWrites = new HashMap<>(); Map<Storage, Set<Integer>> futureReads = new HashMap<>(); for (Storage s : storage) { initWrites.put(s, new HashSet<Integer>()); futureReads.put(s, new HashSet<Integer>()); } for (ActorGroup g : groups) for (int i = 0; i < initSchedule.get(g); ++i) for (Map.Entry<Storage, ImmutableSortedSet<Integer>> writes : g.writes(i).entrySet()) initWrites.get(writes.getKey()).addAll(writes.getValue()); for (ActorGroup g : groups) { //We run until our read indices don't intersect any of the write //indices, at which point we aren't keeping any more elements live. boolean canStop = false; for (int i = initSchedule.get(g); !canStop; ++i) { canStop = true; for (Map.Entry<Storage, ImmutableSortedSet<Integer>> reads : g.reads(i).entrySet()) { Storage s = reads.getKey(); Set<Integer> readIndices = reads.getValue(); Set<Integer> writeIndices = initWrites.get(s); futureReads.get(s).addAll(readIndices); canStop &= Collections.min(readIndices) > Collections.max(writeIndices); // if (canStop) System.out.println(i+" "+readIndices+" "+writeIndices); } } } for (Storage s : storage) s.setIndicesLiveDuringSteadyState(ImmutableSortedSet.copyOf(Sets.intersection(initWrites.get(s), futureReads.get(s)))); } private static final class MigrationInstruction implements Runnable { private final ConcreteStorage init, steady; private final ImmutableSortedSet<Integer> indicesToMigrate; private MigrationInstruction(Storage storage, ConcreteStorage init, ConcreteStorage steady) { this.init = init; this.steady = steady; this.indicesToMigrate = storage.indicesLiveDuringSteadyState(); } @Override public void run() { init.sync(); for (int i : indicesToMigrate) steady.write(i, init.read(i)); steady.sync(); } } /** * The X doesn't stand for anything. I just needed a different name. */ private static final class XDrainInstruction implements DrainInstruction { private final Token token; private final ConcreteStorage storage; private final ImmutableSortedSet<Integer> indices; private XDrainInstruction(Token token, ConcreteStorage storage, ImmutableSortedSet<Integer> indices) { this.token = token; this.storage = storage; this.indices = indices; } @Override public Map<Token, Object[]> call() { Object[] data = new Object[indices.size()]; int idx = 0; for (int i : indices) data[idx++] = storage.read(i); return ImmutableMap.of(token, data); } } /** * TODO: consider using read/write handles instead of read(), write()? * TODO: if the index function is a contiguous range and the storage is * backed by an array, allow the storage to readAll directly into its array */ private static final class TokenReadInstruction implements ReadInstruction { private final Token token; private final MethodHandle idxFxn; private final ConcreteStorage storage; private final int count; private Buffer buffer; private TokenReadInstruction(ActorGroup tokenGroup, ConcreteStorage storage, int executions) { assert tokenGroup.isTokenGroup(); TokenActor actor = (TokenActor)Iterables.getOnlyElement(tokenGroup.actors()); assert actor.isInput(); this.token = actor.token(); this.idxFxn = Iterables.getOnlyElement(actor.outputIndexFunctions()); this.storage = storage; this.count = executions; } @Override public void init(Map<Token, Buffer> buffers) { this.buffer = buffers.get(token); if (buffer == null) throw new IllegalArgumentException("no buffer for "+token); } @Override public Map<Token, Integer> getMinimumBufferCapacity() { return ImmutableMap.of(token, count); } @Override public boolean load() { Object[] data = new Object[count]; if (!buffer.readAll(data)) return false; for (int i = 0; i < data.length; ++i) { int idx; try { idx = (int)idxFxn.invokeExact(i); } catch (Throwable ex) { throw new AssertionError("Can't happen! Index functions should not throw", ex); } storage.write(idx, data[i]); } storage.sync(); return true; } @Override public Map<Token, Object[]> unload() { Object[] data = new Object[count]; for (int i = 0; i < data.length; ++i) { int idx; try { idx = (int)idxFxn.invokeExact(i); } catch (Throwable ex) { throw new AssertionError("Can't happen! Index functions should not throw", ex); } data[i] = storage.read(idx); } return ImmutableMap.of(token, data); } } /** * TODO: consider using read handles instead of read()? * TODO: if the index function is a contiguous range and the storage is * backed by an array, allow the storage to writeAll directly from its array */ private static final class TokenWriteInstruction implements WriteInstruction { private final Token token; private final MethodHandle idxFxn; private final ConcreteStorage storage; private final int count; private Buffer buffer; private TokenWriteInstruction(ActorGroup tokenGroup, ConcreteStorage storage, int executions) { assert tokenGroup.isTokenGroup(); TokenActor actor = (TokenActor)Iterables.getOnlyElement(tokenGroup.actors()); assert actor.isOutput(); this.token = actor.token(); this.idxFxn = Iterables.getOnlyElement(actor.inputIndexFunctions()); this.storage = storage; this.count = executions; } @Override public void init(Map<Token, Buffer> buffers) { this.buffer = buffers.get(token); if (buffer == null) throw new IllegalArgumentException("no buffer for "+token); } @Override public Map<Token, Integer> getMinimumBufferCapacity() { return ImmutableMap.of(token, count); } @Override public void run() { Object[] data = new Object[count]; for (int i = 0; i < count; ++i) { int idx; try { idx = (int)idxFxn.invokeExact(i); } catch (Throwable ex) { throw new AssertionError("Can't happen! Index functions should not throw", ex); } data[i] = storage.read(idx); } for (int written = 0; written != data.length;) { written += buffer.write(data, written, data.length-written); } } } /** * Writes initial data into init storage, or "unloads" it (just returning it * as it was in the DrainData, not actually reading the storage) if we drain * during init. (Any remaining data after init will be migrated as normal.) * There's only one of these per blob because it returns all the data, and * it should be the first initReadInstruction. */ private static final class InitDataReadInstruction implements ReadInstruction { private final ImmutableMap<ConcreteStorage, ImmutableList<Pair<ImmutableList<Object>, MethodHandle>>> toWrite; private final ImmutableMap<Token, ImmutableList<Object>> initialStateDataMap; private InitDataReadInstruction(Map<Storage, ConcreteStorage> initStorage, ImmutableMap<Token, ImmutableList<Object>> initialStateDataMap) { ImmutableMap.Builder<ConcreteStorage, ImmutableList<Pair<ImmutableList<Object>, MethodHandle>>> toWriteBuilder = ImmutableMap.builder(); for (Map.Entry<Storage, ConcreteStorage> e : initStorage.entrySet()) { Storage s = e.getKey(); if (s.isInternal()) continue; if (s.initialData().isEmpty()) continue; toWriteBuilder.put(e.getValue(), ImmutableList.copyOf(s.initialData())); } this.toWrite = toWriteBuilder.build(); this.initialStateDataMap = initialStateDataMap; } @Override public void init(Map<Token, Buffer> buffers) { } @Override public Map<Token, Integer> getMinimumBufferCapacity() { return ImmutableMap.of(); } @Override public boolean load() { for (Map.Entry<ConcreteStorage, ImmutableList<Pair<ImmutableList<Object>, MethodHandle>>> e : toWrite.entrySet()) for (Pair<ImmutableList<Object>, MethodHandle> p : e.getValue()) for (int i = 0; i < p.first.size(); ++i) { int idx; try { idx = (int)p.second.invokeExact(i); } catch (Throwable ex) { throw new AssertionError("Can't happen! Index functions should not throw", ex); } e.getKey().write(idx, p.first.get(i)); } return true; } @Override public Map<Token, Object[]> unload() { Map<Token, Object[]> r = new HashMap<>(); for (Map.Entry<Token, ImmutableList<Object>> e : initialStateDataMap.entrySet()) r.put(e.getKey(), e.getValue().toArray()); return r; } } /** * Creates the blob host. This mostly involves shuffling our state into the * form the blob host wants. * @return the blob */ public Blob instantiateBlob() { ImmutableSortedSet.Builder<Token> inputTokens = ImmutableSortedSet.naturalOrder(), outputTokens = ImmutableSortedSet.naturalOrder(); ImmutableMap.Builder<Token, ConcreteStorage> tokenInitStorage = ImmutableMap.builder(), tokenSteadyStateStorage = ImmutableMap.builder(); for (TokenActor ta : Iterables.filter(actors, TokenActor.class)) { (ta.isInput() ? inputTokens : outputTokens).add(ta.token()); Storage s = ta.isInput() ? Iterables.getOnlyElement(ta.outputs()) : Iterables.getOnlyElement(ta.inputs()); tokenInitStorage.put(ta.token(), initStorage.get(s)); tokenSteadyStateStorage.put(ta.token(), steadyStateStorage.get(s)); } ImmutableList.Builder<MethodHandle> storageAdjusts = ImmutableList.builder(); for (ConcreteStorage s : steadyStateStorage.values()) storageAdjusts.add(s.adjustHandle()); return new Compiler2BlobHost(workers, inputTokens.build(), outputTokens.build(), initCode, steadyStateCode, storageAdjusts.build(), initReadInstructions, initWriteInstructions, migrationInstructions, readInstructions, writeInstructions, drainInstructions); } // public static void main(String[] args) { // StreamCompiler sc = new Compiler2StreamCompiler();//.multiplier(64).maxNumCores(8); //// Benchmark bm = new PipelineSanity.Add15(); //// Benchmark bm = new FMRadio.FMRadioBenchmarkProvider().iterator().next(); // Benchmark bm = new SplitjoinComputeSanity.MultiplyBenchmark(); // Benchmarker.runBenchmark(bm, sc).get(0).print(System.out); public static void main(String[] args) { Benchmarker.runBenchmark(new Reg20131116_104433_226(), new edu.mit.streamjit.impl.compiler2.Compiler2StreamCompiler()).get(0).print(System.out); } }
package com.madhackerdesigns.jinder; import java.io.IOException; import java.util.List; import java.util.SortedSet; import java.util.concurrent.ConcurrentSkipListSet; import com.google.api.client.extensions.android.json.AndroidJsonFactory; import com.google.api.client.extensions.appengine.http.UrlFetchTransport; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.apache.ApacheHttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.gson.GsonFactory; import com.google.api.client.json.jackson2.JacksonFactory; import com.madhackerdesigns.jinder.models.RoomList; import com.madhackerdesigns.jinder.models.SingleUser; import com.madhackerdesigns.jinder.models.User; /** * The {@link Campfire} class provides the public methods for accessing a 37signals Campfire * account. A new Campfire instance will build its own {@link Connection} for communicating * with the public Campfire API. The main purpose of the Campfire class is to fetch information * about available {@link Room}s and {@link User}s. * * @author flintinatux * @see Room * @see User */ public class Campfire { private Connection connection; // constructors /** * @param subdomain * @param token */ public Campfire(String subdomain, String token) { this.connection = new Connection(subdomain, token); } /** * This version of the constructor does not permanently store the username * and password, but instead uses them to obtain the API authentication token. * * @param subdomain * @param username * @param password */ public Campfire(String subdomain, String username, String password) { this.connection = new Connection(subdomain, username, password); } // public methods // public /** * Disables logging. */ public void disableLogging() { connection.disableLogging(); } /** * Enables logging. */ public void enableLogging() { connection.enableLogging(); } /** * Finds the {@link Room} that matches the given id. * * @param id - the id of the desired {@link Room} * @return the {@link Room} that matches this id, or null if no match exists * @throws IOException */ public Room findRoomById(long id) throws IOException { for (Room room : rooms()) { if (id == room.id) { return room; } } return null; } /** * Finds the {@link Room} that matches a given name. * * @param name - the name of the desired {@link Room} * @return the {@link Room} that matches this name, or null if no match exists * @throws IOException */ public Room findRoomByName(String name) throws IOException { for (Room room : rooms()) { if (name.equals(room.name)) { return room; } } return null; } /** * Finds the {@link Room} that matches a given guest hash. * * @param hash - the guest hash or code for the desired {@link Room} * @return the room for this guest hash, or null if no match exists * @throws IOException */ public Room findRoomByGuestHash(String hash) throws IOException { for (Room room : rooms()) { if (hash.equals(room.active_token_value)) { return room; } } return null; } /** * @return the currently logged in {@link User} * @throws IOException */ public User me() throws IOException { return connection.get("/users/me.json").parseAs(SingleUser.class).user; } /** * @return a list of available {@link Room}s for this account * @throws IOException */ public List<Room> rooms() throws IOException { List<Room> rooms = connection.get("/rooms.json").parseAs(RoomList.class).rooms(); for (Room room : rooms) { room.setConnection(connection); } return rooms; } /** * Sets the pluggable {@link HttpTransport} to use for this connection. If not explicitly set, * the default is {@link NetHttpTransport}. * * @param httpTransport - the {@link HttpTransport} to use for this connection. * @see NetHttpTransport * @see ApacheHttpTransport * @see UrlFetchTransport */ public void setHttpTransport(HttpTransport httpTransport) { connection.setHttpTransport(httpTransport); } /** * Sets the pluggable {@link JsonFactory} to use for this connection. If not explicitly set, * the default is {@link GsonFactory}. * * @param jsonFactory - the {@link JsonFactory} to use for this connection. * @see AndroidJsonFactory * @see GsonFactory * @see JacksonFactory */ public void setJsonFactory(JsonFactory jsonFactory) { connection.setJsonFactory(jsonFactory); } /** * @return the list of all {@link User}s currently in all {@link Room}s of this Campfire account. * @throws IOException */ public SortedSet<User> users() throws IOException { SortedSet<User> users = new ConcurrentSkipListSet<User>(); for (Room room : rooms()) { users.addAll(room.users()); } return users; } }
package pl.dawidfiruzek.dagger2mvpexample.ui.main; import android.support.annotation.NonNull; import java.util.List; import pl.dawidfiruzek.dagger2mvpexample.data.Repository; import pl.dawidfiruzek.dagger2mvpexample.util.api.GitHubService; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class MainPresenter implements MainContract.Presenter { private final GitHubService gitHubService; private MainContract.View view; private MainContract.Router router; public MainPresenter(GitHubService gitHubService) { this.gitHubService = gitHubService; } @Override public void setView(@NonNull MainContract.View view) { this.view = view; } @Override public void setRouter(@NonNull MainContract.Router router) { this.router = router; } @Override public void clear() { view = null; router = null; } @Override public void onResumed() { gitHubService .getRepositories("dawidfiruzek") .enqueue(new Callback<List<Repository>>() { @Override public void onResponse(Call<List<Repository>> call, Response<List<Repository>> response) { if (response.isSuccessful()) { StringBuilder stringBuilder = new StringBuilder(); for (Repository repo : response.body()) { stringBuilder.append(repo.getName()); stringBuilder.append("\n"); } if(view != null) { view.showRepos(stringBuilder.toString()); } } } @Override public void onFailure(Call<List<Repository>> call, Throwable t) { if(view != null) { view.showRepos("błąd"); } } }); } }
package me.lucko.helper.hologram.individual; import com.comphenix.protocol.PacketType; import com.comphenix.protocol.events.ListenerPriority; import com.comphenix.protocol.events.PacketContainer; import com.comphenix.protocol.wrappers.WrappedWatchableObject; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableSet; import me.lucko.helper.Events; import me.lucko.helper.protocol.Protocol; import me.lucko.helper.reflect.MinecraftVersion; import me.lucko.helper.reflect.MinecraftVersions; import me.lucko.helper.reflect.ServerReflection; import me.lucko.helper.serialize.Position; import me.lucko.helper.terminable.composite.CompositeTerminable; import me.lucko.helper.text.Text; import me.lucko.helper.utils.entityspawner.EntitySpawner; import org.bukkit.Chunk; import org.bukkit.Location; import org.bukkit.entity.ArmorStand; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.event.player.PlayerQuitEvent; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.ThreadLocalRandom; import java.util.function.Consumer; import javax.annotation.Nonnull; import javax.annotation.Nullable; public class PacketIndividualHologramFactory implements IndividualHologramFactory { private static final Method GET_HANDLE_METHOD; private static final Method GET_ID_METHOD; static { try { Class<?> entityClass = ServerReflection.nmsClass("Entity"); GET_ID_METHOD = entityClass.getDeclaredMethod("getId"); GET_ID_METHOD.setAccessible(true); Class<?> craftEntityClass = ServerReflection.obcClass("entity.CraftEntity"); GET_HANDLE_METHOD = craftEntityClass.getDeclaredMethod("getHandle"); GET_HANDLE_METHOD.setAccessible(true); } catch (Exception e) { throw new ExceptionInInitializerError(e); } } private static int getEntityId(Entity entity) { try { Object handle = GET_HANDLE_METHOD.invoke(entity); return (int) GET_ID_METHOD.invoke(handle); } catch (IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(e); } } @Nonnull @Override public IndividualHologram newHologram(@Nonnull Position position, @Nonnull List<HologramLine> lines) { return new PacketHologram(position, lines); } private static final class HologramEntity { private ArmorStand armorStand; private HologramLine line; private int entityId; private final Map<Integer, WrappedWatchableObject> cachedMetadata = new HashMap<>(); private HologramEntity(HologramLine line) { this.line = line; } public ArmorStand getArmorStand() { return this.armorStand; } public void setArmorStand(ArmorStand armorStand) { this.armorStand = armorStand; } public HologramLine getLine() { return this.line; } public void setLine(HologramLine line) { this.line = line; } public int getId() { return this.entityId; } public void setId(int entityId) { this.entityId = entityId; } public Map<Integer, WrappedWatchableObject> getCachedMetadata() { return this.cachedMetadata; } } private static final class PacketHologram implements IndividualHologram { private Position position; private final List<HologramLine> lines = new ArrayList<>(); private final List<HologramEntity> spawnedEntities = new ArrayList<>(); private final Set<Player> viewers = Collections.synchronizedSet(new HashSet<>()); private boolean spawned = false; private CompositeTerminable listeners = null; private Consumer<Player> clickCallback = null; PacketHologram(Position position, List<HologramLine> lines) { this.position = Objects.requireNonNull(position, "position"); updateLines(lines); } private Position getNewLinePosition() { if (this.spawnedEntities.isEmpty()) { return this.position; } else { // get the last entry ArmorStand last = this.spawnedEntities.get(this.spawnedEntities.size() - 1).getArmorStand(); return Position.of(last.getLocation()).subtract(0.0d, 0.25d, 0.0d); } } @Override public void spawn() { // ensure listening if (this.listeners == null) { setupPacketListeners(); } // resize to fit any new lines int linesSize = this.lines.size(); int spawnedSize = this.spawnedEntities.size(); // remove excess lines if (linesSize < spawnedSize) { int diff = spawnedSize - linesSize; for (int i = 0; i < diff; i++) { // get and remove the last entry int index = this.spawnedEntities.size() - 1; // remove the armorstand first ArmorStand as = this.spawnedEntities.get(index).getArmorStand(); as.remove(); // then remove from the list this.spawnedEntities.remove(index); } } // now enough armorstands are spawned, we can now update the text for (int i = 0; i < this.lines.size(); i++) { HologramLine line = this.lines.get(i); String generatedName = "hologramline-" + ThreadLocalRandom.current().nextInt(100000000); if (i >= this.spawnedEntities.size()) { // add a new line Location loc = getNewLinePosition().toLocation(); // init the holo entity before actually spawning (so the listeners can catch it) HologramEntity holoEntity = new HologramEntity(line); this.spawnedEntities.add(holoEntity); // ensure the hologram's chunk is loaded. Chunk chunk = loc.getChunk(); if (!chunk.isLoaded()) { chunk.load(); } // spawn the armorstand EntitySpawner.INSTANCE.spawn(loc, ArmorStand.class, as -> { int eid = getEntityId(as); holoEntity.setId(eid); holoEntity.setArmorStand(as); as.setSmall(true); as.setMarker(true); as.setArms(false); as.setBasePlate(false); as.setGravity(false); as.setVisible(false); as.setCustomName(generatedName); as.setCustomNameVisible(true); if (MinecraftVersion.getRuntimeVersion().isAfterOrEq(MinecraftVersions.v1_9)) { as.setAI(false); as.setCollidable(false); as.setInvulnerable(true); } }); } else { // update existing line if necessary HologramEntity as = this.spawnedEntities.get(i); if (!as.getLine().equals(line)) { as.setLine(line); as.getArmorStand().setCustomName(generatedName); } } } this.spawned = true; } @Override public void despawn() { this.spawnedEntities.forEach(e -> e.getArmorStand().remove()); this.spawnedEntities.clear(); this.spawned = false; if (this.listeners != null) { this.listeners.closeAndReportException(); } this.listeners = null; } @Override public boolean isSpawned() { if (!this.spawned) { return false; } for (HologramEntity stand : this.spawnedEntities) { if (!stand.getArmorStand().isValid()) { return false; } } return true; } @Override public void updatePosition(@Nonnull Position position) { Objects.requireNonNull(position, "position"); if (this.position.equals(position)) { return; } this.position = position; despawn(); spawn(); } @Override public void updateLines(@Nonnull List<HologramLine> lines) { Objects.requireNonNull(lines, "lines"); Preconditions.checkArgument(!lines.isEmpty(), "lines cannot be empty"); for (HologramLine line : lines) { Preconditions.checkArgument(line != null, "null line"); } if (this.lines.equals(lines)) { return; } this.lines.clear(); this.lines.addAll(lines); } @Nonnull @Override public Set<Player> getViewers() { return ImmutableSet.copyOf(this.viewers); } @Override public void addViewer(@Nonnull Player player) { if (!this.viewers.add(player)) { return; } boolean modern = MinecraftVersion.getRuntimeVersion().isAfterOrEq(MinecraftVersions.v1_9); // handle resending for (HologramEntity entity : this.spawnedEntities) { PacketContainer spawnPacket = new PacketContainer(PacketType.Play.Server.SPAWN_ENTITY); spawnPacket.getModifier().writeDefaults(); // write entity id spawnPacket.getIntegers().write(0, entity.getId()); // write unique id if (modern) { spawnPacket.getUUIDs().write(0, entity.getArmorStand().getUniqueId()); } // write coordinates Location loc = entity.getArmorStand().getLocation(); if (modern) { spawnPacket.getDoubles().write(0, loc.getX()); spawnPacket.getDoubles().write(1, loc.getY()); spawnPacket.getDoubles().write(2, loc.getZ()); } else { spawnPacket.getIntegers().write(1, (int) Math.floor(loc.getX() * 32)); spawnPacket.getIntegers().write(2, (int) Math.floor(loc.getY() * 32)); spawnPacket.getIntegers().write(3, (int) Math.floor(loc.getZ() * 32)); } spawnPacket.getIntegers().write(modern ? 4 : 7, (int) ((loc.getPitch()) * 256.0F / 360.0F)); spawnPacket.getIntegers().write(modern ? 5 : 8, (int) ((loc.getYaw()) * 256.0F / 360.0F)); // write type spawnPacket.getIntegers().write(modern ? 6 : 9, 78); // write object data spawnPacket.getIntegers().write(modern ? 7 : 10, 0); // send it Protocol.sendPacket(player, spawnPacket); // send missed metadata PacketContainer metadataPacket = new PacketContainer(PacketType.Play.Server.ENTITY_METADATA); // write entity id metadataPacket.getIntegers().write(0, entity.getId()); // write metadata List<WrappedWatchableObject> watchableObjects = new ArrayList<>(); // set custom name watchableObjects.add(new WrappedWatchableObject(2, Text.colorize(entity.getLine().resolve(player)))); // set custom name visible if (modern) { watchableObjects.add(new WrappedWatchableObject(3, true)); } else { watchableObjects.add(new WrappedWatchableObject(3, (byte) 1)); } // re-add all other cached metadata for (Map.Entry<Integer, WrappedWatchableObject> ent : entity.getCachedMetadata().entrySet()) { if (ent.getKey() != 2 && ent.getKey() != 3) { watchableObjects.add(ent.getValue()); } } metadataPacket.getWatchableCollectionModifier().write(0, watchableObjects); // send it Protocol.sendPacket(player, metadataPacket); } } @Override public void removeViewer(@Nonnull Player player) { if (!this.viewers.remove(player)) { return; } // handle removing the existing entity? PacketContainer destroyPacket = new PacketContainer(PacketType.Play.Server.ENTITY_DESTROY); // set ids int[] ids = this.spawnedEntities.stream().mapToInt(HologramEntity::getId).toArray(); destroyPacket.getIntegerArrays().write(0, ids); Protocol.sendPacket(player, destroyPacket); } @Override public void setClickCallback(@Nullable Consumer<Player> clickCallback) { this.clickCallback = clickCallback; } @Override public void close() { despawn(); } @Override public boolean isClosed() { return !this.spawned; } private HologramEntity getHologramEntity(int entityId) { for (HologramEntity entity : PacketHologram.this.spawnedEntities) { if (entity.getId() == entityId) { return entity; } } return null; } private void setupPacketListeners() { this.listeners = CompositeTerminable.create(); // remove players when they quit Events.subscribe(PlayerQuitEvent.class) .handler(e -> this.viewers.remove(e.getPlayer())) .bindWith(this.listeners); Protocol.subscribe(ListenerPriority.HIGH, PacketType.Play.Server.ENTITY_METADATA) .handler(e -> { PacketContainer packet = e.getPacket(); Player player = e.getPlayer(); // get entity id int entityId = packet.getIntegers().read(0); // find a matching hologram line HologramEntity hologram = getHologramEntity(entityId); if (hologram == null) { return; } // get metadata List<WrappedWatchableObject> metadata = new ArrayList<>(packet.getWatchableCollectionModifier().read(0)); if (!this.viewers.contains(player)) { // attempt to cache metadata anyway for (WrappedWatchableObject value : metadata) { if (value.getIndex() != 2) { hologram.getCachedMetadata().put(value.getIndex(), value); } } e.setCancelled(true); return; } // process metadata for (WrappedWatchableObject value : metadata) { if (value.getIndex() == 2) { value.setValue(Text.colorize(hologram.getLine().resolve(player))); } else { // cache the metadata hologram.getCachedMetadata().put(value.getIndex(), value); } } packet = packet.deepClone(); packet.getWatchableCollectionModifier().write(0, metadata); e.setPacket(packet); }) .bindWith(this.listeners); Protocol.subscribe(ListenerPriority.HIGH, PacketType.Play.Server.SPAWN_ENTITY) .handler(e -> { PacketContainer packet = e.getPacket(); Player player = e.getPlayer(); // get entity id int entityId = packet.getIntegers().read(0); // find a matching hologram HologramEntity hologram = getHologramEntity(entityId); if (hologram == null) { return; } if (!this.viewers.contains(player)) { e.setCancelled(true); } }) .bindWith(this.listeners); Protocol.subscribe(ListenerPriority.HIGH, PacketType.Play.Client.USE_ENTITY) .handler(e -> { PacketContainer packet = e.getPacket(); Player player = e.getPlayer(); // get entity id int entityId = packet.getIntegers().read(0); // find a matching hologram HologramEntity hologram = getHologramEntity(entityId); if (hologram == null) { return; } // always cancel interacts involving hologram objects e.setCancelled(true); if (this.clickCallback == null) { return; } // if the player isn't a viewer, don't process the click if (!this.viewers.contains(player)) { return; } Location location = hologram.getArmorStand().getLocation(); if (player.getLocation().distance(location) > 5) { return; } this.clickCallback.accept(player); }) .bindWith(this.listeners); } } }
package com.metamolecular.pubcouch.test; import junit.framework.TestSuite; import junit.textui.TestRunner; /** * * @author Richard L. Apodaca <rapodaca at metamolecular.com> */ public class Main { public static void main(String[] args) throws Exception { TestSuite suite = new TestSuite(); // suite.addTestSuite(SnapshotTest.class); // suite.addTestSuite(BundleTest.class); suite.addTestSuite(RecordTest.class); TestRunner.run(suite); } }
package com.opencms.defaults; import com.opencms.template.*; import com.opencms.workplace.*; import com.opencms.defaults.*; import com.opencms.file.*; import com.opencms.core.*; import com.opencms.core.exceptions.*; import java.util.*; import java.lang.reflect.*; public abstract class A_CmsBackoffice extends CmsWorkplaceDefault implements I_CmsConstants{ private static int C_NOT_LOCKED = -1; private static int C_NO_ACCESS = -2; private static String C_DEFAULT_SELECTOR="(default)"; private static String C_DONE_SELECTOR="done"; /** * Gets the backoffice url of the module. * @returns A string with the backoffice url */ abstract public String getBackofficeUrl(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) throws Exception ; /** * Gets the create url of the module. * @returns a string with the create url */ abstract public String getCreateUrl(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) throws Exception ; /** * Gets the edit url of the module. * @returns A string with the edit url */ abstract public String getEditUrl(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) throws Exception ; /** * Gets the redirect url of the module. This URL is called, when an entry of the file list is selected * @returns A string with the url. */ public String getUrl(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) throws Exception { return ""; } /** * Gets the setup url of the module. This is the url of the setup page for this module. * @returns A string with the setup url. */ public String getSetupUrl(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) throws Exception { return ""; } /** * Gets the content of a given template file. * This method displays any content provided by a content definition * class on the template. The used backoffice class does not need to use a * special getContent method. It just has to extend the methods of this class! * Using reflection, this method creates the table headline and table content * with the layout provided by the template automatically! * @param cms A_CmsObject Object for accessing system resources * @param templateFile Filename of the template file * @param elementName <em>not used here</em>. * @param parameters <em>not used here</em>. * @param templateSelector template section that should be processed. * @return Processed content of the given template file. * @exception CmsException */ public byte[] getContent(CmsObject cms, String templateFile, String elementName, Hashtable parameters, String templateSelector) throws CmsException { //return var byte[] returnProcess = null; String error=""; // the CD to be used A_CmsContentDefinition cd=null; // session will be created or fetched I_CmsSession session = (CmsSession) cms.getRequestContext().getSession(true); //create new workplace templatefile object CmsXmlWpTemplateFile template = new CmsXmlWpTemplateFile(cms, templateFile); //get parameters String selectBox = (String) parameters.get("selectbox"); String filterParam = (String) parameters.get("filterparameter"); String id = (String) parameters.get("id"); String idlock = (String) parameters.get("idlock"); String iddelete = (String) parameters.get("iddelete"); String idedit = (String) parameters.get("idedit"); String idview = (String) parameters.get("idview"); String action = (String) parameters.get("action"); String parentId = (String) parameters.get("parentId"); String ok = (String) parameters.get("ok"); String setaction = (String) parameters.get("setaction"); // debug-code String hasFilterParam = (String) session.getValue("filterparameter"); template.setData("filternumber","0"); //change filter if ((hasFilterParam == null) && (filterParam == null) && (setaction == null)) { if (selectBox != null) { session.putValue("filter", selectBox); template.setData("filternumber",selectBox); } } else { template.setData("filternumber", (String)session.getValue("filter")); } //move id values to id, remove old markers if (idlock != null) { id = idlock; session.putValue("idlock", idlock); session.removeValue("idedit"); session.removeValue("idnew"); session.removeValue("iddelete"); } if (idedit != null) { id = idedit; session.putValue("idedit", idedit); session.removeValue("idlock"); session.removeValue("idnew"); session.removeValue("iddelete"); } if (iddelete != null) { id = iddelete; session.putValue("iddelete", iddelete); session.removeValue("idedit"); session.removeValue("idnew"); session.removeValue("idlock"); } if ((id != null) && (id.equals("new"))) { session.putValue("idnew", id); session.removeValue("idedit"); session.removeValue("idnew"); session.removeValue("iddelete"); session.removeValue("idlock"); } //get marker id from session String idsave = (String) session.getValue("idsave"); if (ok == null) { idsave = null; } if(parentId != null) { session.putValue("parentId", parentId); } //get marker for accessing the new dialog String idnewsave = (String) session.getValue("idnew"); //access to new dialog if ((id != null) && (id.equals("new")) || ((idsave != null) && (idsave.equals("new")))) { if (idsave != null) { parameters.put("id", idsave); } if (id != null) { parameters.put("id", id); session.putValue("idsave", id); } return getContentNewInternal(cms,id,cd,session,template,elementName,parameters,templateSelector); } //go to the appropriate getContent methods if ((id == null) && (idsave == null) && (action == null) && (idlock==null) && (iddelete == null) && (idedit == null)) { //process the head frame containing the filter returnProcess = getContentHead(cms, template, elementName, parameters, templateSelector); //finally return processed data return returnProcess; } else { //process the body frame containing the table if(action == null) { action = ""; } if (action.equalsIgnoreCase("list")){ //process the list output // clear "idsave" here in case user verification of data failed and input has to be shown again ... session.removeValue("idsave"); returnProcess = getContentList(cms, template, elementName, parameters, templateSelector); //finally return processed data return returnProcess; } else { //get marker for accessing the edit dialog String ideditsave = (String) session.getValue("idedit"); //go to the edit dialog if ((idedit != null) || (ideditsave != null)) { if (idsave != null) { parameters.put("id", idsave); } if (id != null) { parameters.put("id", id); session.putValue("idsave", id); } return getContentEditInternal(cms,id,cd,session,template,elementName,parameters,templateSelector); } else { //store id parameters for delete and lock if (idsave != null) { parameters.put("id", idsave); session.removeValue("idsave"); } else { parameters.put("id", id); session.putValue("idsave", id); } //get marker for accessing the delete dialog String iddeletesave = (String) session.getValue("iddelete"); //access delete dialog if (((iddelete != null) || (iddeletesave != null)) && (idlock == null)) { returnProcess = getContentDelete(cms, template, elementName, parameters, templateSelector); return returnProcess; }else { //access lock dialog returnProcess = getContentLock(cms, template, elementName, parameters, templateSelector); //finally return processed data return returnProcess; } } } } } /** * Gets the content definition class * @returns class content definition class * Must be implemented in the extending backoffice class! */ public abstract Class getContentDefinitionClass() ; /** * Gets the content definition class method constructor * @returns content definition object */ protected Object getContentDefinition(CmsObject cms, Class cdClass, Integer id) { Object o = null; try { Constructor c = cdClass.getConstructor(new Class[] {CmsObject.class, Integer.class}); o = c.newInstance(new Object[] {cms, id}); } catch (InvocationTargetException ite) { if (I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_INFO, getClassName() + ": Backoffice contentDefinitionConstructor: Invocation target exception!"); } } catch (NoSuchMethodException nsm) { if (I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_INFO, getClassName() + ": Backoffice contentDefinitionConstructor: Requested method was not found!"); } } catch (InstantiationException ie) { if (I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_INFO, getClassName() + ": Backoffice contentDefinitionConstructor: the reflected class is abstract!"); } } catch (Exception e) { if (I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_INFO, getClassName() + ": Backoffice contentDefinitionConstructor: Other exception! "+e); } if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_INFO, e.getMessage() ); } } return o; } /** * Gets the content definition class method constructor * @returns content definition object */ protected Object getContentDefinition(CmsObject cms, Class cdClass) { Object o = null; try { Constructor c = cdClass.getConstructor(new Class[] {CmsObject.class}); o = c.newInstance(new Object[] {cms}); } catch (InvocationTargetException ite) { if (I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_INFO, getClassName() + ": Backoffice contentDefinitionConstructor: Invocation target exception!"); } } catch (NoSuchMethodException nsm) { if (I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_INFO, getClassName() + ": Backoffice contentDefinitionConstructor: Requested method was not found!"); } } catch (InstantiationException ie) { if (I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_INFO, getClassName() + ": Backoffice contentDefinitionConstructor: the reflected class is abstract!"); } } catch (Exception e) { if (I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_INFO, getClassName() + ": Backoffice contentDefinitionConstructor: Other exception! "+e); } if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_INFO, e.getMessage() ); } } return o; } /** * Gets the content definition class method constructor * @returns content definition object */ protected Object getContentDefinition(CmsObject cms, Class cdClass, String id) { Object o = null; try { Constructor c = cdClass.getConstructor(new Class[] {CmsObject.class, String.class}); o = c.newInstance(new Object[] {cms, id}); } catch (InvocationTargetException ite) { if (I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_INFO, getClassName() + ": Backoffice contentDefinitionConstructor: Invocation target exception!"); } } catch (NoSuchMethodException nsm) { if (I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_INFO, getClassName() + ": Backoffice contentDefinitionConstructor: Requested method was not found!"); } } catch (InstantiationException ie) { if (I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_INFO, getClassName() + ": Backoffice contentDefinitionConstructor: the reflected class is abstract!"); } } catch (Exception e) { if (I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_INFO, getClassName() + ": Backoffice contentDefinitionConstructor: Other exception! "+e); } if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_INFO, e.getMessage() ); } } return o; } /** * Gets the content of a given template file. * <P> * While processing the template file the table entry * <code>entryTitle<code> will be displayed in the delete dialog * * @param cms A_CmsObject Object for accessing system resources * @param templateFile Filename of the template file * @param elementName not used here * @param parameters get the parameters action for the button activity * and id for the used content definition instance object * @param templateSelector template section that should be processed. * @return Processed content of the given template file. * @exception CmsException */ public byte[] getContentDelete(CmsObject cms, CmsXmlWpTemplateFile template, String elementName, Hashtable parameters, String templateSelector) throws CmsException { //return var byte[] processResult = null; // session will be created or fetched I_CmsSession session = (CmsSession) cms.getRequestContext().getSession(true); //get the class of the content definition Class cdClass = getContentDefinitionClass(); //get (stored) id parameter String id = (String) parameters.get("id"); if (id == null) { id = ""; } // get value of hidden input field action String action = (String) parameters.get("action"); //no button pressed, go to the default section! //delete dialog, displays the title of the entry to be deleted if (action == null || action.equals("")) { if (id != "") { //set template section templateSelector = "delete"; //create appropriate class name with underscores for labels /* String moduleName = ""; moduleName = (String) getClass().toString(); //get name moduleName = moduleName.substring(5); //remove 'class' substring at the beginning moduleName = moduleName.trim(); moduleName = moduleName.replace('.', '_'); //replace dots with underscores */ //create new language file object CmsXmlLanguageFile lang = new CmsXmlLanguageFile(cms); //get the dialog from the langauge file and set it in the template template.setData("deletetitle", lang.getLanguageValue("messagebox.title.delete")); template.setData("deletedialog", lang.getLanguageValue("messagebox.message1.delete")); template.setData("newsentry", id); template.setData("setaction", "default"); } // confirmation button pressed, process data! } else { //set template section templateSelector = "done"; //remove marker session.removeValue("idsave"); //delete the content definition instance Integer idInteger = null; try { idInteger = Integer.valueOf(id); } catch (Exception e) { //access content definition constructor by reflection Object o = null; o = getContentDefinition(cms, cdClass, id); //get delete method and delete content definition instance try { ((A_CmsContentDefinition) o).delete(cms); } catch (Exception e1) { if (I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_INFO, getClassName() + ": Backoffice: delete method throwed an exception!"); } templateSelector = "deleteerror"; template.setData("deleteerror", e1.getMessage()); } //finally start the processing processResult = startProcessing(cms, template, elementName, parameters, templateSelector); return processResult; } //access content definition constructor by reflection Object o = null; o = getContentDefinition(cms, cdClass, idInteger); //get delete method and delete content definition instance try { ((A_CmsContentDefinition) o).delete(cms); }catch (Exception e) { templateSelector = "deleteerror"; template.setData("deleteerror", e.getMessage()); } } //finally start the processing processResult = startProcessing(cms, template, elementName, parameters, templateSelector); return processResult; } /** * Gets the content of a given template file. * <P> * * @param cms A_CmsObject Object for accessing system resources * @param templateFile Filename of the template file * @param elementName not used here * @param parameters get the parameters action for the button activity * and id for the used content definition instance object * and the author, title, text content for setting the new/changed data * @param templateSelector template section that should be processed. * @return Processed content of the given template file. * @exception CmsException */ private byte[] getContentHead(CmsObject cms, CmsXmlWpTemplateFile template, String elementName, Hashtable parameters, String templateSelector) throws CmsException { //return var byte[] processResult = null; //get the class of the content definition Class cdClass = getContentDefinitionClass(); //init vars String singleSelection = ""; String allSelections = ""; //create new or fetch existing session CmsSession session = (CmsSession) cms.getRequestContext().getSession(true); String uri = cms.getRequestContext().getUri(); String sessionSelectBoxValue = uri+"selectBoxValue"; //get filter method from session String selectBoxValue = (String) parameters.get("selectbox"); if(selectBoxValue == null) { // set default value if((String)session.getValue(sessionSelectBoxValue) != null) { // came back from edit or something ... redisplay last filter selectBoxValue = (String)session.getValue(sessionSelectBoxValue); } else { // the very first time here... selectBoxValue = "0"; } } boolean filterChanged = true; if( selectBoxValue.equals((String)session.getValue(sessionSelectBoxValue)) ) { filterChanged = false; }else { filterChanged = true; } //get vector of filter names from the content definition Vector filterMethods = getFilterMethods(cms); if( Integer.parseInt(selectBoxValue) >= filterMethods.size() ) { // the stored seclectBoxValue is does not exist any more, ... selectBoxValue = "0"; } session.putValue(sessionSelectBoxValue, selectBoxValue); // store in session for Selectbox! session.putValue("filter",selectBoxValue); // store filter in session for getContentList! String filterParam = (String) parameters.get("filterparameter"); String action = (String) parameters.get("action"); String setaction = (String) parameters.get("setaction"); // create the key for the filterparameter in the session ... should be unique to avoid problems... String sessionFilterParam = uri+selectBoxValue+"filterparameter"; //store filterparameter in the session, new enty for every filter of every url ... if (filterParam != null) { session.putValue(sessionFilterParam, filterParam); } //create appropriate class name with underscores for labels String moduleName = ""; moduleName = (String) getClass().toString(); //get name moduleName = moduleName.substring(5); //remove 'class' substring at the beginning moduleName = moduleName.trim(); moduleName = moduleName.replace('.', '_'); //replace dots with underscores //create new language file object CmsXmlLanguageFile lang = new CmsXmlLanguageFile(cms); //set labels in the template template.setData("filterlabel", lang.getLanguageValue(moduleName + ".label.filter")); template.setData("filterparameterlabel", lang.getLanguageValue(moduleName + ".label.filterparameter")); //no filter selected so far, store a default filter in the session CmsFilterMethod filterMethod = null; if (selectBoxValue == null) { CmsFilterMethod defaultFilter = (CmsFilterMethod) filterMethods.firstElement(); session.putValue("selectbox", defaultFilter.getFilterName()); } // show param box ? CmsFilterMethod currentFilter = (CmsFilterMethod) filterMethods.elementAt(Integer.parseInt(selectBoxValue)); if(currentFilter.hasUserParameter()) { if(filterChanged) { template.setData("filterparameter", currentFilter.getDefaultFilterParam()); // access default in getContentList() .... session.putValue(sessionFilterParam, currentFilter.getDefaultFilterParam()); } else if(filterParam!= null) { template.setData("filterparameter", filterParam); } else { // redisplay after edit or something like this ... template.setData("filterparameter", (String)session.getValue(sessionFilterParam)); } template.setData("insertFilter", template.getProcessedDataValue("selectboxWithParam", this, parameters)); template.setData("setfocus", template.getDataValue("focus")); }else{ template.setData("insertFilter", template.getProcessedDataValue("singleSelectbox", this, parameters)); } //if getCreateUrl equals null, the "create new entry" button //will not be displayed in the template String createButton = null; try { createButton = (String) getCreateUrl(cms, null, null, null); } catch (Exception e) { } if (createButton == null) { String cb = template.getDataValue("nowand"); template.setData("createbutton", cb); } else { String cb = template.getProcessedDataValue("wand", this, parameters); template.setData("createbutton", cb); } //if getSetupUrl is empty, the module setup button will not be displayed in the template. String setupButton = null; try { setupButton = (String) getSetupUrl(cms, null, null, null); } catch (Exception e) { } if ((setupButton == null) || (setupButton.equals(""))){ String sb = template.getDataValue("nosetup"); template.setData("setupbutton", sb); } else { String sb= template.getProcessedDataValue("setup", this, parameters); template.setData("setupbutton",sb); } //finally start the processing processResult = startProcessing(cms, template, elementName, parameters, templateSelector); return processResult; } /** * Gets the content of a given template file. * This method displays any content provided by a content definition * class on the template. The used backoffice class does not need to use a * special getContent method. It just has to extend the methods of this class! * Using reflection, this method creates the table headline and table content * with the layout provided by the template automatically! * @param cms CmsObjectfor accessing system resources * @param templateFile Filename of the template file * @param elementName <em>not used here</em>. * @param parameters <em>not used here</em>. * @param templateSelector template section that should be processed. * @return Processed content of the given template file. * @exception CmsException */ private byte[] getContentList(CmsObject cms, CmsXmlWpTemplateFile template, String elementName, Hashtable parameters, String templateSelector) throws CmsException { //return var byte[] processResult = null; // session will be created or fetched I_CmsSession session = (CmsSession) cms.getRequestContext().getSession(true); //get the class of the content definition Class cdClass = getContentDefinitionClass(); String action = (String) parameters.get("action"); //read value of the selected filter String filterMethodName = (String) session.getValue("filter"); if (filterMethodName == null) { filterMethodName = "0"; } String uri = cms.getRequestContext().getUri(); String sessionFilterParam = uri+filterMethodName+"filterparameter"; //read value of the inputfield filterparameter String filterParam = (String) session.getValue(sessionFilterParam); if (filterParam == "") { filterParam = null; } //change template to list section for data list output templateSelector = "list"; //init vars String tableHead = ""; String singleRow = ""; String allEntrys = ""; String entry = ""; String url = ""; int columns = 0; // get number of columns Vector columnsVector = new Vector(); String fieldNamesMethod = "getFieldNames"; Class paramClasses[] = {CmsObject.class}; Object params[] = {cms}; columnsVector = (Vector) getContentMethodObject(cms, cdClass, fieldNamesMethod, paramClasses, params); columns = columnsVector.size(); //create appropriate class name with underscores for labels String moduleName = ""; moduleName = (String) getClass().toString(); //get name moduleName = moduleName.substring(5); //remove 'class' substring at the beginning moduleName = moduleName.trim(); moduleName = moduleName.replace('.', '_'); //replace dots with underscores //create new language file object CmsXmlLanguageFile lang = new CmsXmlLanguageFile(cms); //create tableheadline for (int i = 0; i < columns; i++) { tableHead += (template.getDataValue("tabledatabegin")) + lang.getLanguageValue(moduleName + ".label." + columnsVector.elementAt(i).toString().toLowerCase().trim()) + (template.getDataValue("tabledataend")); } //set template data for table headline content template.setData("tableheadline", tableHead); // get vector of filterMethods and select the appropriate filter method, // if no filter is appropriate, select a default filter get number of rows for output Vector tableContent = new Vector(); try { Vector filterMethods = (Vector) cdClass.getMethod("getFilterMethods", new Class[] {CmsObject.class}).invoke(null, new Object[] {cms}); CmsFilterMethod filterMethod = null; CmsFilterMethod filterName = (CmsFilterMethod) filterMethods.elementAt(Integer.parseInt(filterMethodName)); filterMethodName = filterName.getFilterName(); //loop trough the filter methods and set the chosen one for (int i = 0; i < filterMethods.size(); i++) { CmsFilterMethod currentFilter = (CmsFilterMethod) filterMethods.elementAt(i); if (currentFilter.getFilterName().equals(filterMethodName)) { filterMethod = currentFilter; break; } } // the chosen filter does not exist, use the first one! if (filterMethod == null) { filterMethod = (CmsFilterMethod) filterMethods.firstElement(); } // now apply the filter with the cms object, the filter method and additional user parameters tableContent = (Vector) cdClass.getMethod("applyFilter", new Class[] {CmsObject.class, CmsFilterMethod.class, String.class}).invoke(null, new Object[] {cms, filterMethod, filterParam}); } catch (InvocationTargetException ite) { //error occured while applying the filter if (I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_INFO, getClassName() + ": Backoffice: apply filter throwed an InvocationTargetException!"); } templateSelector = "error"; template.setData("filtername", filterMethodName); while(ite.getTargetException() instanceof InvocationTargetException) { ite = ((InvocationTargetException) ite.getTargetException()); } template.setData("filtererror", ite.getTargetException().getMessage()); session.removeValue(sessionFilterParam); //session.removeValue("filter"); } catch (NoSuchMethodException nsm) { if (I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_INFO, getClassName() + ": Backoffice: apply filter method was not found!"); } templateSelector = "error"; template.setData("filtername", filterMethodName); template.setData("filtererror", nsm.getMessage()); session.removeValue(sessionFilterParam); //session.removeValue("filterparameter"); } catch (Exception e) { if (I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_INFO, getClassName() + ": Backoffice: apply filter: Other Exception! "+e); } templateSelector = "error"; template.setData("filtername", filterMethodName); template.setData("filtererror", e.getMessage()); session.removeValue(sessionFilterParam); //session.removeValue("filterparameter"); } //get the number of rows int rows = tableContent.size(); // get the field methods from the content definition Vector fieldMethods = new Vector(); try { fieldMethods = (Vector) cdClass.getMethod("getFieldMethods", new Class[] {CmsObject.class}).invoke(null, new Object[] {cms}); } catch (Exception exc) { if (I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_INFO, getClassName() + ": Backoffice getContentList: getFieldMethods throwed an exception"); } templateSelector = "error"; template.setData("filtername", filterMethodName); template.setData("filtererror", exc.getMessage()); } // create output from the table data String fieldEntry = ""; String id = ""; for (int i = 0; i < rows; i++) { //init entry = ""; singleRow = ""; Object entryObject = new Object(); entryObject = tableContent.elementAt(i); //cd object in row //set data of single row for (int j = 0; j < columns; j++) { fieldEntry = "+++ NO VALUE FOUND +++"; // call the field methods Method getMethod = null; try { getMethod = (Method) fieldMethods.elementAt(j); } catch (Exception e) { if (I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_INFO, getClassName() + ": Could not get field method for "+(String)columnsVector.elementAt(j)+" - check for correct spelling!"); } } try { //apply methods on content definition object Object fieldEntryObject = null; fieldEntryObject = getMethod.invoke(entryObject, new Object[0]); if (fieldEntryObject != null) { fieldEntry = fieldEntryObject.toString(); } else { fieldEntry = null; } } catch (InvocationTargetException ite) { if (I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_INFO, getClassName() + ": Backoffice content definition object throwed an InvocationTargetException!"); } } catch (Exception e) { if (I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_INFO, getClassName() + ": Backoffice content definition object: Other exception! "+e); } } try { id = ((A_CmsContentDefinition)entryObject).getUniqueId(cms); } catch (Exception e) { if (I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_INFO, getClassName() + ": Backoffice: getUniqueId throwed an Exception!"); } } //insert unique id in contextmenue if (id != null) { template.setData("uniqueid", id); } //insert table entry if (fieldEntry != null) { try{ Vector v = new Vector(); v.addElement(new Integer(id)); v.addElement(template); url = getUrl(cms, null, null,v); }catch (Exception e) { url = ""; } if(!url.equals("")) { // enable url entry += (template.getDataValue("tabledatabegin")) + (template.getProcessedDataValue("url", this, parameters)) + fieldEntry + (template.getDataValue("tabledataend")); }else { // disable url entry += (template.getDataValue("tabledatabegin")) + fieldEntry + (template.getDataValue("tabledataend")); } } else { entry += (template.getDataValue("tabledatabegin")) + "" + (template.getDataValue("tabledataend")); } } //get the unique id belonging to an entry try { id = ((A_CmsContentDefinition)entryObject).getUniqueId(cms); } catch (Exception e) { if (I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_INFO, getClassName() + ": Backoffice: getUniqueId throwed an Exception!"); } } //insert unique id in contextmenue if (id != null) { template.setData("uniqueid", id); } //set the lockstates for the actual entry setLockstates(cms, template, cdClass, entryObject, parameters); //insert single table row in template template.setData("entry", entry); // processed row from template singleRow = template.getProcessedDataValue("singlerow", this, parameters); allEntrys += (template.getDataValue("tablerowbegin")) + singleRow + (template.getDataValue("tablerowend")); } //insert tablecontent in template template.setData("tablecontent", "" + allEntrys); //save select box value into session session.putValue("selectbox", filterMethodName); //finally start the processing processResult = startProcessing(cms, template, elementName, parameters, templateSelector); return processResult; } /** * Gets the content of a given template file. * <P> * While processing the template file the table entry * <code>entryTitle<code> will be displayed in the delete dialog * * @param cms A_CmsObject Object for accessing system resources * @param templateFile Filename of the template file * @param elementName not used here * @param parameters get the parameters action for the button activity * and id for the used content definition instance object * @param templateSelector template section that should be processed. * @return Processed content of the given template file. * @exception CmsException */ private byte[] getContentLock(CmsObject cms, CmsXmlWpTemplateFile template, String elementName, Hashtable parameters, String templateSelector) throws CmsException { //return var byte[] processResult = null; // now check if the "do you really want to lock" dialog should be shown. Hashtable startSettings = (Hashtable)cms.getRequestContext().currentUser().getAdditionalInfo(C_ADDITIONAL_INFO_STARTSETTINGS); String showLockDialog = "on"; if(startSettings!=null){ showLockDialog = (String)startSettings.get(C_START_LOCKDIALOG); } if (!showLockDialog.equalsIgnoreCase("on")) { parameters.put("action","go"); } // session will be created or fetched I_CmsSession session = (CmsSession) cms.getRequestContext().getSession(true); //get the class of the content definition Class cdClass = getContentDefinitionClass(); int actUserId = cms.getRequestContext().currentUser().getId(); //get (stored) id parameter String id = (String) parameters.get("id"); if (id == null) id = ""; /*if (id != "") { session.putValue("idsave", id); } else { String idsave = (String) session.getValue("idsave"); if (idsave == null) idsave = ""; id = idsave; session.removeValue("idsave"); } */ parameters.put("idlock", id); // get value of hidden input field action String action = (String) parameters.get("action"); //no button pressed, go to the default section! if (action == null || action.equals("")) { //lock dialog, displays the title of the entry to be changed in lockstate templateSelector = "lock"; Integer idInteger = null; int ls = -1; try { idInteger = Integer.valueOf(id); } catch (Exception e) { ls = -1; //access content definition object specified by id through reflection String title = "no title"; Object o = null; o = getContentDefinition(cms, cdClass, id); try { ls = ((A_CmsContentDefinition) o).getLockstate(); /*Method getLockstateMethod = (Method) cdClass.getMethod("getLockstate", new Class[] {}); ls = (int) getLockstateMethod.invoke(o, new Object[0]); */ } catch (Exception exc) { exc.printStackTrace(); } } //access content definition object specified by id through reflection String title = "no title"; Object o = null; if (idInteger != null) { o = getContentDefinition(cms, cdClass, idInteger); try { ls = ((A_CmsContentDefinition) o).getLockstate(); } catch (Exception e) { if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_INFO, e.getMessage() ); } } } else { o = getContentDefinition(cms, cdClass, id); try { ls = ((A_CmsContentDefinition) o).getLockstate(); } catch (Exception e) { if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_INFO, e.getMessage() ); } } } //create appropriate class name with underscores for labels String moduleName = ""; moduleName = (String) getClass().toString(); //get name moduleName = moduleName.substring(5); //remove 'class' substring at the beginning moduleName = moduleName.trim(); moduleName = moduleName.replace('.', '_'); //replace dots with underscores //create new language file object CmsXmlLanguageFile lang = new CmsXmlLanguageFile(cms); //get the dialog from the langauge file and set it in the template if (ls != C_NOT_LOCKED && ls != actUserId) { // "lock" template.setData("locktitle", lang.getLanguageValue("messagebox.title.lockchange")); template.setData("lockstate", lang.getLanguageValue("messagebox.message1.lockchange")); } if (ls == C_NOT_LOCKED) { // "nolock" template.setData("locktitle", lang.getLanguageValue("messagebox.title.lock")); template.setData("lockstate", lang.getLanguageValue("messagebox.message1.lock")); } if (ls == actUserId) { template.setData("locktitle", lang.getLanguageValue("messagebox.title.unlock")); template.setData("lockstate", lang.getLanguageValue("messagebox.message1.unlock")); } //set the title of the selected entry template.setData("newsentry", id); //go to default template section template.setData("setaction", "default"); parameters.put("action", "done"); // confirmation button pressed, process data! } else { templateSelector = "done"; // session.removeValue("idsave"); //access content definition constructor by reflection Integer idInteger = null; int ls = C_NOT_LOCKED; try { idInteger = Integer.valueOf(id); } catch (Exception e) { ls = C_NOT_LOCKED; //access content definition object specified by id through reflection String title = "no title"; Object o = null; o = getContentDefinition(cms, cdClass, id); try { ls = ((A_CmsContentDefinition) o).getLockstate(); } catch (Exception ex) { if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_INFO, ex.getMessage() ); } } } //call the appropriate content definition constructor Object o = null; if (idInteger != null) { o = getContentDefinition(cms, cdClass, idInteger); try { ls = ((A_CmsContentDefinition) o).getLockstate(); } catch (Exception e) { if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_INFO, e.getMessage() ); } } } else { o = getContentDefinition(cms, cdClass, id); try { ls = ((A_CmsContentDefinition) o).getLockstate(); } catch (Exception e) { if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_INFO, e.getMessage() ); } } } try { ls = ((A_CmsContentDefinition) o).getLockstate(); } catch (Exception e) { if (I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_INFO, getClassName() + " Backoffice getContentLock: Method getLockstate throwed an exception!"); } } //show the possible cases of a lockstate in the template //and change lockstate in content definition (and in DB or VFS) if (ls == actUserId) { //steal lock (userlock -> nolock) try { ((A_CmsContentDefinition) o).setLockstate(C_NOT_LOCKED); } catch (Exception e) { if (I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_INFO, getClassName() + " Backoffice getContentLock: Method setLockstate throwed an exception!"); } } //write to DB try { ((A_CmsContentDefinition) o).write(cms); // reflection is not neccessary! } catch (Exception e) { if (I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_INFO, getClassName() + " Backoffice getContentLock: Method write throwed an exception!"); } } templateSelector = "done"; } else { if ((ls != C_NOT_LOCKED) && (ls != actUserId)) { //unlock (lock -> userlock) try { ((A_CmsContentDefinition) o).setLockstate(actUserId); } catch (Exception e) { if (I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_INFO, getClassName() + ": Backoffice getContentLock: Could not set lockstate!"); } } //write to DB try { ((A_CmsContentDefinition) o).write(cms); } catch (Exception e) { if (I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_INFO, getClassName() + ": Backoffice getContentLock: Could not set lockstate!"); } } templateSelector = "done"; } else { //lock (nolock -> userlock) try { ((A_CmsContentDefinition) o).setLockstate(actUserId); } catch (Exception e) { if (I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_INFO, getClassName() + ": Backoffice getContentLock: Could not set lockstate!"); } } //write to DB/VFS try { ((A_CmsContentDefinition) o).write(cms); } catch (Exception e) { if (I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_INFO, getClassName() + ": Backoffice getContentLock: Could not write to content definition!"); } } } } } //finally start the processing processResult = startProcessing(cms, template, elementName, parameters, templateSelector); return processResult; } /** * gets the content definition class method object * @returns object content definition class method object */ private Object getContentMethodObject(CmsObject cms, Class cdClass, String method, Class paramClasses[], Object params[]) { //return value Object retObject = null; if (method != "") { try { retObject = cdClass.getMethod(method, paramClasses).invoke(null, params); } catch (InvocationTargetException ite) { if (I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_INFO, getClassName() + method + " throwed an InvocationTargetException!"); } ite.getTargetException().printStackTrace(); } catch (NoSuchMethodException nsm) { if (I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_INFO, getClassName() + method + ": Requested method was not found!"); } } catch (Exception e) { if (I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_INFO, getClassName() + method + ": Other Exception!"); } } } return retObject; } /** * The old version of the getContentNew methos. Only available for compatilibility resons. * Per default, it uses the edit dialog. If you want to use a seperate input form, you have to create * a new one and write your own getContentNew method in your backoffice class. */ public byte[] getContentNew(CmsObject cms, CmsXmlWpTemplateFile templateFile, String elementName, Hashtable parameters, String templateSelector) throws CmsException { parameters.put("id", "new"); return getContentEdit(cms, templateFile, elementName, parameters, templateSelector); } /** * The new version of the getContentNew methos. Only this one should be used from now on. * Per default, it uses the edit dialog. If you want to use a seperate input form, you have to create * a new one and write your own getContentNew method in your backoffice class. */ public String getContentNew(CmsObject cms,CmsXmlWpTemplateFile template, A_CmsContentDefinition cd, String elementName,Enumeration keys, Hashtable parameters, String templateSelector) throws CmsException { parameters.put("id", "new"); return getContentEdit(cms, template, cd,elementName, keys ,parameters, templateSelector); } /** * Gets the content of a edited entry form. * Has to be overwritten in your backoffice class if the old way of writeing BackOffices is used. * Only available for compatibility reasons. */ public byte[] getContentEdit(CmsObject cms,CmsXmlWpTemplateFile templateFile, String elementName, Hashtable parameters, String templateSelector) throws CmsException { return null; } /** * Gets the content of a edited entry form. * Has to be overwritten in your backoffice class if the new way of writeing BackOffices is used. */ public String getContentEdit(CmsObject cms,CmsXmlWpTemplateFile templateFile, A_CmsContentDefinition cd, String elementName,Enumeration keys, Hashtable parameters, String templateSelector) throws CmsException { return null; } /** * Used for filling the values of a checkbox. * <P> * Gets the resources displayed in the Checkbox group on the new resource dialog. * @param cms The CmsObject. * @param lang The langauge definitions. * @param names The names of the new rescources (used for optional images). * @param values The links that are connected with each resource. * @param parameters Hashtable of parameters. * @returns The vectors names and values are filled with the information found in the * workplace.ini. * @exception Throws CmsException if something goes wrong. */ /*public Integer setCheckbox(CmsObject cms, Vector names, Vector values, Hashtable parameters) throws CmsException { int returnValue = 0; CmsSession session = (CmsSession) cms.getRequestContext().getSession(true); String checkboxValue = (String) session.getValue("checkselect"); if (checkboxValue == null){ checkboxValue = ""; } // add values for the checkbox values.addElement("contents"); values.addElement("navigation"); values.addElement("design"); values.addElement("other"); // add corresponding names for the checkboxvalues names.addElement("contents"); names.addElement("navigation"); names.addElement("design"); names.addElement("other"); // set the return values if (checkboxValue.equals("contents")) { returnValue = 0; } if (checkboxValue.equals("navigation")) { returnValue = 1; } if (checkboxValue.equals("design")) { returnValue = 2; } if (checkboxValue.equals("other")) { returnValue = 3; } return new Integer (returnValue); }*/ /** * Set the correct lockstates in the list output. * Lockstates can be "unlocked", "locked", "locked by user" or "no access" * @param cms The current CmsObject. * @param template The actual template file. * @param cdClass The content defintion. * @param entryObject * @param paramters All template ands URL parameters. */ private void setLockstates(CmsObject cms, CmsXmlWpTemplateFile template, Class cdClass, Object entryObject, Hashtable parameters) { //init lock state vars String la = "false"; Object laObject = new Object(); int ls = -1; String lockString = null; int actUserId = cms.getRequestContext().currentUser().getId(); String isLockedBy = null; //is the content definition object (i.e. the table entry) lockable? try { //get the method Method laMethod = cdClass.getMethod("isLockable", new Class[] {}); //get the returned object laObject = laMethod.invoke(null, null); } catch (InvocationTargetException ite) { if (I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_INFO, getClassName() + ": Backoffice setLockstates: Method isLockable throwed an Invocation target exception!"); } } catch (NoSuchMethodException nsm) { if (I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_INFO, getClassName() + ": Backoffice setLockstates: Requested method isLockable was not found!"); } } catch (Exception e) { if (I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_INFO, getClassName() + ": Backoffice setLockstates: Method isLockable throwed an exception: "+e.toString()); } } //cast the returned object to a string la = (String) laObject.toString(); if (la.equals("false")) { try{ //the entry is not lockable: use standard contextmenue template.setData("backofficecontextmenue", "backofficeedit"); template.setData("lockedby", template.getDataValue("nolock")); } catch (Exception e) { if (I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_INFO, getClassName() + ": Backoffice setLockstates:'not lockable' section hrowed an exception!"); } } } else { //...get the lockstate of an entry try { //get the method lockstate ls = ((A_CmsContentDefinition) entryObject).getLockstate(); } catch (Exception e) { if (I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_INFO, getClassName() + ": Backoffice setLockstates: Method getLockstate throwed an exception: "+e.toString()); } } try { //show the possible cases of a lockstate in the template if (ls == actUserId) { // lockuser isLockedBy = cms.getRequestContext().currentUser().getName(); template.setData("isLockedBy", isLockedBy); // set current users name in the template lockString = template.getProcessedDataValue("lockuser", this, parameters); template.setData("lockedby", lockString); template.setData("backofficecontextmenue", "backofficelockuser"); } else { if (ls != C_NOT_LOCKED) { // lock // set the name of the user who locked the file in the template ... if (ls==C_NO_ACCESS) { lockString = template.getProcessedDataValue("noaccess", this, parameters); template.setData("lockedby", lockString); template.setData("backofficecontextmenue", "backofficenoaccess"); } else { isLockedBy = cms.readUser(ls).getName(); template.setData("isLockedBy", isLockedBy); lockString = template.getProcessedDataValue("lock", this, parameters); template.setData("lockedby", lockString); template.setData("backofficecontextmenue", "backofficelock"); } } else { // nolock lockString = template.getProcessedDataValue("nolock", this, parameters); template.setData("lockedby", lockString); template.setData("backofficecontextmenue", "backofficenolock"); } } } catch (Exception e) { if (I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_INFO, getClassName() + ": Backoffice setLockstates throwed an exception: "+e.toString()); } } } } /** * This method creates the selectbox in the head-frame * @author Tilo Kellermeier */ public Integer getFilter(CmsObject cms, CmsXmlLanguageFile lang, Vector names, Vector values, Hashtable parameters) throws CmsException { CmsSession session = (CmsSession) cms.getRequestContext().getSession(true); int returnValue = 0; String uri = cms.getRequestContext().getUri(); String sessionSelectBoxValue = uri+"selectBoxValue"; Vector filterMethods = getFilterMethods(cms); String tmp = (String) session.getValue(sessionSelectBoxValue); if(tmp != null) { returnValue = Integer.parseInt(tmp); } for (int i = 0; i < filterMethods.size(); i++) { CmsFilterMethod currentFilter = (CmsFilterMethod) filterMethods.elementAt(i); //insert filter in the template selectbox names.addElement(currentFilter.getFilterName()); values.addElement(""+ i); } return new Integer(returnValue); } /** * User method that handles a checkbox in the input form of the backoffice. */ public Object handleCheckbox(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) throws CmsException { Hashtable parameters = (Hashtable) userObject; String returnValue=""; String selected = (String) parameters.get(tagcontent); if (selected != null && selected.equals("on")) { returnValue="checked"; } return returnValue; } /** * Get the all available filter methods. * @param cms The actual CmsObject * @return Vector of Filter Methods */ private Vector getFilterMethods(CmsObject cms) { Vector filterMethods = new Vector(); Class cdClass = getContentDefinitionClass(); try { filterMethods = (Vector) cdClass.getMethod("getFilterMethods", new Class[] {CmsObject.class}).invoke(null, new Object[] {cms}); } catch (InvocationTargetException ite) { //error occured while applying the filter if (I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_INFO, getClassName() + ": Backoffice getContentHead: InvocationTargetException!"); } } catch (NoSuchMethodException nsm) { if (I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_INFO, getClassName() + ": Backoffice getContentHead: Requested method was not found!"); } } catch (Exception e) { if (I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_INFO, getClassName() + ": Backoffice getContentHead: Problem occured with your filter methods: "+e.toString()); } } return filterMethods; } /** * This method creates the selectbox with all avaiable Pages to select from. */ public Integer getSelectedPage(CmsObject cms, CmsXmlLanguageFile lang, Vector names, Vector values, Hashtable parameters) throws CmsException { int returnValue = 0; CmsSession session = (CmsSession) cms.getRequestContext().getSession(true); // get all aviable template selectors Vector templateSelectors=(Vector)session.getValue("backofficepageselectorvector"); // get the actual template selector String selectedPage=(String)parameters.get("backofficepage"); if (selectedPage==null) { selectedPage=""; } // now build the names and values for the selectbox for (int i = 0; i < templateSelectors.size(); i++) { String selector = (String) templateSelectors.elementAt(i); names.addElement(selector); values.addElement(selector); // check for the selected item if (selectedPage.equals(selector)) { returnValue=i; } } return new Integer(returnValue); } /** * This method contains the code used by the getContent method when the new form of the backoffice is processed. * It automatically gets all the data from the "getXYZ" methods and sets it in the correct datablock of the * template. * @param cms The actual CmsObject. * @param id The id of the content definition object to be edited. * @param cd the content definition. * @param session The current user session. * @param template The template file. * @param elementName The emelentName of the template mechanism. * @param parameters All parameters of this request. * @param templateSelector The template selector. * @returns Content of the template, as an array of bytes. */ private byte[] getContentNewInternal(CmsObject cms,String id,A_CmsContentDefinition cd, I_CmsSession session,CmsXmlWpTemplateFile template, String elementName,Hashtable parameters, String templateSelector) throws CmsException{ //return varlue byte[] returnProcess = null; //error storage String error=""; // action value of backoffice buttons String action = (String)parameters.get("action"); // get the correct template selector templateSelector=getTemplateSelector(cms,template,parameters,templateSelector); //process the template for entering the data // first try to do it in the old way to be compatible to the existing modules. returnProcess = getContentNew(cms, template, elementName, parameters, templateSelector); // there was no returnvalue, so the BO uses the new getContentNew method if (returnProcess == null) { //try to get the CD form the session cd = (A_CmsContentDefinition) session.getValue(this.getContentDefinitionClass().getName()); if (cd == null) { //get a new, empty content definition cd = (A_CmsContentDefinition) this.getContentDefinition(cms,this.getContentDefinitionClass()); } //get all existing parameters Enumeration keys=parameters.keys(); //call the new getContentEdit method error = getContentNew(cms, template, cd,elementName, keys ,parameters, templateSelector); // get all getXVY methods to automatically get the data from the CD Vector methods=this.getGetMethods(cd); // get all setXVY methods to automatically set the data into the CD Hashtable setMethods=this.getSetMethods(cd); //set all data from the parameters into the CD this.fillContentDefinition(cms,cd,parameters,setMethods); //now set all the data from the CD into the template this.setDatablocks(template,cd,methods); // store the modified CD in the session session.putValue(this.getContentDefinitionClass().getName(),cd); // check if there was an error found in the input form if (!error.equals("")) { template.setData("error",template.getProcessedDataValue("errormsg")+error); } else { template.setData("error",""); } // now check if one of the exit buttons is used returnProcess = getContentButtonsInternal(cms,cd,session,template,parameters,templateSelector, action,error); } //finally retrun processed data return returnProcess; } /** * This method contains the code used by the getContent method when the edit form of the backoffice is processed. * It automatically gets all the data from the "getXYZ" methods and sets it in the correct datablock of the * template. * @param cms The actual CmsObject. * @param id The id of the content definition object to be edited. * @param cd the content definition. * @param session The current user session. * @param template The template file. * @param elementName The emelentName of the template mechanism. * @param parameters All parameters of this request. * @param templateSelector The template selector. * @returns Content of the template, as an array of bytes. */ private byte[] getContentEditInternal(CmsObject cms,String id,A_CmsContentDefinition cd, I_CmsSession session,CmsXmlWpTemplateFile template, String elementName,Hashtable parameters, String templateSelector) throws CmsException{ //return varlue byte[] returnProcess = null; //error storage String error=""; // action value of backoffice buttons String action = (String)parameters.get("action"); // get the correct template selector templateSelector=getTemplateSelector(cms,template,parameters,templateSelector); //process the template for editing the data // first try to do it in the old way to be compatible to the existing modules. returnProcess = getContentEdit(cms, template, elementName, parameters, templateSelector); // there was no returnvalue, so the BO uses the new getContentEdit method if (returnProcess == null) { //try to get the CD form the session cd = (A_CmsContentDefinition) session.getValue(this.getContentDefinitionClass().getName()); if (cd == null) { // not successful, so read new content definition with given id Integer idvalue=new Integer (id); cd = (A_CmsContentDefinition) this.getContentDefinition(cms,this.getContentDefinitionClass(),idvalue); } //get all existing parameters Enumeration keys=parameters.keys(); //call the new getContentEdit method error = getContentEdit(cms, template, cd,elementName, keys ,parameters, templateSelector); // get all getXVY methods to automatically get the data from the CD Vector getMethods=this.getGetMethods(cd); // get all setXVY methods to automatically set the data into the CD Hashtable setMethods=this.getSetMethods(cd); //set all data from the parameters into the CD this.fillContentDefinition(cms,cd,parameters,setMethods); //now set all the data from the CD into the template this.setDatablocks(template,cd,getMethods); // store the modified CD in the session session.putValue(this.getContentDefinitionClass().getName(),cd); // check if there was an error found in the input form if (!error.equals("")) { template.setData("error",template.getProcessedDataValue("errormsg")+error); } else { template.setData("error",""); } // now check if one of the exit buttons is used returnProcess = getContentButtonsInternal(cms,cd,session,template,parameters,templateSelector, action,error); } //finally return processed data return returnProcess; } /** This method checks the three function buttons on the backoffice edit/new template. * The following actions are excecuted: <ul> * <li>Save: Save the CD to the database if plausi shows no error, return to the edit/new template.</li> * <li>Save & Exit: Save the CD to the database if plausi shows no error, return to the list view. </li> * <li>Exit: Return to the list view without saving. </li> * </ul> * @param cms The actual CmsObject. * @param cd The acutal content definition. * @param session The current user session. * @param template The template file. * @param parameters All parameters of this request. * @param templateSelector The template selector. * @returns Content of the template, as an array of bytes or null if a rediect has happend. */ private byte[] getContentButtonsInternal(CmsObject cms,A_CmsContentDefinition cd, I_CmsSession session, CmsXmlWpTemplateFile template, Hashtable parameters, String templateSelector, String action, String error) throws CmsException{ // storage for possible errors during plausibilization Vector errorCodes=null; // storage for a single error code String errorCode=null; // storage for the field where an error occured String errorField=null; // storage for the error type String errorType=null; // the complete error text displayed on the template //String error=null; // check if one of the exit buttons is used if (action!=null) { // there was no button selected, so the selectbox was used. Do a check of the input fileds. if ((!action.equals("save")) && (!action.equals("saveexit")) && (!action.equals("exit"))){ try { cd.check(false); } catch (CmsPlausibilizationException plex) { // there was an error during plausibilization, so create an error text errorCodes=plex.getErrorCodes(); //loop through all errors for (int i=0;i<errorCodes.size();i++) { errorCode=(String)errorCodes.elementAt(i); // try to get an error message that fits thos this error code exactly if (template.hasData(C_ERRPREFIX+errorCode)) { error+=template.getProcessedDataValue(C_ERRPREFIX+errorCode); } else { // now check if there is a general error message for this field errorField=errorCode.substring(0,errorCode.indexOf(A_CmsContentDefinition.C_ERRSPERATOR)); if (template.hasData(C_ERRPREFIX+errorField)) { error+=template.getProcessedDataValue(C_ERRPREFIX+errorField); } else { // now check if there is at least a general error messace for the error type errorType=errorCode.substring(errorCode.indexOf(C_ERRSPERATOR)+1,errorCode.length()); if (template.hasData(C_ERRPREFIX+errorType)) { error+=template.getProcessedDataValue(C_ERRPREFIX+errorType); } else { // no error dmessage was found, so generate a default one error+="["+errorCode+"]"; } } } } //check if there is an introtext for the errors if (template.hasData("errormsg")) { error=template.getProcessedDataValue("errormsg")+error; } template.setData("error",error); if (session.getValue("backofficepagetemplateselector")!=null) { templateSelector=(String)session.getValue("backofficepagetemplateselector"); parameters.put("backofficepage",templateSelector); } else { templateSelector=null; } } // catch } // the same or save&exit button were pressed, so save the content definition to the // database if (((action.equals("save")) || (action.equals("saveexit"))) && (error.equals(""))){ try { // first check if all plausibilization was ok cd.check(true); // write the data to the database cd.write(cms); } catch (CmsPlausibilizationException plex) { // there was an error during plausibilization, so create an error text errorCodes=plex.getErrorCodes(); //loop through all errors for (int i=0;i<errorCodes.size();i++) { errorCode=(String)errorCodes.elementAt(i); // try to get an error message that fits thos this error code exactly if (template.hasData(C_ERRPREFIX+errorCode)) { error+=template.getProcessedDataValue(C_ERRPREFIX+errorCode); } else { // now check if there is a general error message for this field errorField=errorCode.substring(0,errorCode.indexOf(A_CmsContentDefinition.C_ERRSPERATOR)); if (template.hasData(C_ERRPREFIX+errorField)) { error+=template.getProcessedDataValue(C_ERRPREFIX+errorField); } else { // now check if there is at least a general error messace for the error type errorType=errorCode.substring(errorCode.indexOf(C_ERRSPERATOR)+1,errorCode.length()); if (template.hasData(C_ERRPREFIX+errorType)) { error+=template.getProcessedDataValue(C_ERRPREFIX+errorType); } else { // no error dmessage was found, so generate a default one error+="["+errorCode+"]"; } } } } //check if there is an introtext for the errors if (template.hasData("errormsg")) { error=template.getProcessedDataValue("errormsg")+error; } template.setData("error",error); } catch (Exception ex) { if (I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_CRITICAL, getClassName() + "Error while saving data to Content Definition "+ex.toString()); } throw new CmsException(ex.getMessage(), CmsException.C_UNKNOWN_EXCEPTION, ex); } } //if (save || saveexit) // only exit the form if there was no error if (errorCodes== null) { // the exit or save&exit buttons were pressed, so return to the list if ((action.equals("exit")) || ((action.equals("saveexit")) && (error.equals("")))) { try { // cleanup session session.removeValue(this.getContentDefinitionClass().getName()); session.removeValue("backofficepageselectorvector"); session.removeValue("backofficepagetemplateselector"); //do the redirect // to do: replace the getUri method with getPathInfo if aviable String uri= cms.getRequestContext().getUri(); uri = "/"+uri.substring(1,uri.lastIndexOf("/")); cms.getRequestContext().getResponse().sendCmsRedirect(uri); return null; } catch (java.io.IOException e) { if (I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_CRITICAL, getClassName() + "Error while doing redirect "+e.toString()); } throw new CmsException(e.getMessage(), CmsException.C_UNKNOWN_EXCEPTION, e); } } // if (exit || saveexit) } // noerror } // if (action!=null) return startProcessing(cms,template,"",parameters,templateSelector); } /** * This methods collects all "getXYZ" methods of the actual content definition. This is used * to automatically preset the datablocks of the template with the values stored in the * content definition. * @param contentDefinition The actual Content Definition class * @returns Vector of get-methods */ private Vector getGetMethods (A_CmsContentDefinition contentDefinition) { Vector getMethods=new Vector(); //get all methods of the CD Method[] methods = this.getContentDefinitionClass().getMethods(); for (int i=0;i<methods.length;i++) { Method m=methods[i]; String name=m.getName().toLowerCase(); //now extract all methods whose name starts with a "get" if (name.startsWith("get")) { Class[] param = m.getParameterTypes(); //only take those methods that have no parameter and return a String if (param.length==0) { Class retType=m.getReturnType(); if (retType.equals(java.lang.String.class)) { getMethods.addElement(m); } } } } // for return getMethods; } //getGetMethods /** * This methods collects all "setXYZ" methods of the actual content definition. This is used * to automatically insert the form parameters into the content definition. * @param contentDefinition The actual Content Definition class * @returns Hashtable of set-methods. */ private Hashtable getSetMethods (A_CmsContentDefinition contentDefinition) { Hashtable setMethods=new Hashtable(); //get all methods of the CD Method[] methods = this.getContentDefinitionClass().getMethods(); for (int i=0;i<methods.length;i++) { Method m=methods[i]; String name=m.getName().toLowerCase(); //now extract all methods whose name starts with a "set" if (name.startsWith("set")) { Class[] param = m.getParameterTypes(); //only take those methods that have a single string parameter and return nothing if (param.length==1) { // check if the parameter is a string if (param[0].equals(java.lang.String.class)) { Class retType=m.getReturnType(); // the return value must be void if (retType.toString().equals("void")) { setMethods.put(m.getName().toLowerCase(),m); } } } } } // for return setMethods; } //getsetMethods /** * This method austomatically fills all datablocks in the template that fit to a special name scheme. * A datablock named "xyz" is filled with the value of a "getXYZ" method form the content defintion. * @param template The template to set the datablocks in. * @param contentDefinition The actual content defintion. * @methods A vector with all "getXYZ" methods to be used. * @exception Throws CmsException if something goes wrong. */ private void setDatablocks(CmsXmlWpTemplateFile template, A_CmsContentDefinition contentDefinition, Vector methods) throws CmsException { String methodName=""; String datablockName=""; String value=""; Method method; for (int i=0;i<methods.size();i++){ // get the method name method=(Method)methods.elementAt(i); methodName=method.getName(); //get the datablock name - the methodname without the leading "get" datablockName=(methodName.substring(3,methodName.length())).toLowerCase(); //check if the datablock name ends with a "string" if so, remove it from the datablockname if (datablockName.endsWith("string")) { datablockName=datablockName.substring(0,datablockName.indexOf("string")); } //now call the method to get the value try { Object result=(Object)method.invoke(contentDefinition,new Object[] {}); // check if the get method returns null (default value of the CD), set the datablock to // to "" then. if (result==null) { value=""; } else { // cast the result to a string, only strings can be set into datablocks. value=result+""; } template.setData(datablockName,value); } catch (Exception e) { if (I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_CRITICAL, getClassName() + "Error during automatic call method '"+methodName+"':"+e.toString()); } } // try } //for } //setDatablocks /** * This method automatically fills the content definition with the values read from the template. * A method "setXYZ(value)" of the content defintion is automatically called and filled with the * value of a template input field named "xyz". * @param cms The current CmsObject. * @param contentDefintion The actual content defintion. * @param parameters A hashtable with all template and url parameters. * @param setMethods A hashtable with all "setXYZ" methods * @exception Throws CmsException if something goes wrong. */ private void fillContentDefinition(CmsObject cms,A_CmsContentDefinition contentDefinition, Hashtable parameters, Hashtable setMethods)throws CmsException { Enumeration keys = parameters.keys(); // loop through all values that were returned while(keys.hasMoreElements()) { String key=(String) keys.nextElement(); String value=parameters.get(key).toString(); // not check if this parameter might be an uploaded file boolean isFile=false; // loop through all uploaded files and check if one of those is equal to the value of // the tested parameter. Enumeration uploadedFiles=cms.getRequestContext().getRequest().getFileNames(); byte[] content=cms.getRequestContext().getRequest().getFile(value); while (uploadedFiles.hasMoreElements()){ String filename=(String) uploadedFiles.nextElement(); // there is a match, so this parameter represents a fileupload. if (filename.equals(value)) { isFile=true; } } // try to find a set method for this parameter Method m=(Method)setMethods.get("set"+key); // there was no method found with this name. So try the name "setXYZString" as an alternative. if (m==null) { m=(Method)setMethods.get("set"+key+"string"); } // there was a method found if (m!=null) { //now call the method to set the value try { m.invoke(contentDefinition,new Object[] {value}); // this parameter was the name of an uploaded file. Now try to set the file content // too. if (isFile) { // get the name of the method. It should be "setXYZContent" String methodName=m.getName()+"Content"; // now get the method itself. Method contentMethod=this.getContentDefinitionClass().getMethod(methodName, new Class[] {byte[].class}); //finally invoke it. contentMethod.invoke(contentDefinition, new Object[] {content}); } } catch (Exception e) { if (I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_CRITICAL, getClassName() + "Error during automatic call method '"+m.getName()+"':"+e.toString()); } } // try } } // while } //fillContentDefiniton /** * Checks how many template selectors are available in the backoffice template and selects the * correct one. * @param cms The current CmsObject. * @param template The current template. * @param parameters All template and URL parameters. * @param templateSelector The current template selector. * @returns The new template selector. * @exception Throws CmsException if something goes wrong. */ private String getTemplateSelector(CmsObject cms, CmsXmlWpTemplateFile template, Hashtable parameters,String templateSelector) throws CmsException { CmsSession session = (CmsSession) cms.getRequestContext().getSession(true); //store the old templateSelector in the session if (templateSelector!=null) { session.putValue("backofficepagetemplateselector",templateSelector); } // Vector to store all template selectors in the template Vector selectors=new Vector(); // Vector to store all useful template selectory in the template Vector filteredSelectors=new Vector(); selectors=template.getAllSections(); // loop through all templateseletors and find the useful ones for (int i=0;i<selectors.size();i++) { String selector=(String)selectors.elementAt(i); if ((!selector.equals(C_DEFAULT_SELECTOR)) && (!selector.equals(C_DONE_SELECTOR))) { filteredSelectors.addElement(selector); } } String selectedPage=(String)parameters.get("backofficepage"); // check if there is more than one useful template selector. If not, do not display the selectbox. if (selectors.size()<4) { template.setData("BOSELECTOR",""); } if (selectedPage!=null) { templateSelector=selectedPage; } else if (filteredSelectors.size()>0) { templateSelector=(String)filteredSelectors.elementAt(0); session.putValue("backofficepagetemplateselector",templateSelector); } session.putValue("backofficepageselectorvector",filteredSelectors); return templateSelector; } }
package com.poco.PoCoCompiler; import com.poco.Extractor.Closure; import com.poco.Extractor.VarTypeVal; import com.poco.PoCoParser.PoCoParser; import com.poco.PoCoParser.PoCoParserBaseVisitor; import org.antlr.v4.runtime.misc.NotNull; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ExtractClosure extends PoCoParserBaseVisitor<Void> { private Closure closure; public Closure getClosure() { return closure; } public void setClosure(Closure closure) { this.closure = closure; } public ExtractClosure(Closure closure) { this.closure = closure; } private boolean frmOpparlist = false; private String closureVal; private String binding; private String policyName = ""; /** * Generates code for class representing a PoCo policy. This is the first visit method called. * * @param ctx * @return */ @Override public Void visitPocopol(@NotNull PoCoParser.PocopolContext ctx) { // need handle when policy has parameteres (e.g., OutgoingMail(String ContactInfo)) closure = new Closure(); policyName = ctx.id().getText().trim() + "_"; if (ctx.paramlist() != null && ctx.paramlist().getText().trim().length() > 0) { PoCoParser.ParamlistContext paraList = ctx.paramlist(); while (paraList != null) { VarTypeVal varTyCal = new VarTypeVal(paraList.qid().getText(), paraList.id().getText()); closure.addClosure(policyName + paraList.id().getText(), varTyCal); paraList = paraList.paramlist(); } } visitChildren(ctx); return null; } @Override public Void visitVardecls(@NotNull PoCoParser.VardeclsContext ctx) { if (ctx.vardecl() != null) { //now only deal with single policy, need add parents in future visitChildren(ctx); } return null; } @Override public Void visitVardecl(@NotNull PoCoParser.VardeclContext ctx) { if (ctx.id() != null) { closure.addClosure(policyName + ctx.id().getText(), new VarTypeVal(null, null)); } return null; } @Override public Void visitMacrodecls(@NotNull PoCoParser.MacrodeclsContext ctx) { if (ctx.macrodecl() != null) { if (closure == null) closure = new Closure(); visitChildren(ctx); } return null; } @Override public Void visitMacrodecl(@NotNull PoCoParser.MacrodeclContext ctx) { String str = null; VarTypeVal varTyCal; if (ctx.RETYPE() != null) str = ctx.re().getText(); else str = ctx.sre().getText(); //regex for Object String reg = " Pattern pattern = Pattern.compile(reg); Matcher matcher; //regex for function def. String reg1 = "(.+)\\((.+)\\)"; Pattern pattern1 = Pattern.compile(reg1); Matcher matcher1 = pattern1.matcher(str); //@SendMail(msg)[`javax.mail.Transport.send(#javax.mail.Message{$msg})']: RE if (matcher1.find()) { String strFunNm = matcher1.group(1).toString().trim(); //e.g., #javax.mail.Message{$msg} String args = matcher1.group(2).toString().trim(); String[] strArgs = args.split(","); if (strArgs != null) { for (int i = 0; i < strArgs.length; i++) { matcher = pattern.matcher(strArgs[i]); if (matcher.find()) { String varTyp = matcher.group(1).toString().trim(); String varName = matcher.group(2).toString(); if (varName.startsWith("$")) { String varNm = varName.substring(1, varName.length()); String existTyp = closure.loadClosure(policyName + varNm).getVarType(); if (existTyp == null || !existTyp.equals(varTyp)) { String context = closure.loadClosure(policyName + varNm).getVarContext(); closure.updateClosure(policyName + varNm, new VarTypeVal(varTyp, context)); } } } } } varTyCal = new VarTypeVal("java.lang.String", strFunNm + "(" + args + ")"); } else { //@ports()[!`#int{143|993|25|110|995|2080}'] :RE matcher = pattern.matcher(str); if (matcher.find()) { varTyCal = new VarTypeVal(matcher.group(1).toString().trim(), getObjVal(str)); } else { varTyCal = new VarTypeVal(null, getObjVal(str)); } } closure.addClosure(policyName + ctx.id().getText(), varTyCal); return null; } @Override public Void visitIre(@NotNull PoCoParser.IreContext ctx) { if (ctx.ACTION() != null) { if(ctx.re(0).AT() != null) visitRe(ctx.re(0)); } else { visitRe(ctx.re(0)); visitRe(ctx.re(1)); } return null; } public Void visitRe(@NotNull PoCoParser.ReContext ctx) { if (ctx.AT() != null ) { binding = ctx.id().getText(); visitChildren(ctx); binding = null; } else { if (frmOpparlist == false) { if (ctx.function() != null) { closureVal = "* "; if (ctx.function().INIT() != null) { closureVal = ctx.function().fxnname().getText() + "new"; } else { //has return value type if (ctx.function().fxnname().getText().trim().split(" ").length == 2) closureVal = ctx.function().fxnname().getText(); else closureVal += ctx.function().fxnname().getText(); } if (ctx.function().arglist() != null) { if (ctx.function().arglist().getText().length() == 0) { closureVal += "()"; } else { frmOpparlist = true; visitChildren(ctx); frmOpparlist = false; } } else { closureVal += "()"; } String existTyp; if (closure.loadClosure(policyName + binding) != null) { if (closure.loadClosure(policyName + binding).getVarType() == null) existTyp = "java.lang.String"; else existTyp = closure.loadClosure(policyName + binding).getVarType(); } else existTyp = "java.lang.String"; closure.updateClosure(policyName + binding, new VarTypeVal(existTyp, closureVal)); } else if (ctx.object() != null) { } else { visitChildren(ctx); } } else { //ptFromOpparamlist = true if (ctx.rewild() != null) { closureVal = closureVal + "(..)"; } else if (ctx.qid() != null) { String strval = ctx.qid().getText().trim(); if (closure != null && closure.isContains(policyName + strval)) { closureVal += "($$" + policyName + strval + "$$)"; } else throw new NullPointerException("No such var exist."); } else if (ctx.object() != null) { if (ctx.object().POUND() != null) { //format as #qid{re} closureVal = closureVal + "(" + ctx.object().qid().getText(); String reStr = ctx.object().re().getText(); //if reStr does not contain the "$", means the value is static, //so we can check it statically, otherwise we have to check it dynamically if (!reStr.contains("$")) { if (reStr.equals("%")) closureVal += "$$$*.*$$$"; else closureVal += "$$$" + reStr.replaceAll("%", "*") + "$$$"; } else { //so the value will be dynamic closureVal += reStr; } closureVal += ")"; } else if (ctx.id() != null) { closureVal = closureVal + "(" + ctx.id().getText() + ")"; } else { //Null case closureVal = closureVal + "(..)"; } } else if (ctx.rebop() != null) { visitRe(ctx.re(0)); visitRe(ctx.re(1)); } else { if (ctx.getText().trim().length() > 0) { String reg = "\\((.+)\\)"; Pattern pattern = Pattern.compile(reg); Matcher matcher = pattern.matcher(ctx.getText().trim()); if (matcher.find()) closureVal = closureVal + "(" + ctx.getText() + ")"; } } } } return null; } private String getObjVal(String str) { String tempStr = ""; String returnStr = ""; String reg = " Pattern pattern = Pattern.compile(reg); Matcher matcher = pattern.matcher(str); if (matcher.find()) tempStr = matcher.group(2).toString().trim().replaceAll("\\\\", ""); else tempStr = str.replaceAll("\\\\", ""); if (tempStr.indexOf('$') == -1) { returnStr = tempStr; } else { while (tempStr.indexOf('$') != -1) { returnStr += tempStr.substring(0, tempStr.indexOf('$')); tempStr = tempStr.substring(tempStr.indexOf('$'), tempStr.length()); if (tempStr.indexOf(' ') != -1) { returnStr += "$$" + policyName + tempStr.substring(1, tempStr.indexOf(' ')) + "$$"; tempStr = tempStr.substring(tempStr.indexOf(' ') + 1, tempStr.length()); } } returnStr += tempStr; } return returnStr; } }
package com.salesforce.samples.vfconnector; import java.util.HashMap; import org.apache.http.cookie.Cookie; import org.json.JSONObject; import android.os.Bundle; import android.util.Log; import android.webkit.CookieManager; import android.webkit.CookieSyncManager; import com.phonegap.DroidGap; import com.salesforce.androidsdk.app.ForceApp; import com.salesforce.androidsdk.rest.ClientManager; import com.salesforce.androidsdk.rest.ClientManager.RestClientCallback; import com.salesforce.androidsdk.rest.RestClient; public class VFConnectorActivity extends DroidGap { public static String TAG = "VFConnector"; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //ensure we have a CookieSyncManager CookieSyncManager.createInstance(this); //ensure that we allow urls from all salesforce domains to be loaded this.addWhiteListEntry("force.com", true); this.addWhiteListEntry("salesforce.com", true); //super.loadUrl("file:///android_asset/www/unauthorized.html"); final String accountType = getString(R.string.account_type); new ClientManager(this, accountType).getRestClient(this, new RestClientCallback() { public void authenticatedRestClient(RestClient client) { if (client == null) { ForceApp.APP.logout(accountType); return; } loggedIn(client); } }); } @Override public void onResume() { CookieSyncManager.getInstance().startSync(); super.onResume(); } @Override public void onPause() { CookieSyncManager.getInstance().stopSync(); super.onPause(); } protected void loggedIn(RestClient client) { //TODO setup cookies //TODO load real content //super.loadUrl("file:///android_asset/www/index.html"); this.setSidCookies(client); String host = client.getBaseUrl().getHost(); String finalURL = "https://" + host + "/apex/BasicVFPage"; super.loadUrl(finalURL); } protected void addSidCookieForDomain(CookieManager cookieMgr, String domain, String sid) { String cookieStr = "sid=" + sid + "; domain=" + domain; cookieMgr.setCookie(domain, cookieStr); Log.i(TAG,"addSidCookieForDomain: " + domain); } protected void setSidCookies(RestClient client) { CookieSyncManager cookieSyncMgr = CookieSyncManager.getInstance(); CookieManager cookieMgr = CookieManager.getInstance(); cookieMgr.removeSessionCookie(); String accessToken = client.getAuthToken(); String domain = client.getBaseUrl().getHost(); //set the cookie on all possible domains we could access addSidCookieForDomain(cookieMgr,domain,accessToken); addSidCookieForDomain(cookieMgr,".force.com",accessToken); addSidCookieForDomain(cookieMgr,".salesforce.com",accessToken); cookieSyncMgr.sync(); } // protected void sendJavascriptLoginEvent(RestClient client) { // HashMap<String, String> data = new HashMap<String, String>(); // data.put("clientId", getString(R.string.oauth_client_id)); // data.put("loginUrl", getString(R.string.login_url)); // data.put("apiVersion", getString(R.string.api_version)); // data.put("accessToken", client.getAuthToken()); // data.put("instanceUrl", client.getBaseUrl().toString()); // data.put("refreshToken", client.getRefreshToken()); // String eventJs = "{'data':" + new JSONObject(data).toString() + "}"; // String jsCall = "onSalesforceOAuthLogin(" + eventJs + ")"; // sendJavascript(jsCall); }
package com.tilioteo.hypothesis.ui; import java.util.Collection; import javax.servlet.annotation.WebServlet; import org.apache.log4j.Logger; import org.vaadin.jouni.animator.AnimatorProxy; import org.vaadin.jouni.animator.AnimatorProxy.AnimationEvent; import org.vaadin.jouni.animator.shared.AnimType; import com.tilioteo.hypothesis.core.CommandQueue; import com.tilioteo.hypothesis.core.CommandScheduler; import com.tilioteo.hypothesis.event.AbstractNotificationEvent; import com.tilioteo.hypothesis.event.AfterFinishSlideEvent; import com.tilioteo.hypothesis.event.AfterPrepareTestEvent; import com.tilioteo.hypothesis.event.CloseTestEvent; import com.tilioteo.hypothesis.event.ErrorNotificationEvent; import com.tilioteo.hypothesis.event.FinishTestEvent; import com.tilioteo.hypothesis.event.ProcessEvent; import com.tilioteo.hypothesis.event.ProcessEventListener; import com.tilioteo.hypothesis.event.RenderContentEvent; import com.tilioteo.hypothesis.extension.PluginManager; import com.tilioteo.hypothesis.model.ProcessModel; import com.tilioteo.hypothesis.processing.Command; import com.tilioteo.hypothesis.servlet.ProcessServlet; import com.vaadin.annotations.PreserveOnRefresh; import com.vaadin.annotations.Theme; import com.vaadin.annotations.VaadinServletConfiguration; import com.vaadin.server.Page; import com.vaadin.server.VaadinRequest; import com.vaadin.server.ClientConnector.DetachListener; import com.vaadin.server.VaadinServlet; import com.vaadin.ui.Component; import com.vaadin.ui.ComponentContainer; import com.vaadin.ui.JavaScript; import com.vaadin.ui.Window.CloseEvent; import com.vaadin.ui.Notification; import com.vaadin.ui.VerticalLayout; /** * @author kamil * */ @SuppressWarnings("serial") @Theme("hypothesis") @PreserveOnRefresh //@Push public class ProcessUI extends HUI implements ProcessEventListener, DetachListener, CommandScheduler { private static Logger log = Logger.getLogger(ProcessUI.class); public static final String FULLSCREEN_PARAMETER = "fs"; public static final String BACK_PARAMETER = "bk"; public static final String TOKEN_PARAMETER = "token"; public static final String CLOSE_URL = "/resource/close.html"; public static final String ERROR_INVALID_ACCESS = "Invalid access."; /** * sets empty vertical layout to remove old content */ public void clearContent(boolean animate, final Command nextCommand) { log.debug("clearContent::"); removeAllTimers(); removeAllShortcutKeys(); if (animate) { Component content = getContent(); if (content instanceof ComponentContainer) { AnimatorProxy animator = new AnimatorProxy(); animator.addListener(new AnimatorProxy.AnimationListener() { @Override public void onAnimation(AnimationEvent event) { setContent(clearLayout); //scheduleCommand(nextCommand); Command.Executor.execute(nextCommand); } }); ((ComponentContainer)content).addComponent(animator); animator.animate(content, AnimType.FADE_OUT).setDuration(300).setDelay(0); } } else { setContent(clearLayout); //scheduleCommand(nextCommand); Command.Executor.execute(nextCommand); } } private void setSlideContent(Component component, Collection<Timer> timers, Collection<ShortcutKey> shortcutKeys) { log.debug("setSlideContent::"); setContent(component); // add timers for (Timer timer : timers) { addTimer(timer); } // add shortcut keys for (ShortcutKey shortcutKey : shortcutKeys) { addShortcutKey(shortcutKey); } focus(); } @Override public void detach(DetachEvent event) { log.debug("ProcessUI detached."); processModel.requestBreak(); processModel.purgeFactories(); } @Override public void close() { log.debug("close::"); super.close(); if (!requestBack) { log.debug("Setting close url."); String path = VaadinServlet.getCurrent().getServletContext().getContextPath(); Page.getCurrent().setLocation(path + CLOSE_URL); } else { log.debug("History back."); JavaScript javaScript = Page.getCurrent().getJavaScript(); javaScript.execute("window.history.back();"); } } public boolean isFullscreen() { return requestFullscreen; } public boolean isAnimated() { return animate; } }
package com.xrtb.exchanges.adx; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletResponse; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.protobuf.ByteString; import com.google.protobuf.ProtocolStringList; import com.xrtb.bidder.RTBServer; import com.xrtb.common.Campaign; import com.xrtb.common.Creative; import com.xrtb.exchanges.adx.RealtimeBidding.BidRequest.AdSlot; import com.xrtb.exchanges.adx.RealtimeBidding.BidRequest.Mobile; import com.xrtb.exchanges.adx.RealtimeBidding.BidRequest.Mobile.DeviceOsVersion; import com.xrtb.exchanges.adx.RealtimeBidding.BidRequest.Video.VideoFormat; import com.xrtb.pojo.BidRequest; import com.xrtb.pojo.BidResponse; import com.xrtb.pojo.Video; interface Command { void runCommand(RealtimeBidding.BidRequest x, Map db, String key); } public class AdxBidRequest extends BidRequest { public static byte e_key []; public static byte i_key []; static Map<String, Command> methodMap = new HashMap<String, Command>(); static { methodMap.put("BidRequest.detected_language", new Command() { public void runCommand(RealtimeBidding.BidRequest x, Map d, String key) { d.put(key, x.getDetectedLanguage(0)); }; }); methodMap.put("BidRequest.postal_code", new Command() { public void runCommand(RealtimeBidding.BidRequest x, Map d, String key) { if (x.hasPostalCode()) d.put(key, x.getPostalCode()); else d.put(key, null); }; }); methodMap.put("BidRequest.postal_code_prefix", new Command() { public void runCommand(RealtimeBidding.BidRequest x, Map d, String key) { if (x.hasPostalCodePrefix()) d.put(key, x.getPostalCodePrefix()); else d.put(key, null); }; }); methodMap.put("BidRequest.google_user_id", new Command() { public void runCommand(RealtimeBidding.BidRequest x, Map d, String key) { if (x.hasGoogleUserId()) d.put(key, x.getGoogleUserId()); else d.put(key, null); }; }); methodMap.put("BidRequest.seller_network_id", new Command() { public void runCommand(RealtimeBidding.BidRequest x, Map d, String key) { if (x.hasSellerNetworkId()) d.put(key, x.getSellerNetworkId()); else d.put(key, null); }; }); methodMap.put("BidRequest.publisher_settings_list_id", new Command() { public void runCommand(RealtimeBidding.BidRequest x, Map d, String key) { if (x.hasPublisherSettingsListId()) d.put(key, x.getPublisherSettingsListId()); else d.put(key, null); }; }); methodMap.put("BidRequest.anonymous_id", new Command() { public void runCommand(RealtimeBidding.BidRequest x, Map d, String key) { if (x.hasAnonymousId()) d.put(key, x.getAnonymousId()); else d.put(key, null); }; }); methodMap.put("BidRequest.constrained_usage_google_user_id", new Command() { public void runCommand(RealtimeBidding.BidRequest x, Map d, String key) { if (x.hasConstrainedUsageGoogleUserId()) d.put(key, x.getConstrainedUsageGoogleUserId()); else d.put(key, null); }; }); methodMap.put("BidRequest.geo_criteria_id", new Command() { public void runCommand(RealtimeBidding.BidRequest x, Map d, String key) { if (x.hasGeoCriteriaId()) d.put(key, x.getGeoCriteriaId()); }; }); methodMap.put("BidRequest.mobile.platform", new Command() { public void runCommand(RealtimeBidding.BidRequest x, Map d, String key) { Mobile m = x.getMobile(); if (m == null) return; if (m.hasPlatform()) { d.put(key, m.getPlatform()); } }; }); methodMap.put("BidRequest.mobile.mobile_device_type", new Command() { public void runCommand(RealtimeBidding.BidRequest x, Map d, String key) { Mobile m = x.getMobile(); if (m == null) return; if (m.hasMobileDeviceType()) { d.put(key, m.getMobileDeviceType()); } }; }); methodMap.put("BidRequest.mobile.screen_orientation", new Command() { public void runCommand(RealtimeBidding.BidRequest x, Map d, String key) { Mobile m = x.getMobile(); if (m == null) return; if (m.hasScreenOrientation()) { d.put(key, m.getScreenOrientation()); } }; }); methodMap.put("BidRequest.mobile.brand", new Command() { public void runCommand(RealtimeBidding.BidRequest x, Map d, String key) { Mobile m = x.getMobile(); if (m == null) return; if (m.hasBrand()) { d.put(key, m.getBrand()); } }; }); methodMap.put("BidRequest.mobile.is_app", new Command() { public void runCommand(RealtimeBidding.BidRequest x, Map d, String key) { Mobile m = x.getMobile(); if (m == null) return; if (m.hasIsApp()) { d.put(key, m.getIsApp()); } }; }); methodMap.put("BidRequest.mobile.is_interstital_request", new Command() { public void runCommand(RealtimeBidding.BidRequest x, Map d, String key) { Mobile m = x.getMobile(); if (m == null) return; if (m.hasIsInterstitialRequest()) { d.put(key, m.getIsInterstitialRequest()); } }; }); methodMap.put("BidRequest.mobile.os_version.os_version_major", new Command() { public void runCommand(RealtimeBidding.BidRequest x, Map d, String key) { Mobile m = x.getMobile(); if (m == null) return; DeviceOsVersion v = m.getOsVersion(); if (v == null) return; if (v.hasOsVersionMajor()) { d.put(key, v.getOsVersionMajor()); } }; }); methodMap.put("BidRequest.mobile.os_version.os_version_minor", new Command() { public void runCommand(RealtimeBidding.BidRequest x, Map d, String key) { Mobile m = x.getMobile(); if (m == null) return; DeviceOsVersion v = m.getOsVersion(); if (v == null) return; if (v.hasOsVersionMinor()) { d.put(key, v.getOsVersionMinor()); } }; }); methodMap.put("BidRequest.mobile.os_version.os_version_micro", new Command() { public void runCommand(RealtimeBidding.BidRequest x, Map d, String key) { Mobile m = x.getMobile(); if (m == null) return; DeviceOsVersion v = m.getOsVersion(); if (v == null) return; if (v.hasOsVersionMicro()) { d.put(key, v.getOsVersionMicro()); } }; }); } List<Integer> excludedCategories = new ArrayList<Integer>(); List<Integer> allowedVendorTypeList = new ArrayList<Integer>(); List<Integer> excludedAttributesList = new ArrayList<Integer>(); int adSlotId; ObjectNode root; public static final String ADX = "adx"; /** * The protobuf version of the bid request */ RealtimeBidding.BidRequest internal; /** * Empty constructor */ public AdxBidRequest() { } /** * Make bid request from a string version of the protobuf. * @param str String. The string to read. * @throws Exception on parsing errors. */ public AdxBidRequest(String str) throws Exception { } /** * Interrogate the bid request */ @Override public Object interrogate(String line) { return database.get(line); } String html_snippet = "%%WINNING_PRICE%%http: String clickthrough = "http://rtb4free.com/click=1"; String creativeid = "my-creative-1234ABCD"; @Override public boolean checkNonStandard(Creative creat, StringBuilder sb) { Integer category = (Integer)creat.extensions.get("category"); Integer type = (Integer)creat.extensions.get("vendorType"); List<Integer> attrs = (List<Integer>)creat.extensions.get("attributes"); if (category != null && excludedCategories.contains(category)) { if (sb != null) { sb.append("Excluded categories contains this category: "); sb.append(category); } return false; } if (allowedVendorTypeList != null && allowedVendorTypeList.size() != 0) { if (sb != null) { sb.append("Allowed vendor types does not contain this vendorType: "); sb.append(type); } return false; } if (attrs != null && excludedAttributesList != null && excludedAttributesList.size() != 0 ) { List<Integer> copy = new ArrayList(attrs); copy.retainAll(excludedAttributesList); if (copy.size() > 0) return false; return true; } return true; } /** * Build the bid response from the bid request, campaign and creatives */ @Override public BidResponse buildNewBidResponse(Campaign camp, Creative creat, int xtime) throws Exception { Integer category = (Integer)creat.extensions.get("category"); Integer type = (Integer)creat.extensions.get("vendorType"); AdxBidResponse response = null; response = new AdxBidResponse(this,camp,creat); response.slotSetId(adSlotId); response.slotSetMaxCpmMicros((int)creat.getPrice()); response.adSetHeight(this.h); response.adSetWidth(this.w); response.adAddClickThroughUrl(clickthrough);; if ((type = (Integer)creat.extensions.get("vendorType")) != null) response.adAddVendorType(type); if (category != null) response.adAddCategory(type); response.adid = creat.impid; String html = null; try { html = response.getTemplate(); } catch (Exception error) { error.printStackTrace(); } response.adSetHtmlSnippet(html); response.build(xtime); return response; } /** * Write the nobid associated with this bid request */ @Override public void writeNoBid(HttpServletResponse response, long time) throws Exception { //new AdxBidResponse((int)time).writeTo(response); AdxBidResponse resp = new AdxBidResponse(); resp.setNoBid(); resp.writeTo(response); } /** * Return the no bid code. Note, for Adx. you have to return 200 * @return int. The return code. */ @Override public int returnNoBidCode() { return RTBServer.BID_CODE; } /** * Return the application type this bid request/response uses * @return String. The content type to return. */ @Override public String returnContentType() { return "application/octet-string"; } static int TOTAL = 1; /** * Constructor using input stream * @param in InputStream. Content of the body as input stream * @throws Exception on I/O or parsing errors. */ public AdxBidRequest(InputStream in) throws Exception { root = BidRequest.factory.objectNode(); internal = RealtimeBidding.BidRequest.parseFrom(in); System.out.println("========>" + TOTAL); TOTAL++; int ads = internal.getAdslotCount(); ByteString id = internal.getId(); String ip = convertIp(internal.getIp()); this.id = convertToHex(internal.getId()); String ua = internal.getUserAgent(); ObjectNode device = AdxBidRequest.factory.objectNode(); device.put("ua", ua); root.put("device", device); ObjectNode user = BidRequest.factory.objectNode(); root.put("user", user); root.put("id", BidRequest.factory.textNode(this.id)); device.put("ip", ip); database.put("exchange", ADX); ArrayNode impressions = BidRequest.factory.arrayNode(); root.put("imp",impressions); boolean isApp = false; if (internal.hasMobile()) { Mobile m = internal.getMobile(); if (m.hasPlatform()) { device.put("model", BidRequest.factory.textNode(m.getPlatform())); } if (m.hasCarrierId()) { device.put("carrier", BidRequest.factory.numberNode(m.getCarrierId())); } if (m.hasOsVersion()) { DeviceOsVersion d = m.getOsVersion(); StringBuilder sb = new StringBuilder(); if (d.hasOsVersionMajor()) { sb.append(d.getOsVersionMajor()); } if (d.hasOsVersionMinor()) { sb.append("."); sb.append(d.getOsVersionMinor()); } if (d.hasOsVersionMicro()) { sb.append("."); sb.append(d.getOsVersionMicro()); } device.put("osv", BidRequest.factory.textNode(sb.toString())); if (m.hasIsApp()) isApp = m.getIsApp(); } } ObjectNode appOrSite = BidRequest.factory.objectNode(); if (isApp) root.put("app", appOrSite); else root.put("site", appOrSite); boolean isVideo = false; if (internal.hasVideo()) { if (internal.hasVideo()) { RealtimeBidding.BidRequest.Video gv = internal.getVideo(); this.video = new Video(); video.maxduration = gv.getMaxAdDuration(); video.minduration = gv.getMinAdDuration(); List<VideoFormat> formats = gv.getAllowedVideoFormatsList(); for (VideoFormat v : formats) { System.out.println("FORMAR: " + v.toString()); } } isVideo = true; } for (int i=0; i<ads;i++) { ObjectNode imp = BidRequest.factory.objectNode(); impressions.add(imp); ObjectNode x = BidRequest.factory.objectNode(); if (isVideo) { imp.put("video", x); x.put("maxduration", BidRequest.factory.numberNode(video.maxduration)); x.put("minduration", BidRequest.factory.numberNode(video.minduration)); } else { imp.put("banner", x); } AdSlot as = internal.getAdslot(i); try { this.w = as.getWidth(i); this.h = as.getHeight(i); } catch (Exception error) { this.w = -1; this.h = -1; } x.put("w", BidRequest.factory.numberNode(this.w)); x.put("h", BidRequest.factory.numberNode(this.h)); this.bidFloor = new Double(as.getMatchingAdData(i).getMinimumCpmMicros()/1000000); this.adSlotId = as.getId(); imp.put("bidfloor", BidRequest.factory.numberNode(this.bidFloor)); imp.put("id", BidRequest.factory.textNode(Integer.toString(this.adSlotId))); excludedCategories = as.getExcludedSensitiveCategoryList(); allowedVendorTypeList = as.getAllowedVendorTypeList(); excludedAttributesList = as.getExcludedAttributeList(); database.put("BidRequest.AdSlot.excluded_attribute",as.getExcludedAttributeList()); database.put("BidRequest.AdSlot.allowed_vendor_type",as.getAllowedVendorTypeList()); database.put("BidRequest.AdSlot.matching_ad_data[adgroup_id]",as.getMatchingAdData(i).getAdgroupId()); Map m = as.getAllFields(); System.out.println("XXXXXXXXXXXXXXX\n" + m + "\nXXXXXXXXXXXXXXX"); } if (internal.hasEncryptedHyperlocalSet()) { ByteString bs = internal.getEncryptedHyperlocalSet(); } ProtocolStringList list = internal.getDetectedLanguageList(); ArrayNode ar = BidRequest.factory.arrayNode(); List<String> slist = new ArrayList<String>(); for (String s : list) { ar.add(s); } user.put("detected_language",ar); ObjectNode geo = BidRequest.factory.objectNode(); device.put("geo", geo); if (internal.hasPostalCode()) { geo.put("zip", BidRequest.factory.textNode(internal.getPostalCode())); } if (internal.hasIsTest()) root.put("is_test", BidRequest.factory.booleanNode(internal.getIsTest())); if (internal.hasGoogleUserId()) user.put("google_user_id", BidRequest.factory.textNode(internal.getGoogleUserId())); if (internal.hasCookieAgeSeconds()) user.put("cookie_age_seconds", BidRequest.factory.numberNode(internal.getCookieAgeSeconds())); System.out.println(internal); byte [] bytes = internal.toByteArray(); String str = new String(Base64.encodeBase64(bytes)); root.put("protobuf", str); internalSetup(); } static String makeKey(String s) { StringBuilder key = new StringBuilder("BidRequest."); key.append(s); return key.toString(); } void internalSetup() { for (int i = 0; i < keys.size(); i++) { String key = keys.get(i); if (key.startsWith("BidRequest")) { methodMap.get(key).runCommand(internal, database, key); } } rootNode = (JsonNode)root; } /** * Convert IP address to dotted decimal (ipv4) and coloned decimal (ipv6) * @param ip ByteString. The bytes to decode * @return String. The ip address form of the byte stream. */ protected static String convertIp(ByteString ip) { ByteBuffer b = ip.asReadOnlyByteBuffer(); StringBuilder sb = new StringBuilder(); if (ip.size() == 3) { for (int i=0;i<ip.size();i++) { sb.append(Integer.toUnsignedString(0xff & b.get(i))); sb.append("."); } sb.append("0"); } else { for (int i=0;i<ip.size();i++) { sb.append(Integer.toUnsignedString(0xff & b.get(i))); sb.append(":"); } sb.append("0"); } return sb.toString(); } /** * Return the hex string * @param ip ByteString. Source to convert * @return String. The string encoded version of the source, as a string og hex digits. */ protected static String convertToHex(ByteString ip) { ByteBuffer b = ip.asReadOnlyByteBuffer(); StringBuilder sb = new StringBuilder(); for (int i=0;i<ip.size();i++) { sb.append(Integer.toHexString(0xff & b.get(i))); } return sb.toString(); } @Override public void handleConfigExtensions(Map extension) throws Exception { String key = (String)extension.get("e_key"); AdxWinObject.encryptionKeyBytes = e_key = javax.xml.bind.DatatypeConverter.parseBase64Binary(key); key = (String)extension.get("i_key"); AdxWinObject.integrityKeyBytes = i_key = javax.xml.bind.DatatypeConverter.parseBase64Binary(key); } }
package structure; import java.io.IOException; import java.io.InputStream; import org.biojava.bio.structure.Structure; import org.biojava.bio.structure.io.PDBFileParser; import org.biojava.bio.structure.io.PDBFileReader; /** a simple demo to demonstrating how to load a PDB file * * @author Andreas Prlic * */ public class LoadStructure { public static void main(String[] args){ LoadStructure demo = new LoadStructure(); if (args.length == 0){ demo.readStructureFromStream(); } else { // the user provided a Path to a PDB file demo.loadStructure(args[0]); } demo.loadStructureById(); } /** access a structure from a directory by using a PDB code. * The PDBFileReader class takes care of compressed PDB files * * @param pdbCode * @return */ public Structure loadStructureById() { String path = "/path/to/PDB/directory"; PDBFileReader pdbreader = new PDBFileReader(); pdbreader.setPath(path); Structure structure = null; try { structure = pdbreader.getStructureById("5pti"); } catch (IOException e){ e.printStackTrace(); } return structure; } public Structure loadStructure(String pathToPDBFile){ PDBFileReader pdbreader = new PDBFileReader(); Structure structure = null; try{ structure = pdbreader.getStructure(pathToPDBFile); System.out.println(structure); } catch (IOException e) { e.printStackTrace(); } return structure; } public Structure readStructureFromStream() { InputStream inStream = this.getClass().getResourceAsStream("/files/5pti.pdb"); Structure structure = null; PDBFileParser pdbpars = new PDBFileParser(); try { structure = pdbpars.parsePDBFile(inStream) ; System.out.println(structure); } catch (IOException e) { e.printStackTrace(); } return structure; } }
package edisyn.synth.tuning; import edisyn.*; public abstract class TuningDefinition { int bases[] = new int[128]; int detunes[] = new int[128]; int rootMIDINote = 0; double rootFrequency = 1; boolean configured; public void setConfigured(boolean val) { configured = val; } public boolean isConfigured() { return configured; } public int[] getBases() { return bases; } public int[] getDetunes() { return detunes; } public int getRootMIDINote() { return rootMIDINote; } public void setRootMIDINote(int val) { rootMIDINote = val; } public double getRootFrequency() { return rootFrequency; } public void setRootFrequency(double val) { rootFrequency = val; } static double LOG_2 = Math.log(2); static double INV_LOG_2 = 1/LOG_2; static int TWO_TO_THE_14 = 16384; // (int) Math.pow(2, 14); public static double midiNumberToHz(int m) { return Math.pow(2, (m - 69) / 12.0) * 440.0; } public static double hzToMidiNumber(double hz) { return Math.log(hz/440) * INV_LOG_2 * 12 + 69; } public static double centsAbove(double f2, double f1) { return 1200 * Math.log(f2/f1) * INV_LOG_2; } public static int centsToTicks(double c) { return (int)((c * TWO_TO_THE_14 / 100.0) + 0.5); } public void setNoteFrequency(int note_index, double freq) { int ind = (int)hzToMidiNumber(freq); double base = midiNumberToHz(ind); double cents = centsAbove(freq, base); while(cents < 0) { ind cents += 100; } int ticks = centsToTicks(cents); if (ticks == TWO_TO_THE_14) { ticks = 0; ind++; } bases[note_index] = ind; detunes[note_index] = ticks; } public abstract void popup(Synth synth); public abstract String getMenuName(); }
package org.jnosql.artemis.column.query; import org.jnosql.artemis.Converters; import org.jnosql.artemis.DynamicQueryException; import org.jnosql.artemis.column.util.ConverterUtil; import org.jnosql.artemis.reflection.ClassRepresentation; import org.jnosql.artemis.reflection.FieldRepresentation; import org.jnosql.query.Params; import java.lang.reflect.Method; import java.util.List; import java.util.Optional; class ParamsBinder { private final ClassRepresentation representation; private final Converters converters; ParamsBinder(ClassRepresentation representation, Converters converters) { this.representation = representation; this.converters = converters; } public void bind(Params params, Object[] args, Method method) { List<String> names = params.getNames(); if (names.size() > args.length) { throw new DynamicQueryException("The number of parameters in a query is bigger than the number of " + "parameters in the method: " + method); } for (int index = 0; index < names.size(); index++) { String name = names.get(index); String fieldName = name.substring(0, name.lastIndexOf("_")); Optional<FieldRepresentation> field = this.representation.getFields().stream() .filter(f -> f.getName().equals(fieldName)).findFirst(); Object value; if (field.isPresent()) { value = ConverterUtil.getValue(args[index], converters, field.get()); } else { value = args[index]; } params.bind(name, value); } } }
package me.capit.Townshend.aegis; import java.io.File; import java.util.ArrayList; import me.capit.Townshend.Messager; import me.capit.Townshend.TownshendPlugin; import me.capit.Townshend.aegis.Aegis.AegisCreationException; import me.capit.Townshend.group.Group; import org.bukkit.block.Block; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.SignChangeEvent; public class AegisHandler implements Listener { TownshendPlugin plugin; public AegisHandler(TownshendPlugin p){ plugin=p; } @EventHandler(priority=EventPriority.LOW) public void onBlockBreak(BlockBreakEvent e){ ArrayList<Aegis> protections = new ArrayList<Aegis>(); for (Aegis a : TownshendPlugin.aegises){ if (a.locationProtectedByAeigs(e.getBlock().getLocation()) && TownshendPlugin.getGroupByName(a.getGroup())!=null && !TownshendPlugin.getGroupByName(a.getGroup()).isMember(e.getPlayer().getUniqueId())){ protections.add(a); } } if (protections.size()>=1){ Aegis lowest = null; for (Aegis a : protections){ if (lowest==null || (lowest.getHP()>a.getHP() && a.getHP()>0)) lowest=a; } if (lowest!=null && lowest.damage()) e.setCancelled(true); } if (!e.isCancelled()){ Block b = e.getBlock(); Aegis aegis = null; for (Aegis a : TownshendPlugin.aegises){ if (a.blockPartOfAegis(b)){aegis = a; break;} } if (aegis!=null){ TownshendPlugin.aegises.remove(aegis); File file = new File(plugin.getDataFolder().getPath()+File.separator+aegis.ID+".yml"); if (file.exists()) file.delete(); } } } @EventHandler public void onSignPlace(SignChangeEvent e){ String[] lines = e.getLines(); if (lines[0].equalsIgnoreCase("[AEGIS]")){ Group g = TownshendPlugin.getGroupByName(lines[1]); if (g!=null){ try { Aegis a = new Aegis(e.getBlock().getLocation(), g.name); TownshendPlugin.aegises.add(a); } catch (AegisCreationException ex){ Messager.sendError(e.getPlayer(), ex.getLocalizedMessage()); } } } } }
package io.flutter.perf; import com.intellij.openapi.editor.Document; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.impl.http.HttpVirtualFile; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.testFramework.LightVirtualFile; import com.intellij.xdebugger.XDebuggerUtil; import com.intellij.xdebugger.XSourcePosition; import com.jetbrains.lang.dart.psi.DartId; import com.jetbrains.lang.dart.psi.DartReferenceExpression; import io.flutter.inspector.InspectorService; public class DocumentFileLocationMapper implements FileLocationMapper { final Document document; private final PsiFile psiFile; private final VirtualFile virtualFile; private final XDebuggerUtil debuggerUtil; public DocumentFileLocationMapper(String path, Project project) { this(lookupDocument(path), project); } public static Document lookupDocument(String path) { final String fileName = InspectorService.fromSourceLocationUri(path); final VirtualFile virtualFile = LocalFileSystem.getInstance().findFileByPath(fileName); if (virtualFile != null && virtualFile.exists() && !(virtualFile instanceof LightVirtualFile) && !(virtualFile instanceof HttpVirtualFile)) { return FileDocumentManager.getInstance().getDocument(virtualFile); } return null; } DocumentFileLocationMapper(Document document, Project project) { this.document = document; if (document != null) { psiFile = PsiDocumentManager.getInstance(project).getPsiFile(document); virtualFile = psiFile != null ? psiFile.getVirtualFile() : null; debuggerUtil = XDebuggerUtil.getInstance(); } else { psiFile = null; virtualFile = null; debuggerUtil = null; } } @Override public TextRange getIdentifierRange(int line, int column) { if (psiFile == null) { return null; } // Convert to zero based line and column indices. line = line - 1; column = column - 1; if (line >= document.getLineCount() || document.isLineModified(line)) { return null; } final XSourcePosition pos = debuggerUtil.createPosition(virtualFile, line, column); if (pos == null) { return null; } final int offset = pos.getOffset(); PsiElement element = psiFile.getOriginalFile().findElementAt(offset); if (element == null) { return null; } // Handle named constructors gracefully. // For example, for the constructor // Image.asset(...) we want to return "Image.asset" instead of "asset". if (element.getParent() instanceof DartId) { element = element.getParent(); } while (element.getParent() instanceof DartReferenceExpression) { element = element.getParent(); } return element.getTextRange(); } @Override public String getText(TextRange textRange) { return document.getText(textRange); } }
package org.xins.common.io; import java.io.File; import org.xins.common.Log; import org.xins.common.MandatoryArgumentChecker; import org.xins.common.Utils; /** * File watcher thread. This thread checks if a file or a set of files * changed and if it has, it notifies the listener. * The check is performed every <em>n</em> seconds, where <em>n</em> can be configured. * * <p>Initially this thread will be a daemon thread. This can be changed by * calling {@link #setDaemon(boolean)}. * * @version $Revision$ $Date$ * @author <a href="mailto:ernst@ernstdehaan.com">Ernst de Haan</a> * * @since XINS 1.0.0 */ public final class FileWatcher extends Thread { /** * Fully-qualified name of this class. */ private static final String CLASSNAME = FileWatcher.class.getName(); /** * Instance counter. Used to generate a unique ID for each instance. */ private static int INSTANCE_COUNT; /** * Lock object for <code>INSTANCE_COUNT</code>. Never <code>null</code>. */ private static final Object INSTANCE_COUNT_LOCK = new Object(); /** * State in which this file watcher thread is not running. */ private static final int NOT_RUNNING = 1; /** * State in which this file watcher thread is currently running and has not * been told to stop. */ private static final int RUNNING = 2; /** * State in which this file watcher thread is currently running, but has * been told to stop. */ private static final int SHOULD_STOP = 3; /** * Unique instance identifier. */ private final int _instanceID; /** * The files to watch. Not <code>null</code>. */ private final File[] _files; /** * The string representation of the files to watch. Not <code>null</code>. */ private final String _filePaths; /** * Delay in seconds, at least 1. When the interval is uninitialized, the * value of this field is less than 1. */ private int _interval; /** * The listener. Not <code>null</code> */ private final Listener _listener; /** * Timestamp of the last modification of the file. The value * <code>-1L</code> indicates that the file could not be found the last * time this was checked. * * <p>Initially this field is <code>-1L</code>. */ private long _lastModified; /** * Current state. Never <code>null</code>. Value is one of the following * values: * * <ul> * <li>{@link #NOT_RUNNING} * <li>{@link #RUNNING} * <li>{@link #SHOULD_STOP} * </ul> * * Once the thread is stopped, the state will be changed to * {@link #NOT_RUNNING} again. */ private int _state; public FileWatcher(String file, Listener listener) throws IllegalArgumentException { this(file, 0, listener); } public FileWatcher(String file, int interval, Listener listener) throws IllegalArgumentException { this(new String[]{file}, interval, listener); } public FileWatcher(String[] files, int interval, Listener listener) throws IllegalArgumentException { // Check preconditions MandatoryArgumentChecker.check("files", files, "listener", listener); if (interval < 0) { throw new IllegalArgumentException("interval (" + interval + ") < 0"); } if (files.length < 1) { throw new IllegalArgumentException("At least one file should be specified."); } for (int i = 0; i < files.length; i++) { if (files[i] == null) { throw new IllegalArgumentException("The file specified at index " + i + " is null."); } } // Determine the unique instance ID int instanceID; synchronized (INSTANCE_COUNT_LOCK) { instanceID = INSTANCE_COUNT++; } // Initialize the fields _instanceID = instanceID; _files = new File[files.length]; String filePaths = ""; for (int i = 0; i < files.length; i++) { _files[i] = new File(files[i]); filePaths += ";" + _files[i].getPath(); } _filePaths = filePaths.substring(1); _interval = interval; _listener = listener; _state = NOT_RUNNING; // Configure thread as daemon setDaemon(true); // Set the name of this thread configureThreadName(); // Immediately check if the file can be read from firstCheck(); } /** * Configures the name of this thread. */ private synchronized void configureThreadName() { String name = CLASSNAME + " #" + _instanceID + " [files=\"" + _filePaths + "\"; interval=" + _interval + ']'; setName(name); } /** * Performs the first check on the file to determine the date the file was * last modified. This method is called from the constructors. If the file * cannot be accessed due to a {@link SecurityException}, then this * exception is logged and ignored. */ private void firstCheck() { for (int i = 0; i < _files.length; i++) { File file = _files[i]; try { if (file.canRead()) { _lastModified = Math.max(_lastModified, file.lastModified()); } // Ignore a SecurityException } catch (SecurityException exception) { Utils.logIgnoredException(exception); } } } public void run() throws IllegalStateException { int interval; int state; synchronized (this) { interval = _interval; state = _state; } // Check preconditions if (Thread.currentThread() != this) { throw new IllegalStateException("Thread.currentThread() != this"); } else if (state == RUNNING) { throw new IllegalStateException("Thread already running."); } else if (state == SHOULD_STOP) { throw new IllegalStateException("Thread should stop running."); } else if (interval < 1) { throw new IllegalStateException("Interval has not been set yet."); } Log.log_1200(_instanceID, _filePaths, interval); // Move to the RUNNING state synchronized (this) { _state = RUNNING; } // Loop while we should keep running boolean shouldStop = false; while (! shouldStop) { synchronized (this) { try { // Wait for the designated amount of time wait(((long) interval) * 1000L); } catch (InterruptedException exception) { // The thread has been notified } // Should we stop? shouldStop = (_state != RUNNING); } // If we do not have to stop yet, check if the file changed if (! shouldStop) { check(); } } // Thread stopped Log.log_1203(_instanceID, _filePaths); } /** * Returns the current interval. * * @return interval * the current interval in seconds, always greater than or equal to 1, * except if the interval is not initialized yet, in which case 0 is * returned. */ public synchronized int getInterval() { return _interval; } public synchronized void setInterval(int newInterval) throws IllegalArgumentException { // Check preconditions if (newInterval < 1) { throw new IllegalArgumentException( "newInterval (" + newInterval + ") < 1"); } // Change the interval if (newInterval != _interval) { Log.log_1201(_instanceID, _filePaths, _interval, newInterval); _interval = newInterval; } // Update the thread name configureThreadName(); // TODO: Interrupt the thread (see #HERE#) } public synchronized void end() throws IllegalStateException { // Check state if (_state == NOT_RUNNING) { throw new IllegalStateException("Thread currently not running."); } else if (_state == SHOULD_STOP) { throw new IllegalStateException("Thread already stopping."); } Log.log_1202(_instanceID, _filePaths); // Change the state and interrupt the thread _state = SHOULD_STOP; this.interrupt(); } /** * Checks if the file changed. The following algorithm is used: * * <ul> * <li>check if the file is readable; * <li>if so, then determine when the file was last modified; * <li>if either the file existence check or the file modification check * causes a {@link SecurityException} to be thrown, then * {@link Listener#securityException(SecurityException)} is called * and the method returns; * <li>otherwise if the file is not readable (it may not exist), then * {@link Listener#fileNotFound()} is called and the method returns; * <li>otherwise if the file is readable, but previously was not, * then {@link Listener#fileFound()} is called and the method * returns; * <li>otherwise if the file was modified, then * {@link Listener#fileModified()} is called and the method returns; * <li>otherwise the file was not modified, then * {@link Listener#fileNotModified()} is called and the method * returns. * </ul> * * @since XINS 1.2.0 */ public synchronized void check() { // Variable to store the file modification timestamp in. The value -1 // indicates the file does not exist. long lastModified = 0L; // Check if the file can be read from and if so, when it was last // modified try { for (int i = 0; i < _files.length; i++) { File file = _files[i]; if (file.canRead() && lastModified != -1L) { lastModified = Math.max(lastModified, file.lastModified()); } else { lastModified = -1L; } } // Authorisation problem; our code is not allowed to call canRead() // and/or lastModified() on the File object } catch (SecurityException securityException) { // Notify the listener try { _listener.securityException(securityException); // Ignore any exceptions thrown by the listener callback method } catch (Throwable exception) { Utils.logIgnoredException(exception); } // Short-circuit return; } // A least one file can not be found if (lastModified == -1L) { // Set _lastModified to -1, which indicates the file did not exist // last time it was checked. _lastModified = -1L; // Notify the listener try { _listener.fileNotFound(); // Ignore any exceptions thrown by the listener callback method } catch (Throwable exception) { Utils.logIgnoredException(exception); } // Previously a file could not be found, but now it can } else if (_lastModified == -1L) { // Update the field that stores the last known modification date _lastModified = lastModified; // Notify the listener try { _listener.fileFound(); // Ignore any exceptions thrown by the listener callback method } catch (Throwable exception) { Utils.logIgnoredException(exception); } // At least one file has been modified } else if (lastModified != _lastModified) { // Update the field that stores the last known modification date _lastModified = lastModified; // Notify listener try { _listener.fileModified(); // Ignore any exceptions thrown by the listener callback method } catch (Throwable exception) { Utils.logIgnoredException(exception); } // None of the files has not been modified } else { // Notify listener try { _listener.fileNotModified(); // Ignore any exceptions thrown by the listener callback method } catch (Throwable exception) { Utils.logIgnoredException(exception); } } } /** * Interface for file watcher listeners. * * <p>Note that exceptions thrown by these callback methods will be ignored * by the <code>FileWatcher</code>. * * @version $Revision$ $Date$ * @author <a href="mailto:ernst@ernstdehaan.com">Ernst de Haan</a> * * @since XINS 1.0.0 */ public interface Listener { /** * Callback method, called if the file is checked but cannot be found. * This method is called the first time the file is determined not to * exist, but also each consecutive time the file is still determined * not to be found. */ void fileNotFound(); /** * Callback method, called if the file is found for the first time since * the <code>FileWatcher</code> was started. Each consecutive time the * file still exists (and is readable), either * {@link #fileModified()} or {@link #fileNotModified()} is called. */ void fileFound(); /** * Callback method, called if an authorisation error prevents that the * file is checked for existence and last modification date. * * @param exception * the caught exception, not <code>null</code>. */ void securityException(SecurityException exception); /** * Callback method, called if the file was checked and found to be * modified. */ void fileModified(); /** * Callback method, called if the file was checked but found not to be * modified. */ void fileNotModified(); } }
package org.apache.solr.perf; import javax.management.*; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; import java.io.IOException; import java.lang.management.*; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Set; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; public class StatisticsHelper implements Runnable { protected final MBeanServerConnection connection; protected final OperatingSystemMXBean operatingSystem; protected final CompilationMXBean jitCompiler; protected final MemoryMXBean heapMemory; protected final AtomicInteger starts = new AtomicInteger(); protected volatile MemoryPoolMXBean youngMemoryPool; protected volatile MemoryPoolMXBean survivorMemoryPool; protected volatile MemoryPoolMXBean oldMemoryPool; protected volatile boolean hasMemoryPools; protected volatile ScheduledFuture< ? > memoryPoller; protected volatile GarbageCollectorMXBean youngCollector; protected volatile GarbageCollectorMXBean oldCollector; protected volatile boolean hasCollectors; protected volatile ScheduledExecutorService scheduler; protected volatile boolean polling; protected volatile long lastYoungUsed; protected volatile long startYoungCollections; protected volatile long startYoungCollectionsTime; protected volatile long totalYoungUsed; protected volatile long lastSurvivorUsed; protected volatile long totalSurvivorUsed; protected volatile long lastOldUsed; protected volatile long startOldCollections; protected volatile long startOldCollectionsTime; protected volatile long totalOldUsed; protected volatile long startTime; protected volatile long startProcessCPUTime; protected volatile long startJITCTime; public static StatisticsHelper createLocalStats() throws IOException, MalformedObjectNameException { MBeanServerConnection connection = ManagementFactory.getPlatformMBeanServer(); return createStats(connection); // OperatingSystemMXBean operatingSystem = ManagementFactory.getOperatingSystemMXBean(); // CompilationMXBean jitCompiler = ManagementFactory.getCompilationMXBean(); // MemoryMXBean heapMemory = ManagementFactory.getMemoryMXBean(); // MemoryPoolMXBean youngMemoryPool = null, survivorMemoryPool = null, oldMemoryPool = null; // List<MemoryPoolMXBean> memoryPools = ManagementFactory.getMemoryPoolMXBeans(); // for (MemoryPoolMXBean memoryPool : memoryPools) { // if ("PS Eden Space".equals(memoryPool.getName()) || "Par Eden Space".equals(memoryPool.getName()) // || "G1 Eden".equals(memoryPool.getName())) { // youngMemoryPool = memoryPool; // } else if ("PS Survivor Space".equals(memoryPool.getName()) || "Par Survivor Space".equals(memoryPool.getName()) // || "G1 Survivor".equals(memoryPool.getName())) { // survivorMemoryPool = memoryPool; // } else if ("PS Old Gen".equals(memoryPool.getName()) || "CMS Old Gen".equals(memoryPool.getName()) // || "G1 Old Gen".equals(memoryPool.getName())) { // oldMemoryPool = memoryPool; // GarbageCollectorMXBean youngCollector = null, oldCollector = null; // List<GarbageCollectorMXBean> garbageCollectors = ManagementFactory.getGarbageCollectorMXBeans(); // for (GarbageCollectorMXBean garbageCollector : garbageCollectors) { // if ("PS Scavenge".equals(garbageCollector.getName()) || "ParNew".equals(garbageCollector.getName()) // || "G1 Young Generation".equals(garbageCollector.getName())) { // youngCollector = garbageCollector; // } else if ("PS MarkSweep".equals(garbageCollector.getName()) // || "ConcurrentMarkSweep".equals(garbageCollector.getName()) // || "G1 Old Generation".equals(garbageCollector.getName())) { // oldCollector = garbageCollector; // return new StatisticsHelper(operatingSystem, jitCompiler, heapMemory, youngMemoryPool, survivorMemoryPool, oldMemoryPool, youngCollector, oldCollector); } public static StatisticsHelper createRemoteStats() throws IOException, MalformedObjectNameException { String url = "service:jmx:rmi:///jndi/rmi://localhost:9999/jmxrmi"; JMXServiceURL serviceURL = new JMXServiceURL(url); JMXConnector jmxConnector = JMXConnectorFactory.connect(serviceURL); MBeanServerConnection connection = jmxConnector.getMBeanServerConnection(); return createStats(connection); } private static StatisticsHelper createStats(MBeanServerConnection connection) throws IOException, MalformedObjectNameException { OperatingSystemMXBean operatingSystem = ManagementFactory.newPlatformMXBeanProxy(connection, ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME, OperatingSystemMXBean.class); CompilationMXBean jitCompiler = ManagementFactory.newPlatformMXBeanProxy(connection, ManagementFactory.COMPILATION_MXBEAN_NAME, CompilationMXBean.class); MemoryMXBean heapMemory = ManagementFactory.newPlatformMXBeanProxy(connection, ManagementFactory.MEMORY_MXBEAN_NAME, MemoryMXBean.class); Set<ObjectName> memoryPoolNames = connection.queryNames(new ObjectName(ManagementFactory.MEMORY_POOL_MXBEAN_DOMAIN_TYPE + ",*"), null); List<MemoryPoolMXBean> memoryPools = new ArrayList<MemoryPoolMXBean>(memoryPoolNames.size()); for (ObjectName memoryPoolName : memoryPoolNames) { MemoryPoolMXBean proxy = ManagementFactory.newPlatformMXBeanProxy(connection, memoryPoolName.toString(), MemoryPoolMXBean.class); memoryPools.add(proxy); } MemoryPoolMXBean youngMemoryPool = null, survivorMemoryPool = null, oldMemoryPool = null; for (MemoryPoolMXBean memoryPool : memoryPools) { if ("PS Eden Space".equals(memoryPool.getName()) || "Par Eden Space".equals(memoryPool.getName()) || "G1 Eden".equals(memoryPool.getName())) { youngMemoryPool = memoryPool; } else if ("PS Survivor Space".equals(memoryPool.getName()) || "Par Survivor Space".equals(memoryPool.getName()) || "G1 Survivor".equals(memoryPool.getName())) { survivorMemoryPool = memoryPool; } else if ("PS Old Gen".equals(memoryPool.getName()) || "CMS Old Gen".equals(memoryPool.getName()) || "G1 Old Gen".equals(memoryPool.getName())) { oldMemoryPool = memoryPool; } } Set<ObjectName> garbageCollectorNames = connection.queryNames(new ObjectName(ManagementFactory.GARBAGE_COLLECTOR_MXBEAN_DOMAIN_TYPE + ",*"), null); List<GarbageCollectorMXBean> garbageCollectors = new ArrayList<GarbageCollectorMXBean>(garbageCollectorNames.size()); for (ObjectName garbageCollectorName : garbageCollectorNames) { GarbageCollectorMXBean proxy = ManagementFactory.newPlatformMXBeanProxy(connection, garbageCollectorName.toString(), GarbageCollectorMXBean.class); garbageCollectors.add(proxy); } GarbageCollectorMXBean youngCollector = null, oldCollector = null; for (GarbageCollectorMXBean garbageCollector : garbageCollectors) { if ("PS Scavenge".equals(garbageCollector.getName()) || "ParNew".equals(garbageCollector.getName()) || "G1 Young Generation".equals(garbageCollector.getName())) { youngCollector = garbageCollector; } else if ("PS MarkSweep".equals(garbageCollector.getName()) || "ConcurrentMarkSweep".equals(garbageCollector.getName()) || "G1 Old Generation".equals(garbageCollector.getName())) { oldCollector = garbageCollector; } } return new StatisticsHelper(connection, operatingSystem, jitCompiler, heapMemory, youngMemoryPool, survivorMemoryPool, oldMemoryPool, youngCollector, oldCollector); } protected StatisticsHelper(MBeanServerConnection connection, OperatingSystemMXBean operatingSystem, CompilationMXBean jitCompiler, MemoryMXBean heapMemory, MemoryPoolMXBean youngMemoryPool, MemoryPoolMXBean survivorMemoryPool, MemoryPoolMXBean oldMemoryPool, GarbageCollectorMXBean youngCollector, GarbageCollectorMXBean oldCollector) { this.connection = connection; this.operatingSystem = operatingSystem; this.jitCompiler = jitCompiler; this.heapMemory = heapMemory; this.youngMemoryPool = youngMemoryPool; this.survivorMemoryPool = survivorMemoryPool; this.oldMemoryPool = oldMemoryPool; this.youngCollector = youngCollector; this.oldCollector = oldCollector; this.hasMemoryPools = youngMemoryPool != null && survivorMemoryPool != null && oldMemoryPool != null; this.hasCollectors = youngCollector != null && oldCollector != null; } public void run() { if (!hasMemoryPools) return; long young = youngMemoryPool.getUsage().getUsed(); long survivor = survivorMemoryPool.getUsage().getUsed(); long old = oldMemoryPool.getUsage().getUsed(); if (!polling) { polling = true; } else { if (lastYoungUsed <= young) { totalYoungUsed += young - lastYoungUsed; } if (lastSurvivorUsed <= survivor) { totalSurvivorUsed += survivor - lastSurvivorUsed; } if (lastOldUsed <= old) { totalOldUsed += old - lastOldUsed; } else { // May need something more here, like "how much was collected" } } lastYoungUsed = young; lastSurvivorUsed = survivor; lastOldUsed = old; } public boolean startStatistics() { // Support for multiple nodes requires to ignore start requests after the // first // but also requires that requests after the first wait until the // initialization // is completed (otherwise node #2 may start the run while the server is // GC'ing) synchronized (this) { if (starts.incrementAndGet() > 1) return false; heapMemory.gc(); System.err.println("\n========================================"); System.err.println("Statistics Started at " + new Date()); System.err.println("Operative System: " + operatingSystem.getName() + " " + operatingSystem.getVersion() + " " + operatingSystem.getArch()); System.err.println("JVM : " + System.getProperty("java.vm.vendor") + " " + System.getProperty("java.vm.name") + " runtime " + System.getProperty("java.vm.version") + " " + System.getProperty("java.runtime.version")); System.err.println("Processors: " + operatingSystem.getAvailableProcessors()); if (operatingSystem instanceof com.sun.management.OperatingSystemMXBean) { com.sun.management.OperatingSystemMXBean os = (com.sun.management.OperatingSystemMXBean) operatingSystem; long totalMemory = os.getTotalPhysicalMemorySize(); long freeMemory = os.getFreePhysicalMemorySize(); System.err.println("System Memory: " + percent(totalMemory - freeMemory, totalMemory) + "% used of " + gibiBytes(totalMemory) + " GiB"); } else { System.err.println("System Memory: N/A"); } MemoryUsage heapMemoryUsage = heapMemory.getHeapMemoryUsage(); System.err.println("Used Heap Size: " + mebiBytes(heapMemoryUsage.getUsed()) + " MiB"); System.err.println("Max Heap Size: " + mebiBytes(heapMemoryUsage.getMax()) + " MiB"); if (hasMemoryPools) { long youngGenerationHeap = heapMemoryUsage.getMax() - oldMemoryPool.getUsage().getMax(); System.err.println("Young Generation Heap Size: " + mebiBytes(youngGenerationHeap) + " MiB"); } else { System.err.println("Young Generation Heap Size: N/A"); } System.err.println("- - - - - - - - - - - - - - - - - - - - "); scheduler = Executors.newSingleThreadScheduledExecutor(); polling = false; memoryPoller = scheduler.scheduleWithFixedDelay(this, 0, 250, TimeUnit.MILLISECONDS); lastYoungUsed = 0; if (hasCollectors) { startYoungCollections = youngCollector.getCollectionCount(); startYoungCollectionsTime = youngCollector.getCollectionTime(); } totalYoungUsed = 0; lastSurvivorUsed = 0; totalSurvivorUsed = 0; lastOldUsed = 0; if (hasCollectors) { startOldCollections = oldCollector.getCollectionCount(); startOldCollectionsTime = oldCollector.getCollectionTime(); } totalOldUsed = 0; startTime = System.nanoTime(); if (operatingSystem instanceof com.sun.management.OperatingSystemMXBean) { com.sun.management.OperatingSystemMXBean os = (com.sun.management.OperatingSystemMXBean) operatingSystem; startProcessCPUTime = os.getProcessCpuTime(); } startJITCTime = jitCompiler.getTotalCompilationTime(); return true; } } public boolean stopStatistics() { synchronized (this) { if (starts.decrementAndGet() > 0) return false; memoryPoller.cancel(false); scheduler.shutdown(); System.err.println("- - - - - - - - - - - - - - - - - - - - "); System.err.println("Statistics Ended at " + new Date()); long elapsedTime = System.nanoTime() - startTime; System.err.println("Elapsed time: " + TimeUnit.NANOSECONDS.toMillis(elapsedTime) + " ms"); long elapsedJITCTime = jitCompiler.getTotalCompilationTime() - startJITCTime; System.err.println("\tTime in JIT compilation: " + elapsedJITCTime + " ms"); if (hasCollectors) { long elapsedYoungCollectionsTime = youngCollector.getCollectionTime() - startYoungCollectionsTime; long youngCollections = youngCollector.getCollectionCount() - startYoungCollections; System.err.println("\tTime in Young Generation GC: " + elapsedYoungCollectionsTime + " ms (" + youngCollections + " collections)"); long elapsedOldCollectionsTime = oldCollector.getCollectionTime() - startOldCollectionsTime; long oldCollections = oldCollector.getCollectionCount() - startOldCollections; System.err.println("\tTime in Old Generation GC: " + elapsedOldCollectionsTime + " ms (" + oldCollections + " collections)"); } else { System.err.println("\tTime in GC: N/A"); } if (hasMemoryPools) { System.err.println("Garbage Generated in Young Generation: " + mebiBytes(totalYoungUsed) + " MiB"); System.err.println("Garbage Generated in Survivor Generation: " + mebiBytes(totalSurvivorUsed) + " MiB"); System.err.println("Garbage Generated in Old Generation: " + mebiBytes(totalOldUsed) + " MiB"); System.err.println("Peak usage in Young Generation: " + mebiBytes(youngMemoryPool.getPeakUsage().getUsed()) + " MiB"); System.err.println("Peak usage in Survivor Generation: " + mebiBytes(survivorMemoryPool.getPeakUsage().getUsed()) + " MiB"); System.err.println("Peak usage in Old Generation: " + mebiBytes(oldMemoryPool.getPeakUsage().getUsed()) + " MiB"); } else { System.err.println("Garbage Generated: N/A"); } double systemLoadAverage = operatingSystem.getSystemLoadAverage(); System.err.println("Average System Load: " + systemLoadAverage); // todo fix this // System.err.println("Process CPU Load: " + getProcessCpuLoad(connection)); if (operatingSystem instanceof com.sun.management.OperatingSystemMXBean) { com.sun.management.OperatingSystemMXBean os = (com.sun.management.OperatingSystemMXBean) operatingSystem; long elapsedProcessCPUTime = os.getProcessCpuTime() - startProcessCPUTime; System.err.println("Average CPU Load: " + ((float) elapsedProcessCPUTime * 100 / elapsedTime) + "/" + (100 * operatingSystem.getAvailableProcessors())); } else { System.err.println("Average CPU Load: N/A"); } System.err.println(" return true; } } public static double getProcessCpuLoad(MBeanServerConnection mbs) { try { ObjectName name = ObjectName.getInstance("java.lang:type=OperatingSystem"); AttributeList list = mbs.getAttributes(name, new String[]{"ProcessCpuLoad"}); if (list.isEmpty()) return Double.NaN; Attribute att = (Attribute) list.get(0); Double value = (Double) att.getValue(); // usually takes a couple of seconds before we get real values if (value == -1.0) return Double.NaN; // returns a percentage value with 1 decimal point precision return ((int) (value * 1000) / 10.0); } catch (Exception e) { e.printStackTrace(); return Double.NaN; } } public float percent(long dividend, long divisor) { return (float) dividend * 100 / divisor; } public float mebiBytes(long bytes) { return (float) bytes / 1024 / 1024; } public float gibiBytes(long bytes) { return (float) bytes / 1024 / 1024 / 1024; } }
package org.jivesoftware.wildfire.group; import org.jivesoftware.database.DbConnectionManager; import org.jivesoftware.util.CacheSizes; import org.jivesoftware.util.Cacheable; import org.jivesoftware.util.Log; import org.jivesoftware.wildfire.XMPPServer; import org.jivesoftware.wildfire.event.GroupEventDispatcher; import org.xmpp.packet.JID; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.*; import java.util.concurrent.ConcurrentHashMap; /** * Groups organize users into a single entity for easier management.<p> * * The actual group implementation is controlled by the {@link GroupProvider}, which * includes things like the group name, the members, and adminstrators. Each group * also has properties, which are always stored in the Wildfire database. * * @see GroupManager#createGroup(String) * * @author Matt Tucker */ public class Group implements Cacheable { private static final String LOAD_PROPERTIES = "SELECT name, propValue FROM jiveGroupProp WHERE groupName=?"; private static final String DELETE_PROPERTY = "DELETE FROM jiveGroupProp WHERE groupName=? AND name=?"; private static final String UPDATE_PROPERTY = "UPDATE jiveGroupProp SET propValue=? WHERE name=? AND groupName=?"; private static final String INSERT_PROPERTY = "INSERT INTO jiveGroupProp (groupName, name, propValue) VALUES (?, ?, ?)"; private static final String LOAD_SHARED_GROUPS = "SELECT groupName FROM jiveGroupProp WHERE name='sharedRoster.showInRoster' " + "AND propValue IS NOT NULL AND propValue <> 'nobody'"; private transient GroupProvider provider; private transient GroupManager groupManager; private String name; private String description; private Map<String, String> properties; private Set<JID> members; private Set<JID> administrators; /** * Returns the name of the groups that are shared groups. * * @return the name of the groups that are shared groups. */ static Set<String> getSharedGroupsNames() { Set<String> groupNames = new HashSet<String>(); Connection con = null; PreparedStatement pstmt = null; try { con = DbConnectionManager.getConnection(); pstmt = con.prepareStatement(LOAD_SHARED_GROUPS); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { groupNames.add(rs.getString(1)); } rs.close(); } catch (SQLException sqle) { Log.error(sqle); } finally { try { if (pstmt != null) pstmt.close(); } catch (Exception e) { Log.error(e); } try { if (con != null) con.close(); } catch (Exception e) { Log.error(e); } } return groupNames; } /** * Constructs a new group. Note: this constructor is intended for implementors of the * {@link GroupProvider} interface. To create a new group, use the * {@link GroupManager#createGroup(String)} method. * * @param name the name. * @param description the description. * @param members a Collection of the group members. * @param administrators a Collection of the group administrators. */ public Group(String name, String description, Collection<JID> members, Collection<JID> administrators) { this.groupManager = GroupManager.getInstance(); this.provider = groupManager.getProvider(); this.name = name; this.description = description; this.members = new HashSet<JID>(members); this.administrators = new HashSet<JID>(administrators); } /** * Returns the name of the group. For example, 'XYZ Admins'. * * @return the name of the group. */ public String getName() { return name; } public void setName(String name) { if (name == this.name || (name != null && name.equals(this.name)) || provider.isReadOnly()) { // Do nothing return; } try { String originalName = this.name; provider.setName(this.name, name); groupManager.groupCache.remove(this.name); this.name = name; groupManager.groupCache.put(name, this); // Fire event. Map<String, Object> params = new HashMap<String, Object>(); params.put("type", "nameModified"); params.put("originalValue", originalName); GroupEventDispatcher.dispatchEvent(this, GroupEventDispatcher.EventType.group_modified, params); } catch (Exception e) { Log.error(e); } } /** * Returns the description of the group. The description often * summarizes a group's function, such as 'Administrators of the XYZ forum'. * * @return the description of the group. */ public String getDescription() { return description; } public void setDescription(String description) { if (description == this.description || (description != null && description.equals(this.description)) || provider.isReadOnly()) { // Do nothing return; } try { String originalDescription = this.description; provider.setDescription(name, description); this.description = description; // Fire event. Map<String, Object> params = new HashMap<String, Object>(); params.put("type", "descriptionModified"); params.put("originalValue", originalDescription); GroupEventDispatcher.dispatchEvent(this, GroupEventDispatcher.EventType.group_modified, params); } catch (Exception e) { Log.error(e); } } public String toString() { return name; } /** * Returns all extended properties of the group. Groups * have an arbitrary number of extended properties. * * @return the extended properties. */ public Map<String,String> getProperties() { synchronized (this) { if (properties == null) { properties = new ConcurrentHashMap<String, String>(); loadProperties(); } } // Return a wrapper that will intercept add and remove commands. return new PropertiesMap(); } /** * Returns a Collection of the group administrators. * * @return a Collection of the group administrators. */ public Collection<JID> getAdmins() { // Return a wrapper that will intercept add and remove commands. return new MemberCollection(administrators, true); } /** * Returns a Collection of the group members. * * @return a Collection of the group members. */ public Collection<JID> getMembers() { // Return a wrapper that will intercept add and remove commands. return new MemberCollection(members, false); } /** * Returns true if the provided username belongs to a user that is part of the group. * * @param user the JID address of the user to check. * @return true if the specified user is a group user. */ public boolean isUser(JID user) { return user != null && (members.contains(user) || administrators.contains(user)); } /** * Returns true if the provided username belongs to a user of the group. * * @param username the username to check. * @return true if the provided username belongs to a user of the group. */ public boolean isUser(String username) { if (username != null) { return isUser(XMPPServer.getInstance().createJID(username, null)); } else { return false; } } private void writeObject(java.io.ObjectOutputStream out) throws IOException { out.defaultWriteObject(); } private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); groupManager = GroupManager.getInstance(); provider = groupManager.getProvider(); } public int getCachedSize() { // Approximate the size of the object in bytes by calculating the size // of each field. int size = 0; size += CacheSizes.sizeOfObject(); // overhead of object size += CacheSizes.sizeOfString(name); size += CacheSizes.sizeOfString(description); size += CacheSizes.sizeOfMap(properties); for (JID member: members) { size += CacheSizes.sizeOfString(member.toString()); } for (JID admin: administrators) { size += CacheSizes.sizeOfString(admin.toString()); } return size; } public int hashCode() { return name.hashCode(); } public boolean equals(Object object) { if (this == object) { return true; } if (object != null && object instanceof Group) { return name.equals(((Group)object).getName()); } else { return false; } } /** * Collection implementation that notifies the GroupProvider of any * changes to the collection. */ private class MemberCollection extends AbstractCollection { private Collection<JID> users; private boolean adminCollection; public MemberCollection(Collection<JID> users, boolean adminCollection) { this.users = users; this.adminCollection = adminCollection; } public Iterator<JID> iterator() { return new Iterator() { Iterator<JID> iter = users.iterator(); Object current = null; public boolean hasNext() { return iter.hasNext(); } public Object next() { current = iter.next(); return current; } public void remove() { if (current == null) { throw new IllegalStateException(); } // Do nothing if the provider is read-only. if (provider.isReadOnly()) { return; } JID user = (JID)current; // Remove the user from the collection in memory. iter.remove(); // Remove the group user from the backend store. provider.deleteMember(name, user); // Fire event. if (adminCollection) { Map<String, String> params = new HashMap<String, String>(); params.put("admin", user.toString()); GroupEventDispatcher.dispatchEvent(Group.this, GroupEventDispatcher.EventType.admin_removed, params); } else { Map<String, String> params = new HashMap<String, String>(); params.put("member", user.toString()); GroupEventDispatcher.dispatchEvent(Group.this, GroupEventDispatcher.EventType.member_removed, params); } } }; } public int size() { return users.size(); } public boolean add(Object member) { // Do nothing if the provider is read-only. if (provider.isReadOnly()) { return false; } JID user = (JID) member; // Find out if the user was already a group user. boolean alreadyGroupUser; if (adminCollection) { alreadyGroupUser = members.contains(user); } else { alreadyGroupUser = administrators.contains(user); } if (users.add(user)) { if (alreadyGroupUser) { // Update the group user privileges in the backend store. provider.updateMember(name, user, adminCollection); } else { // Add the group user to the backend store. provider.addMember(name, user, adminCollection); } // Fire event. if (adminCollection) { Map<String, String> params = new HashMap<String, String>(); params.put("admin", user.toString()); if (alreadyGroupUser) { GroupEventDispatcher.dispatchEvent(Group.this, GroupEventDispatcher.EventType.member_removed, params); } GroupEventDispatcher.dispatchEvent(Group.this, GroupEventDispatcher.EventType.admin_added, params); } else { Map<String, String> params = new HashMap<String, String>(); params.put("member", user.toString()); if (alreadyGroupUser) { GroupEventDispatcher.dispatchEvent(Group.this, GroupEventDispatcher.EventType.admin_removed, params); } GroupEventDispatcher.dispatchEvent(Group.this, GroupEventDispatcher.EventType.member_added, params); } // If the user was a member that became an admin or vice versa then remove the // user from the other collection if (alreadyGroupUser) { if (adminCollection) { if (members.contains(user)) { members.remove(user); } } else { if (administrators.contains(user)) { administrators.remove(user); } } } return true; } return false; } } /** * Map implementation that updates the database when properties are modified. */ private class PropertiesMap extends AbstractMap { public Object put(Object key, Object value) { if (key == null || value == null) { throw new NullPointerException(); } Map<String, Object> eventParams = new HashMap<String, Object>(); Object answer; String keyString = (String) key; synchronized (keyString.intern()) { if (properties.containsKey(keyString)) { String originalValue = properties.get(keyString); answer = properties.put(keyString, (String)value); updateProperty(keyString, (String)value); // Configure event. eventParams.put("type", "propertyModified"); eventParams.put("propertyKey", key); eventParams.put("originalValue", originalValue); } else { answer = properties.put(keyString, (String)value); insertProperty(keyString, (String)value); // Configure event. eventParams.put("type", "propertyAdded"); eventParams.put("propertyKey", key); } } // Fire event. GroupEventDispatcher.dispatchEvent(Group.this, GroupEventDispatcher.EventType.group_modified, eventParams); return answer; } public Set<Entry> entrySet() { return new PropertiesEntrySet(); } } /** * Set implementation that updates the database when properties are deleted. */ private class PropertiesEntrySet extends AbstractSet { public int size() { return properties.entrySet().size(); } public Iterator iterator() { return new Iterator() { Iterator iter = properties.entrySet().iterator(); Map.Entry current = null; public boolean hasNext() { return iter.hasNext(); } public Object next() { current = (Map.Entry)iter.next(); return current; } public void remove() { if (current == null) { throw new IllegalStateException(); } String key = (String)current.getKey(); deleteProperty(key); iter.remove(); // Fire event. Map<String, Object> params = new HashMap<String, Object>(); params.put("type", "propertyDeleted"); params.put("propertyKey", key); GroupEventDispatcher.dispatchEvent(Group.this, GroupEventDispatcher.EventType.group_modified, params); } }; } } private void loadProperties() { Connection con = null; PreparedStatement pstmt = null; try { con = DbConnectionManager.getConnection(); pstmt = con.prepareStatement(LOAD_PROPERTIES); pstmt.setString(1, name); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { String key = rs.getString(1); String value = rs.getString(2); if (key != null) { if (value == null) { value = ""; Log.warn("There is a group property whose value is null of Group: " + name); } properties.put(key, value); } else { Log.warn("There is a group property whose key is null of Group: " + name); } } rs.close(); } catch (SQLException sqle) { Log.error(sqle); } finally { try { if (pstmt != null) pstmt.close(); } catch (Exception e) { Log.error(e); } try { if (con != null) con.close(); } catch (Exception e) { Log.error(e); } } } private void insertProperty(String propName, String propValue) { Connection con = null; PreparedStatement pstmt = null; try { con = DbConnectionManager.getConnection(); pstmt = con.prepareStatement(INSERT_PROPERTY); pstmt.setString(1, name); pstmt.setString(2, propName); pstmt.setString(3, propValue); pstmt.executeUpdate(); } catch (SQLException e) { Log.error(e); } finally { try { if (pstmt != null) pstmt.close(); } catch (Exception e) { Log.error(e); } try { if (con != null) con.close(); } catch (Exception e) { Log.error(e); } } } private void updateProperty(String propName, String propValue) { Connection con = null; PreparedStatement pstmt = null; try { con = DbConnectionManager.getConnection(); pstmt = con.prepareStatement(UPDATE_PROPERTY); pstmt.setString(1, propValue); pstmt.setString(2, propName); pstmt.setString(3, name); pstmt.executeUpdate(); } catch (SQLException e) { Log.error(e); } finally { try { if (pstmt != null) pstmt.close(); } catch (Exception e) { Log.error(e); } try { if (con != null) con.close(); } catch (Exception e) { Log.error(e); } } } private void deleteProperty(String propName) { Connection con = null; PreparedStatement pstmt = null; try { con = DbConnectionManager.getConnection(); pstmt = con.prepareStatement(DELETE_PROPERTY); pstmt.setString(1, name); pstmt.setString(2, propName); pstmt.executeUpdate(); } catch (SQLException e) { Log.error(e); } finally { try { if (pstmt != null) pstmt.close(); } catch (Exception e) { Log.error(e); } try { if (con != null) con.close(); } catch (Exception e) { Log.error(e); } } } }
import java.io.*; import java.util.*; public class Intcode { public static final String DELIMITER = ","; public static final String INITIALISED_MEMORY = "0"; public Intcode (Vector<String> values, String initialInput, boolean debug) { _debug = debug; _instructionPointer = 0; _output = new Vector<String>(); _memory = new Vector<String>(values); _input = new Vector<String>(); _input.add(initialInput); _status = Status.CREATED; _relativeBase = 0; } public final boolean hasHalted () { return (_status == Status.HALTED); } public final boolean hasPaused () { return (_status == Status.PAUSED); } public final boolean waitingForInput () { return (_status == Status.WAITING_FOR_INPUT); } public final int status () { return _status; } public final boolean hasOutput () { return (_output.size() > 0); } public final String getOutput () { return _output.remove(0); } public final void setInput (String input) { _input.add(input); } public final String getInput () { try { return _input.elementAt(0); } catch (Exception ex) { return null; } } public final String consumeInput () { try { return _input.remove(0); } catch (Exception ex) { return null; } } public final void changeInstruction (int entry, String value) { _memory.setElementAt(value, entry); } /** * Execute all the commands given, only returning when paused or halted. * * @return the current status. */ public int executeProgram () { while (!hasHalted()) { singleStepExecution(); // assume input only needed once! } return _status; } /** * Execute until input required. * * @return the current status. */ public int executeUntilInput () { do { singleStepExecution(); } while (!waitingForInput()); return _status; } /** * Execute one instruction at a time. If input is required and none is provided * then change status and pause anyway. * * @return the current status. */ public int singleStepExecution () { if (hasHalted()) { if (_debug) System.out.println("Intcode computer has halted!"); return _status; } if (_debug) System.out.println("Intcode input <"+getInput()+"> and instruction pointer: "+_instructionPointer); String str = getOpcode(_memory.elementAt(_instructionPointer)); int opcode = Integer.valueOf(str); int[] modes = ParameterMode.getModes(_memory.elementAt(_instructionPointer)); if (_debug) { System.out.println("\nWorking on element "+_instructionPointer+" which is command "+Instructions.commandToString(opcode)+ " with parameter modes ..."); ParameterMode.printModes(modes); } /* * Now factor in the parameter modes. */ switch (opcode) { case Instructions.ADD: { /* * Opcode 1 adds together numbers read from two positions * and stores the result in a third position. The three integers * immediately after the opcode tell you these three positions - the * first two indicate the positions from which you should read the * input values, and the third indicates the position at which * the output should be stored. */ long param1 = Long.valueOf(getValue(_instructionPointer+1, modes[0], false)); long param2 = Long.valueOf(getValue(_instructionPointer+2, modes[1], false)); int param3 = Integer.valueOf(getValue(_instructionPointer+3, modes[2], true)); if (_debug) System.out.println("Adding "+param1+" and "+param2); long sum = param1+param2; if (_debug) System.out.println("Storing "+sum+" at position "+param3); setValue(param3, String.valueOf(sum)); _instructionPointer += 4; // move the pointer on. } break; case Instructions.MULTIPLY: { /* * Opcode 2 works exactly like opcode 1, except it multiplies the * two inputs instead of adding them. Again, the three integers after * the opcode indicate where the inputs and outputs are, not their values. */ long param1 = Long.valueOf(getValue(_instructionPointer+1, modes[0], false)); long param2 = Long.valueOf(getValue(_instructionPointer+2, modes[1], false)); int param3 = Integer.valueOf(getValue(_instructionPointer+3, modes[2], true)); if (_debug) System.out.println("Multiplying "+param1+" and "+param2); long product = Long.valueOf(param1)*Long.valueOf(param2); if (_debug) System.out.println("Storing "+product+" at position "+param3); setValue(param3, String.valueOf(product)); _instructionPointer += 4; // move the pointer on. } break; case Instructions.INPUT_AND_STORE: { /* * Opcode 3 takes a single integer as input and saves it to * the position given by its only parameter. */ if (getInput() != null) { int param1 = Integer.valueOf(getValue(_instructionPointer+1, modes[0], true)); if (_debug) System.out.println("Storing "+getInput()+" at position "+param1); setValue(param1, consumeInput()); _instructionPointer += 2; // move the pointer on. } else { if (_debug) System.out.println("Waiting for input."); _status = Status.WAITING_FOR_INPUT; return _status; } } break; case Instructions.OUTPUT: { /* * Opcode 4 outputs the value of its only parameter. */ long param1 = Long.valueOf(getValue(_instructionPointer+1, modes[0], false)); if (_debug) System.out.println("Adding value "+param1+" to output state."); _output.add(Long.toString(param1)); _instructionPointer += 2; // move the pointer on. _status = Status.PAUSED; return _status; } case Instructions.JUMP_IF_TRUE: { /* * If the first parameter is non-zero, it sets the instruction pointer to * the value from the second parameter. Otherwise, it does nothing. */ long param1 = Long.valueOf(getValue(_instructionPointer+1, modes[0], false)); long param2 = Long.valueOf(getValue(_instructionPointer+2, modes[1], false)); if (_debug) System.out.println("Checking "+param1+" != 0 and might jump to "+param2); if (param1 != 0) { _instructionPointer = (int) param2; if (_debug) System.out.println("Will jump to "+param2); } else _instructionPointer += 3; } break; case Instructions.JUMP_IF_FALSE: { /* * If the first parameter is zero, it sets the instruction pointer to the value * from the second parameter. Otherwise, it does nothing. */ long param1 = Long.valueOf(getValue(_instructionPointer+1, modes[0], false)); long param2 = Long.valueOf(getValue(_instructionPointer+2, modes[1], false)); if (_debug) System.out.println("Checking "+param1+" == 0 and might jump to "+param2); if (param1 == 0) { _instructionPointer = (int) param2; if (_debug) System.out.println("Will jump to "+param2); } else _instructionPointer += 3; } break; case Instructions.LESS_THAN: { /* * If the first parameter is less than the second parameter, it stores 1 * in the position given by the third parameter. Otherwise, it stores 0. */ System.out.println("got "+getValue(_instructionPointer+1, modes[0], false)); long param1 = Long.valueOf(getValue(_instructionPointer+1, modes[0], false)); long param2 = Long.valueOf(getValue(_instructionPointer+2, modes[1], false)); int param3 = Integer.valueOf(getValue(_instructionPointer+3, modes[2], true)); if (_debug) { System.out.println("Checking whether "+param1+" < "+param2); System.out.print("Storing "); } if (param1 < param2) { if (_debug) System.out.print("1"); setValue(param3, "1"); } else { if (_debug) System.out.print("0"); setValue(param3, "0"); } if (_debug) System.out.println(" at location "+param3); _instructionPointer += 4; // move the pointer on. } break; case Instructions.EQUALS: { /* * If the first parameter is equal to the second parameter, it stores 1 * in the position given by the third parameter. Otherwise, it stores 0. */ long param1 = Long.valueOf(getValue(_instructionPointer+1, modes[0], false)); long param2 = Long.valueOf(getValue(_instructionPointer+2, modes[1], false)); int param3 = Integer.valueOf(getValue(_instructionPointer+3, modes[2], true)); if (_debug) { System.out.println("Checking whether "+param1+" is equal to "+param2); System.out.print("Storing "); } if (param1 == param2) { if (_debug) System.out.print("1"); setValue(param3, "1"); } else { if (_debug) System.out.print("0"); setValue(param3, "0"); } if (_debug) System.out.println(" at location "+param3); _instructionPointer += 4; // move the pointer on. } break; case Instructions.RELATIVE_BASE: { /* * The relative base increases (or decreases, if the value is negative) * by the value of the parameter. */ int param1 = Integer.valueOf(getValue(_instructionPointer+1, modes[0], false)); _relativeBase += param1; if (_debug) System.out.println("Relative base now "+_relativeBase); _instructionPointer += 2; } break; case Instructions.HALT: { /* * Means that the program is finished and should immediately halt. */ if (_debug) System.out.println("Halting execution."); _instructionPointer = _memory.size(); _status = Status.HALTED; return _status; } default: { System.out.println("Unknown opcode "+str+" encountered"); _instructionPointer = _memory.size(); // stop any further execution. _status = Status.HALTED; } } _status = Status.RUNNING; return _status; } // these methods ensure capacity is available private String getValue (int index, int mode, boolean isOutput) { String param = null; switch (mode) { case ParameterMode.POSITION_MODE: { param = getValue(index); if (!isOutput) param = getValue(Integer.valueOf(param)); } break; case ParameterMode.IMMEDIATE_MODE: { param = getValue(index); } break; case ParameterMode.RELATIVE_MODE: { param = getValue(index); if (!isOutput) param = getValue(Integer.valueOf(param) + _relativeBase); else param = Integer.toString(Integer.valueOf(param) + _relativeBase); } break; default: { System.out.println("Unknown Parameter Mode found: "+mode); param = "-1"; } } return param; } private String getValue (int i) { if (_memory.size() <= i) _memory.setSize(i+EXPANSION_FACTOR); String str = _memory.elementAt(i); if (str == null) { str = INITIALISED_MEMORY; _memory.set(i, str); } return str; } private void setValue (int i, String str) { if (_memory.size() <= i) _memory.setSize(i+EXPANSION_FACTOR); _memory.set(i, str); } private String getOpcode (String digits) { String opcode = null; if ((digits != null) && (digits.length() > 2)) opcode = digits.substring(digits.length()-2); else opcode = digits; return opcode; } private boolean _debug; private int _instructionPointer; private Vector<String> _output; private Vector<String> _memory; private Vector<String> _input; private int _status; private int _relativeBase; private static final int EXPANSION_FACTOR = 10; // if we need to increase memory, add a bit more to reduce multiple back-to-back expansions }