answer
stringlengths
17
10.2M
package org.azavea.otm; import java.text.NumberFormat; import java.util.Locale; import org.azavea.otm.data.Model; import org.azavea.otm.data.Plot; import org.json.JSONException; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.widget.TextView; public class EcoField extends Field { private static final String VALUE_KEY = ".value"; private static final String UNIT_KEY = ".unit"; private static final String AMOUNT_KEY = ".dollars"; // Eco fields are calculated, not edited, so they have much less // information in their definition. protected EcoField(String key, String label, int minimumToEdit, String keyboard, String format, String type) { super(key, label, minimumToEdit, keyboard, format, type, null, null); } @Override public View renderForDisplay(LayoutInflater layout, Plot model, Context context) throws JSONException { View container = layout.inflate(R.layout.plot_ecofield_row, null); ((TextView)container.findViewById(R.id.field_label)).setText(this.label); // Extract the value of this type of eco benefit Object value = getValueForKey(this.key + VALUE_KEY, model.getData()); Object units = getValueForKey(this.key + UNIT_KEY, model.getData()); if (value != null) { String valueTruncated = String.format("%.1f", value); ((TextView)container.findViewById(R.id.field_value)) .setText(valueTruncated + " " + units); // The dollar amount of the benefit NumberFormat currency = NumberFormat.getCurrencyInstance(App.getFieldManager().getLocale()); currency.setMaximumFractionDigits(2); Double amount = (Double)getValueForKey(this.key + AMOUNT_KEY, model.getData()); ((TextView)container.findViewById(R.id.field_money)) .setText(currency.format(amount)); } return container; } }
package org.apache.gora.pig; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import org.apache.avro.Schema; import org.apache.avro.Schema.Field; import org.apache.avro.Schema.Type; import org.apache.avro.generic.GenericData; import org.apache.avro.generic.GenericData.Array; import org.apache.gora.mapreduce.GoraInputFormat; import org.apache.gora.mapreduce.GoraInputFormatFactory; import org.apache.gora.mapreduce.GoraOutputFormat; import org.apache.gora.mapreduce.GoraOutputFormatFactory; import org.apache.gora.mapreduce.GoraRecordReader; import org.apache.gora.mapreduce.GoraRecordWriter; import org.apache.gora.persistency.impl.PersistentBase; import org.apache.gora.query.Query; import org.apache.gora.store.DataStore; import org.apache.gora.store.DataStoreFactory; import org.apache.gora.util.AvroUtils; import org.apache.gora.util.GoraException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapreduce.InputFormat; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.OutputFormat; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.RecordWriter; import org.apache.pig.Expression; import org.apache.pig.LoadCaster; import org.apache.pig.LoadFunc; import org.apache.pig.LoadMetadata; import org.apache.pig.ResourceSchema; import org.apache.pig.ResourceSchema.ResourceFieldSchema; import org.apache.pig.ResourceStatistics; import org.apache.pig.StoreFuncInterface; import org.apache.pig.backend.executionengine.ExecException; import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigSplit; import org.apache.pig.data.BagFactory; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.DataType; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.apache.pig.impl.util.UDFContext; import org.apache.pig.impl.util.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class GoraStorage extends LoadFunc implements StoreFuncInterface, LoadMetadata { public static final Logger LOG = LoggerFactory.getLogger(GoraStorage.class); /** * Key in UDFContext properties that marks config is set (set at backend nodes) */ private static final String GORA_CONFIG_SET = "gorastorage.config.set" ; private static final String GORA_STORE_SCHEMA = "gorastorage.pig.store.schema" ; protected Job job; protected JobConf localJobConf ; protected String udfcSignature = null ; protected String keyClassName ; protected String persistentClassName ; protected Class<?> keyClass; protected Class<? extends PersistentBase> persistentClass; protected Schema persistentSchema ; private DataStore<?, ? extends PersistentBase> dataStore ; protected GoraInputFormat<?,? extends PersistentBase> inputFormat ; protected GoraRecordReader<?,? extends PersistentBase> reader ; protected PigGoraOutputFormat<?,? extends PersistentBase> outputFormat ; protected GoraRecordWriter<?,? extends PersistentBase> writer ; protected PigSplit split ; protected ResourceSchema readResourceSchema ; protected ResourceSchema writeResourceSchema ; private Map<String, ResourceFieldSchemaWithIndex> writeResourceFieldSchemaMap ; /** Fields to load as Query - same as {@link loadSaveFields} but without 'key' */ protected String[] loadQueryFields ; /** Setted to 'true' if location is '*'. All fields will be loaded into a tuple when reading, * and all tuple fields will be copied to the persistent instance when saving. */ protected boolean loadSaveAllFields = false ; public GoraStorage(String keyClassName, String persistentClassName) throws InstantiationException, IllegalAccessException { this(keyClassName, persistentClassName, "*") ; } public GoraStorage(String keyClassName, String persistentClassName, String csvFields) throws InstantiationException, IllegalAccessException { super(); LOG.trace("***"+(UDFContext.getUDFContext().isFrontend()?"[FRONTEND]":"[BACKEND]")+" GoraStorage constructor() {}", this); this.keyClassName = keyClassName ; this.persistentClassName = persistentClassName ; try { this.keyClass = Class.forName(keyClassName); Class<?> persistentClazz = Class.forName(persistentClassName); this.persistentClass = persistentClazz.asSubclass(PersistentBase.class); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } this.persistentSchema = this.persistentClass.newInstance().getSchema() ; // Populates this.loadQueryFields List<String> declaredConstructorFields = new ArrayList<String>() ; if (csvFields.contains("*")) { // Declared fields "*" this.setLoadSaveAllFields(true) ; for (Field field : this.persistentSchema.getFields()) { declaredConstructorFields.add(field.name()) ; } } else { // CSV fields declared in constructor. String[] fieldsInConstructor = csvFields.split("\\s*,\\s*") ; // splits "field, field, field, field" declaredConstructorFields.addAll(Arrays.asList(fieldsInConstructor)) ; } this.setLoadQueryFields(declaredConstructorFields.toArray(new String[0])) ; } /** * Returns the internal DataStore for <code>&lt;keyClass,persistentClass&gt;</code> * using configuration set in job (from setLocation()). * Creates one datastore at first call. * @return DataStore for &lt;keyClass,persistentClass&gt; * @throws GoraException on DataStore creation error. */ protected DataStore<?, ? extends PersistentBase> getDataStore() throws GoraException { if (this.localJobConf == null) { throw new GoraException("Calling getDataStore(). setLocation()/setStoreLocation() must be called first!") ; } if (this.dataStore == null) { this.dataStore = DataStoreFactory.getDataStore(this.keyClass, this.persistentClass, this.localJobConf) ; } return this.dataStore ; } /** * Gets the job, initialized the localJobConf (the actual used to create a datastore) and splits from 'location' the fields to load/save * */ @Override public void setLocation(String location, Job job) throws IOException { LOG.trace("***"+(UDFContext.getUDFContext().isFrontend()?"[FRONTEND]":"[BACKEND]")+" GoraStorage setLocation() {} {}", location, this); this.job = job; this.localJobConf = this.initializeLocalJobConfig(job) ; } /** * Returns UDFProperties based on <code>udfcSignature</code>, <code>keyClassName</code> and <code>persistentClassName</code>. */ private Properties getUDFProperties() { return UDFContext.getUDFContext().getUDFProperties(this.getClass(), new String[] {this.udfcSignature,this.keyClassName,this.persistentClassName}); } private JobConf initializeLocalJobConfig(Job job) { Properties udfProps = getUDFProperties(); Configuration jobConf = job.getConfiguration(); JobConf localConf = new JobConf(jobConf); // localConf starts as a copy of jobConf if (udfProps.containsKey(GORA_CONFIG_SET)) { // Already configured (maybe from frontend to backend) for (Entry<Object, Object> entry : udfProps.entrySet()) { localConf.set((String) entry.getKey(), (String) entry.getValue()); } } else { // Not configured. We load to localConf the configuration and put it in udfProps Configuration goraConf = new Configuration(); for (Entry<String, String> entry : goraConf) { // JobConf may have some conf overriding ones in hbase-site.xml // So only copy hbase config not in job config to UDFContext // Also avoids copying core-default.xml and core-site.xml // props in hbaseConf to UDFContext which would be redundant. if (localConf.get(entry.getKey()) == null) { udfProps.setProperty(entry.getKey(), entry.getValue()); localConf.set(entry.getKey(), entry.getValue()); } } udfProps.setProperty(GORA_CONFIG_SET, "true"); } return localConf; } @Override @SuppressWarnings({ "rawtypes", "unchecked" }) public InputFormat getInputFormat() throws IOException { LOG.trace("***"+(UDFContext.getUDFContext().isFrontend()?"[FRONTEND]":"[BACKEND]")+" GoraStorage getInputFormat() {}", this); this.inputFormat = GoraInputFormatFactory.createInstance(this.keyClass, this.persistentClass); Query query = this.getDataStore().newQuery() ; if (this.isLoadSaveAllFields() == false) { query.setFields(this.getLoadQueryFields()) ; } GoraInputFormat.setInput(this.job, query, false) ; inputFormat.setConf(this.job.getConfiguration()) ; return this.inputFormat ; } @Override public LoadCaster getLoadCaster() throws IOException { LOG.trace("***"+(UDFContext.getUDFContext().isFrontend()?"[FRONTEND]":"[BACKEND]")+" GoraStorage getLoadCaster()", this); return null; } @Override @SuppressWarnings({ "rawtypes" }) public void prepareToRead(RecordReader reader, PigSplit split) throws IOException { LOG.trace("***"+(UDFContext.getUDFContext().isFrontend()?"[FRONTEND]":"[BACKEND]")+" GoraStorage prepareToRead {}", this); this.reader = (GoraRecordReader<?, ?>) reader; this.split = split; } @Override public Tuple getNext() throws IOException { LOG.trace("***"+(UDFContext.getUDFContext().isFrontend()?"[FRONTEND]":"[BACKEND]")+" GoraStorage getNext() {}", this); try { if (!this.reader.nextKeyValue()) return null; } catch (Exception e) { throw new IOException(e); } PersistentBase persistentObj; Object persistentKey ; try { persistentKey = this.reader.getCurrentKey() ; persistentObj = this.reader.getCurrentValue(); } catch (Exception e) { throw new IOException(e); } return persistent2Tuple(persistentKey, persistentObj, this.getLoadQueryFields()) ; } /** * Creates a pig tuple from a PersistentBase, given some fields in order. It adds "key" field. * The resulting tuple has fields (key, field1, field2,...) * * Internally calls persistentField2PigType(Schema, Object) for each field * * @param persistentKey Key of the PersistentBase object * @param persistentObj PersistentBase instance * @return Tuple with schemafields+1 elements (1<sup>st</sup> element is the row key) * @throws ExecException * On setting tuple field errors */ private static Tuple persistent2Tuple(Object persistentKey, PersistentBase persistentObj, String[] fields) throws ExecException { Tuple tuple = TupleFactory.getInstance().newTuple(fields.length + 1); Schema avroSchema = persistentObj.getSchema() ; tuple.set(0, persistentKey) ; int fieldIndex = 1 ; for (String fieldName : fields) { Field field = avroSchema.getField(fieldName) ; Schema fieldSchema = field.schema() ; Object fieldValue = persistentObj.get(field.pos()) ; tuple.set(fieldIndex++, persistentField2PigType(fieldSchema, fieldValue)) ; } return tuple ; } /** * Recursively converts PersistentBase fields to Pig type: Tuple | Bag | String | Long | ... * * The mapping is as follows: * null -> null * Boolean -> Boolean * Enum -> Integer * ByteBuffer -> DataByteArray * String -> String * Float -> Float * Double -> Double * Integer -> Integer * Long -> Long * Union -> X * Record -> Tuple * Array -> Bag * Map<String,b'> -> HashMap<String,Object> * * @param schema Source schema * @param data Source data: PersistentBase | String | Long,... * @return Pig type: Tuple | Bag | String | Long | ... * @throws ExecException */ @SuppressWarnings("unchecked") private static Object persistentField2PigType(Schema schema, Object data) throws ExecException { Type schemaType = schema.getType(); switch (schemaType) { case NULL: return null ; case BOOLEAN: return (Boolean)data ; case ENUM: return new Integer(((Enum<?>)data).ordinal()) ; case BYTES: return new DataByteArray(((ByteBuffer)data).array()) ; case STRING: return data.toString() ; case FLOAT: case DOUBLE: case INT: case LONG: return data ; case UNION: int unionIndex = GenericData.get().resolveUnion(schema, data) ; Schema unionTypeSchema = schema.getTypes().get(unionIndex) ; return persistentField2PigType(unionTypeSchema, data) ; case RECORD: List<Field> recordFields = schema.getFields() ; int numRecordElements = recordFields.size() ; Tuple recordTuple = TupleFactory.getInstance().newTuple(numRecordElements); for (int i=0; i<numRecordElements ; i++ ) { recordTuple.set(i, persistentField2PigType(recordFields.get(i).schema(), ((PersistentBase)data).get(i))) ; } return recordTuple ; case ARRAY: DataBag bag = BagFactory.getInstance().newDefaultBag() ; Schema arrValueSchema = schema.getElementType() ; for(Object element: (List<?>)data) { Object pigElement = persistentField2PigType(arrValueSchema, element) ; if (pigElement instanceof Tuple) { bag.add((Tuple)pigElement) ; } else { Tuple arrElemTuple = TupleFactory.getInstance().newTuple(1) ; arrElemTuple.set(0, pigElement) ; bag.add(arrElemTuple) ; } } return bag ; case MAP: HashMap<String,Object> map = new HashMap<String,Object>() ; for (Entry<CharSequence,?> e : ((Map<CharSequence,?>)data).entrySet()) { map.put(e.getKey().toString(), persistentField2PigType(schema.getValueType(), e.getValue())) ; } return map ; case FIXED: // TODO: Implement FIXED data type throw new RuntimeException("Fixed type not implemented") ; default: LOG.error("Unexpected schema type {}", schemaType) ; throw new RuntimeException("Unexpected schema type " + schemaType) ; } } @Override public void setUDFContextSignature(String signature) { LOG.trace("***"+(UDFContext.getUDFContext().isFrontend()?"[FRONTEND]":"[BACKEND]")+" GoraStorage setUDFContextSignature() {}", this); this.udfcSignature = signature; } @Override public String relativeToAbsolutePath(String location, Path curDir) throws IOException { // Do nothing return location ; } /** * Retrieves the Pig Schema from the declared fields in constructor and the Avro Schema * Avro Schema must begin with a record. * Pig Schema will be a Tuple (in 1st level) with $0 = "key":rowkey */ @Override public ResourceSchema getSchema(String location, Job job) throws IOException { LOG.trace("***"+(UDFContext.getUDFContext().isFrontend()?"[FRONTEND]":"[BACKEND]")+" GoraStorage getSchema() {}", this); // Reuse if already created if (this.readResourceSchema != null) return this.readResourceSchema ; ResourceFieldSchema[] resourceFieldSchemas = null ; int numFields = this.loadQueryFields.length + 1 ; resourceFieldSchemas = new ResourceFieldSchema[numFields] ; resourceFieldSchemas[0] = new ResourceFieldSchema().setType(DataType.findType(this.keyClass)).setName("key") ; for (int fieldIndex = 1; fieldIndex < numFields ; fieldIndex++) { Field field = this.persistentSchema.getField(this.loadQueryFields[fieldIndex-1]) ; resourceFieldSchemas[fieldIndex] = this.avro2ResouceFieldSchema(field.schema()).setName(field.name()) ; } ResourceSchema resourceSchema = new ResourceSchema().setFields(resourceFieldSchemas) ; // Save Pig schema inside the instance this.readResourceSchema = resourceSchema ; return this.readResourceSchema ; } private ResourceFieldSchema avro2ResouceFieldSchema(Schema schema) throws IOException { Type schemaType = schema.getType(); switch (schemaType) { case NULL: return new ResourceFieldSchema().setType(DataType.NULL) ; case BOOLEAN: return new ResourceFieldSchema().setType(DataType.BOOLEAN) ; case ENUM: return new ResourceFieldSchema().setType(DataType.INTEGER) ; case BYTES: return new ResourceFieldSchema().setType(DataType.BYTEARRAY); case STRING: return new ResourceFieldSchema().setType(DataType.CHARARRAY) ; case FLOAT: return new ResourceFieldSchema().setType(DataType.FLOAT) ; case DOUBLE: return new ResourceFieldSchema().setType(DataType.DOUBLE) ; case INT: return new ResourceFieldSchema().setType(DataType.INTEGER) ; case LONG: return new ResourceFieldSchema().setType(DataType.LONG) ; case UNION: // Returns the first not-null type if (schema.getTypes().size() != 2) { LOG.warn("Field UNION {} must be ['null','othertype']. Maybe wrong definition?") ; } for (Schema s: schema.getTypes()) { if (s.getType() != Type.NULL) return avro2ResouceFieldSchema(s) ; } throw new RuntimeException("Union with only ['null']?") ; case RECORD: // A record in Gora is a Tuple in Pig int numRecordFields = schema.getFields().size() ; Iterator<Field> recordFields = schema.getFields().iterator(); ResourceFieldSchema returnRecordResourceFieldSchema = new ResourceFieldSchema().setType(DataType.TUPLE) ; ResourceFieldSchema[] recordFieldSchemas = new ResourceFieldSchema[numRecordFields] ; for (int fieldIndex = 0; recordFields.hasNext(); fieldIndex++) { Field schemaField = recordFields.next(); recordFieldSchemas[fieldIndex] = this.avro2ResouceFieldSchema(schemaField.schema()).setName(schemaField.name()) ; } returnRecordResourceFieldSchema.setSchema(new ResourceSchema().setFields(recordFieldSchemas)) ; return returnRecordResourceFieldSchema ; case ARRAY: // An array in Gora is a Bag in Pig // Maybe should be a Map with string(numeric) index to ensure order, but Avro and Pig data model are different :\ ResourceFieldSchema returnArrayResourceFieldSchema = new ResourceFieldSchema().setType(DataType.BAG) ; Schema arrayElementType = schema.getElementType() ; returnArrayResourceFieldSchema.setSchema( new ResourceSchema().setFields( new ResourceFieldSchema[]{ new ResourceFieldSchema().setType(DataType.TUPLE).setName("t").setSchema( new ResourceSchema().setFields( new ResourceFieldSchema[]{ avro2ResouceFieldSchema(arrayElementType) } ) ) } ) ) ; return returnArrayResourceFieldSchema ; case MAP: // A map in Gora is a Map in Pig, but in pig is only chararray=>something ResourceFieldSchema returnMapResourceFieldSchema = new ResourceFieldSchema().setType(DataType.MAP) ; Schema mapValueType = schema.getValueType(); returnMapResourceFieldSchema.setSchema( new ResourceSchema().setFields( new ResourceFieldSchema[]{ avro2ResouceFieldSchema(mapValueType) } ) ) ; return returnMapResourceFieldSchema ; case FIXED: // TODO Implement FIXED data type throw new RuntimeException("Fixed type not implemented") ; default: LOG.error("Unexpected schema type {}", schemaType) ; throw new RuntimeException("Unexpected schema type " + schemaType) ; } } @Override public ResourceStatistics getStatistics(String location, Job job) throws IOException { // TODO Not implemented since Pig does not use it (feb 2013) return null; } @Override /** * Disabled by now (returns null). * Later we will consider only one partition key: row key */ public String[] getPartitionKeys(String location, Job job) throws IOException { // TODO Disabled by now return null ; //return new String[] {"key"} ; } @Override /** * Ignored by now since getPartitionKeys() return null */ public void setPartitionFilter(Expression partitionFilter) throws IOException { // TODO Ignored since getPartitionsKeys() return null throw new IOException() ; } @Override public String relToAbsPathForStoreLocation(String location, Path curDir) throws IOException { // Do nothing return location ; } @Override @SuppressWarnings({ "rawtypes", "unchecked" }) public OutputFormat getOutputFormat() throws IOException { LOG.trace("***"+(UDFContext.getUDFContext().isFrontend()?"[FRONTEND]":"[BACKEND]")+" GoraStorage getOutputFormat() {}", this); try { this.outputFormat = GoraOutputFormatFactory.createInstance(PigGoraOutputFormat.class, this.keyClass, this.persistentClass); } catch (Exception e) { throw new IOException(e) ; } GoraOutputFormat.setOutput(this.job, this.getDataStore(), false) ; this.outputFormat.setConf(this.job.getConfiguration()) ; return this.outputFormat ; } @Override public void setStoreLocation(String location, Job job) throws IOException { LOG.trace("***"+(UDFContext.getUDFContext().isFrontend()?"[FRONTEND]":"[BACKEND]")+" GoraStorage setStoreLocation() {}", this) ; this.job = job ; this.localJobConf = this.initializeLocalJobConfig(job) ; } @Override /** * Checks the pig schema using names, using the first element of the tuple as key (fieldname = 'key'). * (key:key, name:recordfield, name:recordfield, name:recordfi...) * * Sets UDFContext property GORA_STORE_SCHEMA with the schema to send it to the backend. * * Not present names for recordfields will be treated as null . */ public void checkSchema(ResourceSchema s) throws IOException { LOG.trace("***"+(UDFContext.getUDFContext().isFrontend()?"[FRONTEND]":"[BACKEND]")+" GoraStorage checkSchema() {}", this); // Expected pig schema: tuple (key, recordfield, recordfield, recordfi...) ResourceFieldSchema[] pigFieldSchemas = s.getFields(); List<String> pigFieldSchemasNames = new ArrayList<String>(Arrays.asList(s.fieldNames())) ; if ( !pigFieldSchemasNames.contains("key") ) { throw new IOException("Expected a field called \"key\" but not found.") ; } // All fields are mandatory List<String> mandatoryFieldNames = new ArrayList<String>(Arrays.asList(this.loadQueryFields)) ; if (pigFieldSchemasNames.containsAll(mandatoryFieldNames)) { for (ResourceFieldSchema pigFieldSchema: pigFieldSchemas) { if (mandatoryFieldNames.contains(pigFieldSchema.getName())) { Field persistentField = this.persistentSchema.getField(pigFieldSchema.getName()) ; if (persistentField == null) { throw new IOException("Declared field in Pig [" + pigFieldSchema.getName() + "] to store does not exists in " + this.persistentClassName +".") ; } checkEqualSchema(pigFieldSchema, this.persistentSchema.getField(pigFieldSchema.getName()).schema()) ; } } } else { throw new IOException("Some fields declared in the constructor (" + Arrays.toString(this.loadQueryFields) + ") are missing in the tuples to be saved (" + Arrays.toString(s.fieldNames()) + ")" ) ; } // Save the schema to UDFContext to use it on backend when writing data getUDFProperties().setProperty(GoraStorage.GORA_STORE_SCHEMA, s.toString()) ; } /** * Checks a Pig field schema comparing with avro schema, based on pig field's name (for record fields). * * @param pigFieldSchema A Pig field schema * @param avroSchema Avro schema related with pig field schema. * @throws IOException */ private void checkEqualSchema(ResourceFieldSchema pigFieldSchema, Schema avroSchema) throws IOException { byte pigType = pigFieldSchema.getType() ; String fieldName = pigFieldSchema.getName() ; Type avroType = avroSchema.getType() ; // Switch that checks if avro type matches pig type, or if avro is union and some nested type matches pig type. switch (pigType) { case DataType.BAG: // Avro Array if (!avroType.equals(Type.ARRAY) && !checkUnionSchema(avroSchema, pigFieldSchema)) throw new IOException("Can not convert field [" + fieldName + "] from Pig BAG with schema " + pigFieldSchema.getSchema() + " to avro " + avroType.name()) ; checkEqualSchema(pigFieldSchema.getSchema().getFields()[0].getSchema().getFields()[0], avroSchema.getElementType()) ; break ; case DataType.BOOLEAN: if (!avroType.equals(Type.BOOLEAN) && !checkUnionSchema(avroSchema, pigFieldSchema)) throw new IOException("Can not convert field [" + fieldName + "] from Pig BOOLEAN with schema " + pigFieldSchema.getSchema() + " to avro " + avroType.name()) ; break ; case DataType.BYTEARRAY: if (!avroType.equals(Type.BYTES) && !checkUnionSchema(avroSchema, pigFieldSchema)) throw new IOException("Can not convert field [" + fieldName + "] from Pig BYTEARRAY with schema " + pigFieldSchema.getSchema() + " to avro " + avroType.name()) ; break ; case DataType.CHARARRAY: // String if (!avroType.equals(Type.STRING) && !checkUnionSchema(avroSchema, pigFieldSchema)) throw new IOException("Can not convert field [" + fieldName + "] from Pig CHARARRAY with schema " + pigFieldSchema.getSchema() + " to avro " + avroType.name()) ; break; case DataType.DOUBLE: if (!avroType.equals(Type.DOUBLE) && !checkUnionSchema(avroSchema, pigFieldSchema)) throw new IOException("Can not convert field [" + fieldName + "] from Pig DOUBLE with schema " + pigFieldSchema.getSchema() + " to avro " + avroType.name()) ; break ; case DataType.FLOAT: if (!avroType.equals(Type.FLOAT) && !checkUnionSchema(avroSchema, pigFieldSchema)) throw new IOException("Can not convert field [" + fieldName + "] from Pig FLOAT with schema " + pigFieldSchema.getSchema() + " to avro " + avroType.name()) ; break ; case DataType.INTEGER: // Int or Enum if (!avroType.equals(Type.INT) && !avroType.equals(Type.ENUM) && !checkUnionSchema(avroSchema, pigFieldSchema)) throw new IOException("Can not convert field [" + fieldName + "] from Pig INTEGER with schema " + pigFieldSchema.getSchema() + " to avro " + avroType.name()) ; break ; case DataType.LONG: if (!avroType.equals(Type.LONG) && !checkUnionSchema(avroSchema, pigFieldSchema)) throw new IOException("Can not convert field [" + fieldName + "] from Pig LONG with schema " + pigFieldSchema.getSchema() + " to avro " + avroType.name()) ; break ; case DataType.MAP: // Avro Map if (!avroType.equals(Type.MAP) && !checkUnionSchema(avroSchema, pigFieldSchema)) throw new IOException("Can not convert field [" + fieldName + "] from Pig MAP with schema " + pigFieldSchema.getSchema() + " to avro " + avroType.name()) ; break ; case DataType.NULL: // Avro nullable?? if(!avroType.equals(Type.NULL) && !checkUnionSchema(avroSchema, pigFieldSchema)) throw new IOException("Can not convert field [" + fieldName + "] from Pig NULL with schema " + pigFieldSchema.getSchema() + " to avro " + avroType.name()) ; break ; case DataType.TUPLE: // Avro Record if (!avroType.equals(Type.RECORD) && !checkUnionSchema(avroSchema, pigFieldSchema)) throw new IOException("Can not convert field [" + fieldName + "] from Pig TUPLE(record) with schema " + pigFieldSchema.getSchema() + " to avro " + avroType.name()) ; break ; default: throw new IOException("Unexpected Pig schema type " + DataType.genTypeToNameMap().get(pigType) + " for avro schema field " + avroSchema.getName() +": " + avroType.name()) ; } } /** * Checks and tries to match a pig field schema with an avro union schema. * @param avroSchema Schema with * @param pigFieldSchema * @return true: if a match is found * false: if avro schema is not UNION * @throws IOException(message, Exception()) if avro schema is UNION but not match is found for pig field schema. */ private boolean checkUnionSchema(Schema avroSchema, ResourceFieldSchema pigFieldSchema) throws IOException { if (!avroSchema.getType().equals(Type.UNION)) return false ; for (Schema unionElementSchema: avroSchema.getTypes()) { try { checkEqualSchema(pigFieldSchema, unionElementSchema) ; return true ; }catch (IOException e){ // Exception from inner union, rethrow if (e.getCause() != null) { throw e ; } // else ignore } } // throws IOException(message,Exception()) to mark nested union exception. throw new IOException("Expected some field defined in '"+avroSchema.getName()+"' for pig schema type '"+DataType.genTypeToNameMap().get(pigFieldSchema.getType()+"'"), new Exception("Union not satisfied")) ; } @Override @SuppressWarnings({ "rawtypes", "unchecked" }) public void prepareToWrite(RecordWriter writer) throws IOException { LOG.trace("***"+(UDFContext.getUDFContext().isFrontend()?"[FRONTEND]":"[BACKEND]")+" GoraStorage prepareToWrite() {}", this); this.writer = (GoraRecordWriter<?,? extends PersistentBase>) writer ; // Get the schema of data to write from UDFContext (coming from frontend checkSchema()) String strSchema = getUDFProperties().getProperty(GoraStorage.GORA_STORE_SCHEMA) ; if (strSchema == null) { throw new IOException("Could not find schema in UDF context. Should have been set in checkSchema() in frontend.") ; } // Parse de the schema from string stored in properties object this.writeResourceSchema = new ResourceSchema(Utils.getSchemaFromString(strSchema)) ; if (LOG.isTraceEnabled()) LOG.trace(this.writeResourceSchema.toString()) ; this.writeResourceFieldSchemaMap = new HashMap<String, ResourceFieldSchemaWithIndex>() ; int index = 0 ; for (ResourceFieldSchema fieldSchema : this.writeResourceSchema.getFields()) { this.writeResourceFieldSchemaMap.put(fieldSchema.getName(), new ResourceFieldSchemaWithIndex(fieldSchema, index++)) ; } } @SuppressWarnings("unchecked") @Override public void putNext(Tuple t) throws IOException { PersistentBase persistentObj ; persistentObj = this.dataStore.newPersistent() ; LOG.trace("key: {}", t.get(0)) ; for (String fieldName : this.loadQueryFields) { LOG.trace(" Put fieldName: {} {}", fieldName, this.writeResourceFieldSchemaMap.get(fieldName).getResourceFieldSchema()) ; LOG.trace(" value: {} - {}",this.writeResourceFieldSchemaMap.get(fieldName).getIndex(), t.get(this.writeResourceFieldSchemaMap.get(fieldName).getIndex())) ; persistentObj.put(persistentObj.getField2IndexMapping().get(fieldName), // name -> index this.writeField(persistentSchema.getField(fieldName).schema(), this.writeResourceFieldSchemaMap.get(fieldName).getResourceFieldSchema(), t.get(this.writeResourceFieldSchemaMap.get(fieldName).getIndex()))) ; } try { ((GoraRecordWriter<Object,PersistentBase>) this.writer).write(t.get(0), (PersistentBase) persistentObj) ; } catch (InterruptedException e) { throw new IOException(e) ; } this.dataStore.flush() ; } /** * Converts one pig field data to PersistentBase Data. * * @param avroSchema PersistentBase schema used to create new nested records * @param field Pig schema of the field being converted * @param pigData Pig data relative to the schema * @return PersistentBase data * @throws IOException */ private Object writeField(Schema avroSchema, ResourceFieldSchema field, Object pigData) throws IOException { // If data is null, return null (check if avro schema is right) if (pigData == null) { if (avroSchema.getType() != Type.UNION && avroSchema.getType() != Type.NULL) { throw new IOException("Tuple field " + field.getName() + " is null, but Avro Schema is not union nor null") ; } else { return null ; } } // If avroSchema is union, it will not be the null field, so select the proper one if (avroSchema.getType() == Type.UNION) { avroSchema = avroSchema.getTypes().get(1) ; } switch(field.getType()) { case DataType.DOUBLE: case DataType.FLOAT: case DataType.LONG: case DataType.BOOLEAN: case DataType.NULL: return (Object)pigData ; case DataType.CHARARRAY: return pigData.toString() ; case DataType.INTEGER: if (avroSchema.getType() == Type.ENUM) { AvroUtils.getEnumValue(avroSchema, (Integer)pigData); }else{ return (Integer)pigData ; } case DataType.BYTEARRAY: return ByteBuffer.wrap(((DataByteArray)pigData).get()) ; case DataType.MAP: // Pig Map -> Avro Map return pigData ; case DataType.BAG: // Pig Bag -> Avro Array Array<Object> persistentArray = new Array<Object>((int)((DataBag)pigData).size(),avroSchema) ; for (Object pigArrayElement: (DataBag)pigData) { if (avroSchema.getElementType().getType() == Type.RECORD) { // If element type is record, the mapping Persistent->PigType deletes one nested tuple: // We want the map as: map((a1,a2,a3), (b1,b2,b3),...) instead of map(((a1,a2,a3)), ((b1,b2,b3)), ...) persistentArray.add(this.writeField(avroSchema.getElementType(), field.getSchema().getFields()[0], pigArrayElement)) ; } else { // Every map has a tuple as element type. Since this is not a record, that "tuple" container must be ignored persistentArray.add(this.writeField(avroSchema.getElementType(), field.getSchema().getFields()[0], ((Tuple)pigArrayElement).get(0))) ; } } return persistentArray ; case DataType.TUPLE: // Pig Tuple -> Avro Record try { PersistentBase persistentRecord = (PersistentBase) Class.forName(avroSchema.getFullName()).newInstance(); ResourceFieldSchema[] tupleFieldSchemas = field.getSchema().getFields() ; for (int i=0; i<tupleFieldSchemas.length; i++) { persistentRecord.put(persistentRecord.getField2IndexMapping().get(tupleFieldSchemas[i].getName()), this.writeField(avroSchema.getField(tupleFieldSchemas[i].getName()).schema(), tupleFieldSchemas[i], ((Tuple)pigData).get(i))) ; } return persistentRecord ; } catch (InstantiationException e) { throw new IOException(e) ; } catch (IllegalAccessException e) { throw new IOException(e) ; } catch (ClassNotFoundException e) { throw new IOException(e) ; } default: throw new IOException("Unexpected field " + field.getName() +" with Pig type "+ DataType.genTypeToNameMap().get(field.getType())) ; } } @Override public void setStoreFuncUDFContextSignature(String signature) { LOG.trace("***"+(UDFContext.getUDFContext().isFrontend()?"[FRONTEND]":"[BACKEND]")+" GoraStorage setStoreFuncUDFContextSignature() {}", this); this.udfcSignature = signature ; } @Override public void cleanupOnFailure(String location, Job job) throws IOException { LOG.trace("***"+(UDFContext.getUDFContext().isFrontend()?"[FRONTEND]":"[BACKEND]")+" GoraStorage cleanupOnFailure() {}", this); } @Override public void cleanupOnSuccess(String location, Job job) throws IOException { if (dataStore != null) dataStore.flush() ; } public boolean isLoadSaveAllFields() { return loadSaveAllFields; } public void setLoadSaveAllFields(boolean loadSaveAllFields) { this.loadSaveAllFields = loadSaveAllFields; } public String[] getLoadQueryFields() { return loadQueryFields; } public void setLoadQueryFields(String[] loadQueryFields) { this.loadQueryFields = loadQueryFields; } }
package squeek.applecore.asm; import net.minecraft.block.Block; import net.minecraft.block.BlockCake; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Items; import net.minecraft.item.EnumAction; import net.minecraft.item.ItemFood; import net.minecraft.item.ItemStack; import net.minecraft.util.DamageSource; import net.minecraft.util.FoodStats; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.eventhandler.Event; import net.minecraftforge.fml.common.eventhandler.Event.Result; import squeek.applecore.api.AppleCoreAPI; import squeek.applecore.api.food.FoodEvent; import squeek.applecore.api.food.FoodValues; import squeek.applecore.api.hunger.ExhaustionEvent; import squeek.applecore.api.hunger.HealthRegenEvent; import squeek.applecore.api.hunger.HungerRegenEvent; import squeek.applecore.api.hunger.StarvationEvent; import squeek.applecore.api.plants.FertilizationEvent; import squeek.applecore.asm.util.IAppleCoreFertilizable; import squeek.applecore.asm.util.IAppleCoreFoodStats; import java.lang.reflect.Method; import java.util.Random; public class Hooks { public static boolean onAppleCoreFoodStatsUpdate(FoodStats foodStats, EntityPlayer player) { if (!(foodStats instanceof IAppleCoreFoodStats)) return false; IAppleCoreFoodStats appleCoreFoodStats = (IAppleCoreFoodStats) foodStats; appleCoreFoodStats.setPrevFoodLevel(foodStats.getFoodLevel()); Result allowExhaustionResult = Hooks.fireAllowExhaustionEvent(player); float maxExhaustion = Hooks.fireExhaustionTickEvent(player, appleCoreFoodStats.getExhaustion()); if (allowExhaustionResult == Result.ALLOW || (allowExhaustionResult == Result.DEFAULT && appleCoreFoodStats.getExhaustion() >= maxExhaustion)) { ExhaustionEvent.Exhausted exhaustedEvent = Hooks.fireExhaustionMaxEvent(player, maxExhaustion, appleCoreFoodStats.getExhaustion()); appleCoreFoodStats.setExhaustion(appleCoreFoodStats.getExhaustion() + exhaustedEvent.deltaExhaustion); if (!exhaustedEvent.isCanceled()) { appleCoreFoodStats.setSaturation(Math.max(foodStats.getSaturationLevel() + exhaustedEvent.deltaSaturation, 0.0F)); foodStats.setFoodLevel(Math.max(foodStats.getFoodLevel() + exhaustedEvent.deltaHunger, 0)); } } boolean hasNaturalRegen = player.worldObj.getGameRules().getBoolean("naturalRegeneration"); Result allowSaturatedRegenResult = Hooks.fireAllowSaturatedRegenEvent(player); boolean shouldDoSaturatedRegen = allowSaturatedRegenResult == Result.ALLOW || (allowSaturatedRegenResult == Result.DEFAULT && hasNaturalRegen && foodStats.getSaturationLevel() > 0.0F && player.shouldHeal() && foodStats.getFoodLevel() >= 20); Result allowRegenResult = shouldDoSaturatedRegen ? Result.DENY : Hooks.fireAllowRegenEvent(player); boolean shouldDoRegen = allowRegenResult == Result.ALLOW || (allowRegenResult == Result.DEFAULT && hasNaturalRegen && foodStats.getFoodLevel() >= 18 && player.shouldHeal()); if (shouldDoSaturatedRegen) { appleCoreFoodStats.setFoodTimer(appleCoreFoodStats.getFoodTimer()+1); if (appleCoreFoodStats.getFoodTimer() >= Hooks.fireSaturatedRegenTickEvent(player)) { HealthRegenEvent.SaturatedRegen saturatedRegenEvent = Hooks.fireSaturatedRegenEvent(player); if (!saturatedRegenEvent.isCanceled()) { player.heal(saturatedRegenEvent.deltaHealth); foodStats.addExhaustion(saturatedRegenEvent.deltaExhaustion); } appleCoreFoodStats.setFoodTimer(0); } } else if (shouldDoRegen) { appleCoreFoodStats.setFoodTimer(appleCoreFoodStats.getFoodTimer()+1); if (appleCoreFoodStats.getFoodTimer() >= Hooks.fireRegenTickEvent(player)) { HealthRegenEvent.Regen regenEvent = Hooks.fireRegenEvent(player); if (!regenEvent.isCanceled()) { player.heal(regenEvent.deltaHealth); foodStats.addExhaustion(regenEvent.deltaExhaustion); } appleCoreFoodStats.setFoodTimer(0); } } else { appleCoreFoodStats.setFoodTimer(0); } Result allowStarvationResult = Hooks.fireAllowStarvation(player); if (allowStarvationResult == Result.ALLOW || (allowStarvationResult == Result.DEFAULT && foodStats.getFoodLevel() <= 0)) { appleCoreFoodStats.setStarveTimer(appleCoreFoodStats.getStarveTimer()+1); if (appleCoreFoodStats.getStarveTimer() >= Hooks.fireStarvationTickEvent(player)) { StarvationEvent.Starve starveEvent = Hooks.fireStarveEvent(player); if (!starveEvent.isCanceled()) { player.attackEntityFrom(DamageSource.starve, starveEvent.starveDamage); } appleCoreFoodStats.setStarveTimer(0); } } else { appleCoreFoodStats.setStarveTimer(0); } return true; } public static FoodValues onFoodStatsAdded(FoodStats foodStats, ItemFood itemFood, ItemStack itemStack, EntityPlayer player) { return AppleCoreAPI.accessor.getFoodValuesForPlayer(itemStack, player); } public static void onPostFoodStatsAdded(FoodStats foodStats, ItemFood itemFood, ItemStack itemStack, FoodValues foodValues, int hungerAdded, float saturationAdded, EntityPlayer player) { MinecraftForge.EVENT_BUS.post(new FoodEvent.FoodEaten(player, itemStack, foodValues, hungerAdded, saturationAdded)); } public static int getItemInUseMaxCount(EntityLivingBase entityLiving, int savedMaxDuration) { EnumAction useAction = entityLiving.getActiveItemStack().getItemUseAction(); if (useAction == EnumAction.EAT || useAction == EnumAction.DRINK) return savedMaxDuration; else return entityLiving.getActiveItemStack().getMaxItemUseDuration(); } // should this be moved elsewhere? private static ItemStack getFoodFromBlock(Block block) { if (block instanceof BlockCake) return new ItemStack(Items.CAKE); return null; } public static FoodValues onBlockFoodEaten(Block block, World world, EntityPlayer player) { ItemStack itemStack = getFoodFromBlock(block); if (itemStack != null) return AppleCoreAPI.accessor.getFoodValuesForPlayer(itemStack, player); else return null; } public static void onPostBlockFoodEaten(Block block, FoodValues foodValues, int prevFoodLevel, float prevSaturationLevel, EntityPlayer player) { ItemStack itemStack = getFoodFromBlock(block); int hungerAdded = player.getFoodStats().getFoodLevel() - prevFoodLevel; float saturationAdded = player.getFoodStats().getSaturationLevel() - prevSaturationLevel; if (itemStack != null) MinecraftForge.EVENT_BUS.post(new FoodEvent.FoodEaten(player, itemStack, foodValues, hungerAdded, saturationAdded)); } public static Result fireAllowExhaustionEvent(EntityPlayer player) { ExhaustionEvent.AllowExhaustion event = new ExhaustionEvent.AllowExhaustion(player); MinecraftForge.EVENT_BUS.post(event); return event.getResult(); } public static float fireExhaustionTickEvent(EntityPlayer player, float foodExhaustionLevel) { return AppleCoreAPI.accessor.getMaxExhaustion(player); } public static ExhaustionEvent.Exhausted fireExhaustionMaxEvent(EntityPlayer player, float maxExhaustionLevel, float foodExhaustionLevel) { ExhaustionEvent.Exhausted event = new ExhaustionEvent.Exhausted(player, maxExhaustionLevel, foodExhaustionLevel); MinecraftForge.EVENT_BUS.post(event); return event; } public static Result fireAllowRegenEvent(EntityPlayer player) { HealthRegenEvent.AllowRegen event = new HealthRegenEvent.AllowRegen(player); MinecraftForge.EVENT_BUS.post(event); return event.getResult(); } public static Result fireAllowSaturatedRegenEvent(EntityPlayer player) { HealthRegenEvent.AllowSaturatedRegen event = new HealthRegenEvent.AllowSaturatedRegen(player); MinecraftForge.EVENT_BUS.post(event); return event.getResult(); } public static int fireRegenTickEvent(EntityPlayer player) { return AppleCoreAPI.accessor.getHealthRegenTickPeriod(player); } public static int fireSaturatedRegenTickEvent(EntityPlayer player) { return AppleCoreAPI.accessor.getSaturatedHealthRegenTickPeriod(player); } public static HealthRegenEvent.Regen fireRegenEvent(EntityPlayer player) { HealthRegenEvent.Regen event = new HealthRegenEvent.Regen(player); MinecraftForge.EVENT_BUS.post(event); return event; } public static HealthRegenEvent.SaturatedRegen fireSaturatedRegenEvent(EntityPlayer player) { HealthRegenEvent.SaturatedRegen event = new HealthRegenEvent.SaturatedRegen(player); MinecraftForge.EVENT_BUS.post(event); return event; } public static HealthRegenEvent.PeacefulRegen firePeacefulRegenEvent(EntityPlayer player) { HealthRegenEvent.PeacefulRegen event = new HealthRegenEvent.PeacefulRegen(player); MinecraftForge.EVENT_BUS.post(event); return event; } public static HungerRegenEvent.PeacefulRegen firePeacefulHungerRegenEvent(EntityPlayer player) { HungerRegenEvent.PeacefulRegen event = new HungerRegenEvent.PeacefulRegen(player); MinecraftForge.EVENT_BUS.post(event); return event; } public static Result fireAllowStarvation(EntityPlayer player) { StarvationEvent.AllowStarvation event = new StarvationEvent.AllowStarvation(player); MinecraftForge.EVENT_BUS.post(event); return event.getResult(); } public static int fireStarvationTickEvent(EntityPlayer player) { return AppleCoreAPI.accessor.getStarveDamageTickPeriod(player); } public static StarvationEvent.Starve fireStarveEvent(EntityPlayer player) { StarvationEvent.Starve event = new StarvationEvent.Starve(player); MinecraftForge.EVENT_BUS.post(event); return event; } public static boolean fireFoodStatsAdditionEvent(EntityPlayer player, FoodValues foodValuesToBeAdded) { FoodEvent.FoodStatsAddition event = new FoodEvent.FoodStatsAddition(player, foodValuesToBeAdded); MinecraftForge.EVENT_BUS.post(event); return event.isCancelable() ? event.isCanceled() : false; } public static Result fireAllowPlantGrowthEvent(Block block, World world, BlockPos pos, IBlockState state, Random random) { return AppleCoreAPI.dispatcher.validatePlantGrowth(block, world, pos, state, random); } public static void fireOnGrowthEvent(Block block, World world, BlockPos pos, IBlockState currentState, IBlockState previousState) { AppleCoreAPI.dispatcher.announcePlantGrowth(block, world, pos, currentState, previousState); } public static void fireOnGrowthEvent(Block block, World world, BlockPos pos, IBlockState previousState) { AppleCoreAPI.dispatcher.announcePlantGrowth(block, world, pos, previousState); } private static final Random fertilizeRandom = new Random(); public static void fireAppleCoreFertilizeEvent(Block block, World world, BlockPos pos, IBlockState state, Random random) { // if the block does not implement our dummy interface, then the transformation did occur if (!(block instanceof IAppleCoreFertilizable)) return; if (random == null) random = fertilizeRandom; IBlockState previousState = state; FertilizationEvent.Fertilize event = new FertilizationEvent.Fertilize(block, world, pos, state, random); MinecraftForge.EVENT_BUS.post(event); Event.Result fertilizeResult = event.getResult(); if (fertilizeResult == Event.Result.DENY) return; if (fertilizeResult == Event.Result.DEFAULT) { IAppleCoreFertilizable fertilizableBlock = (IAppleCoreFertilizable) block; try { fertilizableBlock.AppleCore_fertilize(world, random, pos, state); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } } Hooks.fireFertilizedEvent(block, world, pos, previousState); } public static void fireFertilizedEvent(Block block, World world, BlockPos pos, IBlockState previousState) { FertilizationEvent.Fertilized event = new FertilizationEvent.Fertilized(block, world, pos, previousState); MinecraftForge.EVENT_BUS.post(event); } public static int toolTipX, toolTipY, toolTipW, toolTipH; public static void onDrawHoveringText(int x, int y, int w, int h) { toolTipX = x; toolTipY = y; toolTipW = w; toolTipH = h; } }
package ohtu.beddit.web; import android.content.Context; import android.util.Log; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.stream.JsonReader; import javax.net.ssl.HttpsURLConnection; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Scanner; public class OAuthHandling { public static String getAccessToken(Context context, String url){ String token = "error"; HttpsURLConnection connect = null; InputStream inputStream = null; Scanner scanscan = null; try { URL address = new URL(url); Log.v("OAuth","url: "+address); System.setProperty("http.keepAlive", "false"); connect = (HttpsURLConnection) address.openConnection(); connect.connect(); Log.v("OAuth","responseCode: "+connect.getResponseCode()); inputStream = connect.getInputStream(); scanscan = new Scanner(inputStream); String stash = ""; while(scanscan.hasNext()) { stash += scanscan.next(); } Log.v("OAuth","stash: "+stash); String token1 = new JsonParser().parse(stash).getAsJsonObject().get("access_token").getAsString(); Log.v("AccessToken" ,"AccessToken = \""+token1+"\""); token = token1; } catch (Throwable e) { Log.v("AccessToken", Log.getStackTraceString(e)); //To change body of catch statement use File | Settings | File Templates. } finally { connect.disconnect(); if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } scanscan.close(); } return token; } }
package VASSAL.counters; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Frame; import java.awt.Graphics; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.Point; import java.awt.Rectangle; import java.awt.Shape; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.swing.DefaultCellEditor; import javax.swing.JButton; import javax.swing.JColorChooser; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JLayeredPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSpinner; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.KeyStroke; import javax.swing.ListSelectionModel; import javax.swing.SwingUtilities; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableCellEditor; import javax.swing.table.TableModel; import javax.swing.text.JTextComponent; import VASSAL.build.GameModule; import VASSAL.build.module.documentation.HelpFile; import VASSAL.command.ChangePiece; import VASSAL.command.Command; import VASSAL.i18n.PieceI18nData; import VASSAL.i18n.TranslatablePiece; import VASSAL.tools.ScrollPane; import VASSAL.tools.SequenceEncoder; /** * A Decorator class that endows a GamePiece with a dialog. */ public class PropertySheet extends Decorator implements TranslatablePiece { public static final String ID = "propertysheet;"; protected String oldState; // properties protected String menuName; protected char launchKey; protected KeyCommand launch; protected Color backgroundColor; protected String m_definition; protected PropertySheetDialog frame; protected JButton applyButton; // Commit type definitions final static String[] COMMIT_VALUES = {"Every Keystroke", "Apply Button or Enter Key", "Close Window or Enter Key"}; static final int COMMIT_IMMEDIATELY = 0; static final int COMMIT_ON_APPLY = 1; static final int COMMIT_ON_CLOSE = 2; static final int COMMIT_DEFAULT = COMMIT_IMMEDIATELY; // Field type definitions static final String[] TYPE_VALUES = {"Text", "Multi-line text", "Label Only", "Tick Marks", "Tick Marks with Max Field", "Tick Marks with Value Field", "Tick Marks with Value & Max", "Spinner"}; static final int TEXT_FIELD = 0; static final int TEXT_AREA = 1; static final int LABEL_ONLY = 2; static final int TICKS = 3; static final int TICKS_MAX = 4; static final int TICKS_VAL = 5; static final int TICKS_VALMAX = 6; static final int SPINNER = 7; protected int commitStyle = COMMIT_DEFAULT; protected boolean isUpdating; protected String state; protected Map<String,Object> properties = new HashMap<String,Object>(); protected List<JComponent> m_fields; static final char TYPE_DELIMITOR = ';'; static final char DEF_DELIMITOR = '~'; static final char STATE_DELIMITOR = '~'; static final char LINE_DELIMINATOR = '|'; static final char VALUE_DELIMINATOR = '/'; class PropertySheetDialog extends JDialog implements ActionListener { private static final long serialVersionUID = 1L; public PropertySheetDialog(Frame owner) { super(owner, false); } public void actionPerformed(ActionEvent event) { if (applyButton != null) { applyButton.setEnabled(false); } updateStateFromFields(); } } public PropertySheet() { // format is propertysheet;menu-name;keystroke;commitStyle;backgroundRed;backgroundGreen;backgroundBlue this(ID + ";Properties;P;;;;", null); } public PropertySheet(String type, GamePiece p) { mySetType(type); setInner(p); } /** Changes the "type" definition this decoration, which discards all value data and structures. * Format: definition; name; keystroke */ public void mySetType(String s) { s = s.substring(ID.length()); SequenceEncoder.Decoder st = new SequenceEncoder.Decoder(s, TYPE_DELIMITOR); m_definition = st.nextToken(); menuName = st.nextToken(); launchKey = st.nextChar('\0'); commitStyle = st.nextInt(COMMIT_DEFAULT); String red = st.hasMoreTokens() ? st.nextToken() : ""; String green = st.hasMoreTokens() ? st.nextToken() : ""; String blue = st.hasMoreTokens() ? st.nextToken() : ""; backgroundColor = red.equals("") ? null : new Color(atoi(red), atoi(green), atoi(blue)); frame = null; } public void draw(java.awt.Graphics g, int x, int y, java.awt.Component obs, double zoom) { piece.draw(g, x, y, obs, zoom); } public String getName() { return piece.getName(); } public java.awt.Rectangle boundingBox() { return piece.boundingBox(); } public Shape getShape() { return piece.getShape(); } public String myGetState() { return state; } public void mySetState(String state) { this.state = state; updateFieldsFromState(); } /** returns string defining the field types */ public String myGetType() { SequenceEncoder se = new SequenceEncoder(TYPE_DELIMITOR); String red = backgroundColor == null ? "" : Integer.toString(backgroundColor.getRed()); String green = backgroundColor == null ? "" : Integer.toString(backgroundColor.getGreen()); String blue = backgroundColor == null ? "" : Integer.toString(backgroundColor.getBlue()); String commit = Integer.toString(commitStyle); se.append(m_definition).append(menuName).append(launchKey).append(commit). append(red).append(green).append(blue); return ID + se.getValue(); } protected KeyCommand[] myGetKeyCommands() { if (launch == null) { launch = new KeyCommand(menuName, KeyStroke.getKeyStroke(launchKey, java.awt.event.InputEvent.CTRL_MASK), Decorator.getOutermost(this), this); } return new KeyCommand[]{launch}; } /** parses leading integer from string */ int atoi(String s) { int value = 0; if (s != null) { for (int i = 0; i < s.length() && Character.isDigit(s.charAt(i)); ++i) { value = value * 10 + s.charAt(i) - '0'; } } return value; } /** parses trailing integer from string */ int atoiRight(String s) { int value = 0; if (s != null) { int base = 1; for (int i = s.length() - 1; i >= 0 && Character.isDigit(s.charAt(i)); --i, base *= 10) { value = value + base * (s.charAt(i) - '0'); } } return value; } // stores field values private void updateStateFromFields() { SequenceEncoder encoder = new SequenceEncoder(STATE_DELIMITOR); for (Object field : m_fields) { if (field instanceof JTextComponent) { encoder.append(((JTextComponent) field).getText() .replace('\n', LINE_DELIMINATOR)); } else if (field instanceof TickPanel) { encoder.append(((TickPanel) field).getValue()); } else { encoder.append("Unknown"); } } if (encoder.getValue() != null && !encoder.getValue().equals(state)) { mySetState(encoder.getValue()); GamePiece outer = Decorator.getOutermost(PropertySheet.this); if (outer.getId() != null) { GameModule.getGameModule().sendAndLog( new ChangePiece(outer.getId(), oldState, outer.getState())); } } } private void updateFieldsFromState() { isUpdating = true; properties.clear(); SequenceEncoder.Decoder defDecoder = new SequenceEncoder.Decoder(m_definition, DEF_DELIMITOR); SequenceEncoder.Decoder stateDecoder = new SequenceEncoder.Decoder(state, STATE_DELIMITOR); for (int iField = 0; defDecoder.hasMoreTokens(); ++iField) { String name = defDecoder.nextToken(); if (name.length() == 0) { continue; } int type = name.charAt(0) - '0'; name = name.substring(1); String value = stateDecoder.nextToken(""); switch (type) { case TICKS: case TICKS_VAL: case TICKS_MAX: case TICKS_VALMAX: int index = value.indexOf('/'); if (index > 0) { properties.put(name, value.substring(0, index)); } else { properties.put(name, value); } break; default: properties.put(name, value); } value = value.replace(LINE_DELIMINATOR, '\n'); if (frame != null) { Object field = m_fields.get(iField); if (field instanceof JTextComponent) { JTextComponent tf = (JTextComponent) field; int pos = tf.getCaretPosition(); tf.setText(value); tf.setCaretPosition(pos); } else if (field instanceof TickPanel) { ((TickPanel) field).updateValue(value); } } } if (applyButton != null) { applyButton.setEnabled(false); } isUpdating = false; } public Command myKeyEvent(KeyStroke stroke) { myGetKeyCommands(); if (launch.matches(stroke)) { if (frame == null) { m_fields = new ArrayList<JComponent>(); VASSAL.build.module.Map map = piece.getMap(); Frame parent = null; if (map != null && map.getView() != null) { Container topWin = map.getView().getTopLevelAncestor(); if (topWin instanceof JFrame) { parent = (Frame) topWin; } } else { parent = GameModule.getGameModule().getFrame(); } frame = new PropertySheetDialog(parent); JPanel pane = new JPanel(); JScrollPane scroll = new JScrollPane(pane, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); frame.add(scroll); // set up Apply button if (commitStyle == COMMIT_ON_APPLY) { applyButton = new JButton("Apply"); applyButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { if (applyButton != null) { applyButton.setEnabled(false); } updateStateFromFields(); } }); applyButton.setMnemonic(java.awt.event.KeyEvent.VK_A); // respond to Alt+A applyButton.setEnabled(false); } // ... enable APPLY button when field changes DocumentListener changeListener = new DocumentListener() { public void insertUpdate(DocumentEvent e) { update(e); } public void removeUpdate(DocumentEvent e) { update(e); } public void changedUpdate(DocumentEvent e) { update(e); } public void update(DocumentEvent e) { if (!isUpdating) { switch (commitStyle) { case COMMIT_IMMEDIATELY: // queue commit operation because it could do something unsafe in a an event update javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { updateStateFromFields(); } }); break; case COMMIT_ON_APPLY: applyButton.setEnabled(true); break; case COMMIT_ON_CLOSE: break; default: throw new RuntimeException(); } } } }; pane.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.BOTH; c.insets = new Insets(1, 3, 1, 3); c.gridx = 0; c.gridy = 0; c.fill = GridBagConstraints.BOTH; SequenceEncoder.Decoder defDecoder = new SequenceEncoder.Decoder(m_definition, DEF_DELIMITOR); SequenceEncoder.Decoder stateDecoder = new SequenceEncoder.Decoder(state, STATE_DELIMITOR); while (defDecoder.hasMoreTokens()) { String code = defDecoder.nextToken(); if (code.length() == 0) { break; } int type = code.charAt(0) - '0'; String name = code.substring(1); JComponent field; switch (type) { case TEXT_FIELD: field = new JTextField(stateDecoder.nextToken("")); ((JTextComponent) field).getDocument() .addDocumentListener(changeListener); ((JTextField) field).addActionListener(frame); m_fields.add(field); break; case TEXT_AREA: field = new JTextArea( stateDecoder.nextToken("").replace(LINE_DELIMINATOR, '\n')); ((JTextComponent) field).getDocument() .addDocumentListener(changeListener); m_fields.add(field); field = new ScrollPane(field); break; case TICKS: case TICKS_VAL: case TICKS_MAX: case TICKS_VALMAX: field = new TickPanel(stateDecoder.nextToken(""), type); ((TickPanel) field).addDocumentListener(changeListener); ((TickPanel) field).addActionListener(frame); if (backgroundColor != null) field.setBackground(backgroundColor); m_fields.add(field); break; case SPINNER: JSpinner spinner = new JSpinner(); JTextField textField = ((JSpinner.DefaultEditor) spinner.getEditor()).getTextField(); textField.setText(stateDecoder.nextToken("")); textField.getDocument().addDocumentListener(changeListener); m_fields.add(textField); field = spinner; break; case LABEL_ONLY: default : stateDecoder.nextToken(""); field = null; m_fields.add(field); break; } c.gridwidth = type == TEXT_AREA || type == LABEL_ONLY ? 2 : 1; if (name != null && !name.equals("")) { c.gridx = 0; c.weighty = 0.0; c.weightx = c.gridwidth == 2 ? 1.0 : 0.0; pane.add(new JLabel(getTranslation(name)), c); if (c.gridwidth == 2) { ++c.gridy; } } if (field != null) { c.weightx = 1.0; c.weighty = type == TEXT_AREA ? 1.0 : 0.0; c.gridx = type == TEXT_AREA ? 0 : 1; pane.add(field, c); ++c.gridy; } } if (backgroundColor != null) { pane.setBackground(backgroundColor); } if (commitStyle == COMMIT_ON_APPLY) { // setup Close button JButton closeButton = new JButton("Close"); closeButton.setMnemonic(java.awt.event.KeyEvent.VK_C); // respond to Alt+C // key event cannot be resolved closeButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { updateStateFromFields(); frame.setVisible(false); } }); c.gridwidth = 1; c.weighty = 0.0; c.anchor = GridBagConstraints.SOUTHEAST; c.gridwidth = 2; // use the whole row c.gridx = 0; c.weightx = 0.0; JPanel buttonRow = new JPanel(); buttonRow.add(applyButton); buttonRow.add(closeButton); if (backgroundColor != null) { applyButton.setBackground(backgroundColor); closeButton.setBackground(backgroundColor); buttonRow.setBackground(backgroundColor); } pane.add(buttonRow, c); } // move window Point p = GameModule.getGameModule().getFrame().getLocation(); if (getMap() != null) { p = getMap().getView().getLocationOnScreen(); Point p2 = getMap().componentCoordinates(getPosition()); p.translate(p2.x, p2.y); } frame.setLocation(p.x, p.y); // watch for window closing - save state frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent evt) { updateStateFromFields(); } }); frame.pack(); } // Name window and make it visible frame.setTitle(getLocalizedName()); oldState = Decorator.getOutermost(this).getState(); frame.setVisible(true); return null; } else { return null; } } public Object getProperty(Object key) { Object value = properties.get(key); if (value == null) { value = super.getProperty(key); } return value; } public String getDescription() { return "Property Sheet"; } public VASSAL.build.module.documentation.HelpFile getHelpFile() { return HelpFile.getReferenceManualPage("PropertySheet.htm"); } public PieceEditor getEditor() { return new Ed(this); } /** A generic panel for editing unit traits. Not directly related to "PropertySheets" **/ static class PropertyPanel extends JPanel implements FocusListener { private static final long serialVersionUID = 1L; GridBagConstraints c = new GridBagConstraints(); public PropertyPanel() { super(new GridBagLayout()); c.insets = new Insets(0, 4, 0, 4); //c.ipadx = 5; c.anchor = GridBagConstraints.WEST; } public JTextField addKeystrokeCtrl(char value) { ++c.gridy; c.gridx = 0; c.weightx = 0.0; c.fill = GridBagConstraints.NONE; add(new JLabel("Keystroke:"), c); ++c.gridx; JTextField field = new JTextField(Character.toString(value)); Dimension minSize = field.getMinimumSize(); minSize.width = 30; field.setMinimumSize(minSize); field.setPreferredSize(minSize); add(field, c); field.setSize(minSize); return field; } public JTextField addStringCtrl(String name, String value) { ++c.gridy; c.gridx = 0; c.weightx = 0.0; c.fill = GridBagConstraints.HORIZONTAL; add(new JLabel(name), c); c.weightx = 1.0; JTextField field = new JTextField(value); ++c.gridx; add(field, c); return field; } public JButton addColorCtrl(String name, Color value) { ++c.gridy; c.gridx = 0; c.weightx = 0.0; c.fill = GridBagConstraints.NONE; add(new JLabel(name), c); c.weightx = 0.0; JButton button = new JButton("Default"); if (value != null) { button.setBackground(value); button.setText("sample"); } button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { JButton button = (JButton) event.getSource(); Color value = button.getBackground(); Color newColor = JColorChooser.showDialog(PropertyPanel.this, "Choose background color or CANCEL to use default color scheme", value); if (newColor != null) { button.setBackground(newColor); button.setText("sample"); } else { button.setBackground(PropertyPanel.this.getBackground()); button.setText("Default"); } } }); ++c.gridx; add(button, c); return button; } public JComboBox addComboBox(String name, String[] values, int initialRow) { JComboBox comboBox = new JComboBox(values); comboBox.setEditable(false); comboBox.setSelectedIndex(initialRow); addCtrl(name, comboBox); return comboBox; } public void addCtrl(String name, JComponent ctrl) { ++c.gridy; c.gridx = 0; c.weightx = 0.0; c.fill = GridBagConstraints.NONE; add(new JLabel(name), c); c.weightx = 0.0; ++c.gridx; add(ctrl, c); } DefaultTableModel tableModel; String[] defaultValues; public class SmartTable extends JTable { private static final long serialVersionUID = 1L; SmartTable(TableModel m) { super(m); setSurrendersFocusOnKeystroke(true); } //Prepares the editor by querying the data model for the value and selection state of the cell at row, column. } public Component prepareEditor(TableCellEditor editor, int row, int column) { if (row == getRowCount() - 1) { ((DefaultTableModel) getModel()).addRow(Ed.DEFAULT_ROW); } Component component = super.prepareEditor(editor, row, column); if (component instanceof JTextComponent) { ((JTextComponent) component).grabFocus(); ((JTextComponent) component).selectAll(); } return component; } } public JTable addTableCtrl(String name, DefaultTableModel theTableModel, String[] theDefaultValues) { tableModel = theTableModel; this.defaultValues = theDefaultValues; ++c.gridy; c.gridx = 0; c.weighty = 0.0; c.weightx = 1.0; c.gridwidth = 2; c.fill = GridBagConstraints.HORIZONTAL; add(new JLabel(name), c); ++c.gridy; c.weighty = 1.0; c.fill = GridBagConstraints.BOTH; final SmartTable table = new SmartTable(tableModel); add(new ScrollPane(table), c); c.gridwidth = 1; ++c.gridy; c.fill = GridBagConstraints.NONE; c.anchor = GridBagConstraints.EAST; c.gridwidth = 2; c.weighty = 0.0; c.weightx = 1.0; JPanel buttonPanel = new JPanel(); // add button JButton addButton = new JButton("Insert Row"); buttonPanel.add(addButton); addButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (table.isEditing()) { table.getCellEditor().stopCellEditing(); } ListSelectionModel selection = table.getSelectionModel(); int iSelection; if (selection.isSelectionEmpty()) { tableModel.addRow(defaultValues); iSelection = tableModel.getRowCount() - 1; } else { iSelection = selection.getMaxSelectionIndex(); tableModel.insertRow(iSelection, defaultValues); } tableModel.fireTableDataChanged(); // BING BING BING selection.setSelectionInterval(iSelection, iSelection); table.grabFocus(); table.editCellAt(iSelection, 0); Component comp = table.getCellEditor().getTableCellEditorComponent(table, null, true, iSelection, 0); if (comp instanceof JComponent) { ((JComponent) comp).grabFocus(); } } }); // delete button final JButton deleteButton = new JButton("Delete Row"); deleteButton.setEnabled(false); buttonPanel.add(deleteButton); deleteButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (table.isEditing()) { table.getCellEditor().stopCellEditing(); } ListSelectionModel selection = table.getSelectionModel(); for (int i = selection.getMaxSelectionIndex(); i >= selection.getMinSelectionIndex(); --i) { if (selection.isSelectedIndex(i)) { tableModel.removeRow(i); } } tableModel.fireTableDataChanged(); // BING BING BING } }); // Ask to be notified of selection changes. table.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent event) { //Ignore extra messages. if (!event.getValueIsAdjusting()) { ListSelectionModel lsm = (ListSelectionModel) event.getSource(); deleteButton.setEnabled(!lsm.isSelectionEmpty()); } } }); add(buttonPanel, c); c.anchor = GridBagConstraints.WEST; c.weightx = 0.0; return table; } public void focusGained(FocusEvent event) { } // make sure we save user's changes public void focusLost(FocusEvent event) { if (event.getComponent() instanceof JTable) { JTable table = (JTable) event.getComponent(); if (table.isEditing()) { table.getCellEditor().stopCellEditing(); } } } } public PieceI18nData getI18nData() { final ArrayList<String> items = new ArrayList<String>(); final SequenceEncoder.Decoder defDecoder = new SequenceEncoder.Decoder(m_definition, DEF_DELIMITOR); while (defDecoder.hasMoreTokens()) { final String item = defDecoder.nextToken(); items.add(item.length() == 0 ? "" : item.substring(1)); } final String[] menuNames = new String[items.size()+1]; final String[] descriptions = new String[items.size()+1]; menuNames[0] = menuName; descriptions[0] = "Property Sheet command"; int j = 1; for (String s : items) { menuNames[j] = s; descriptions[j] = "Property Sheet item " + j; j++; } return getI18nData(menuNames, descriptions); } private static class Ed implements PieceEditor { private PropertyPanel m_panel; private JTextField menuNameCtrl; private JTextField keystrokeCtrl; private JButton colorCtrl; private JTable propertyTable; private JComboBox commitCtrl; static final String[] COLUMN_NAMES = {"Name", "Type"}; static final String[] DEFAULT_ROW = {"*new property*", "Text"}; public Ed(PropertySheet propertySheet) { m_panel = new PropertyPanel(); menuNameCtrl = m_panel.addStringCtrl("Menu Text:", propertySheet.menuName); keystrokeCtrl = m_panel.addKeystrokeCtrl(propertySheet.launchKey); commitCtrl = m_panel.addComboBox("Commit changes on:", COMMIT_VALUES, propertySheet.commitStyle); colorCtrl = m_panel.addColorCtrl("Background Color:", propertySheet.backgroundColor); DefaultTableModel dataModel = new DefaultTableModel(getTableData(propertySheet.m_definition), COLUMN_NAMES); AddCreateRow(dataModel); propertyTable = m_panel.addTableCtrl("Properties:", dataModel, DEFAULT_ROW); DefaultCellEditor typePicklist = new DefaultCellEditor(new JComboBox(TYPE_VALUES)); propertyTable.getColumnModel().getColumn(1).setCellEditor(typePicklist); } protected void AddCreateRow(DefaultTableModel data) { data.addRow(DEFAULT_ROW); } protected String[][] getTableData(String definition) { SequenceEncoder.Decoder decoder = new SequenceEncoder.Decoder(definition, DEF_DELIMITOR); int numRows = !definition.equals("") && decoder.hasMoreTokens() ? 1 : 0; for (int iDef = -1; (iDef = definition.indexOf(DEF_DELIMITOR, iDef + 1)) >= 0;) { ++numRows; } String[][] rows = new String[numRows][2]; for (int iRow = 0; decoder.hasMoreTokens() && iRow < numRows; ++iRow) { String token = decoder.nextToken(); rows[iRow][0] = token.substring(1); rows[iRow][1] = TYPE_VALUES[token.charAt(0) - '0']; } return rows; } public java.awt.Component getControls() { return m_panel; } /** returns the type-definition in the format: definition, name, keystroke, commit, red, green, blue */ public String getType() { if (propertyTable.isEditing()) { propertyTable.getCellEditor().stopCellEditing(); } SequenceEncoder defEncoder = new SequenceEncoder(DEF_DELIMITOR); // StringBuilder definition = new StringBuilder(); // int numRows = propertyTable.getRowCount(); for (int iRow = 0; iRow < propertyTable.getRowCount(); ++iRow) { String typeString = (String) propertyTable.getValueAt(iRow, 1); for (int iType = 0; iType < TYPE_VALUES.length; ++iType) { if (typeString.matches(TYPE_VALUES[iType]) && !DEFAULT_ROW[0].equals(propertyTable.getValueAt(iRow, 0))) { defEncoder.append(iType + (String) propertyTable.getValueAt(iRow, 0)); break; } } } SequenceEncoder typeEncoder = new SequenceEncoder(TYPE_DELIMITOR); // calc color strings String red, green, blue; if (colorCtrl.getText().equals("Default")) { red = ""; green = ""; blue = ""; } else { red = Integer.toString(colorCtrl.getBackground().getRed()); green = Integer.toString(colorCtrl.getBackground().getGreen()); blue = Integer.toString(colorCtrl.getBackground().getBlue()); } String definitionString = defEncoder.getValue(); typeEncoder.append(definitionString == null ? "" : definitionString). append(menuNameCtrl.getText()). append(keystrokeCtrl.getText()). append(Integer.toString(commitCtrl.getSelectedIndex())). append(red).append(green).append(blue); return ID + typeEncoder.getValue(); } /** returns a default value-string for the given definition */ public String getState() { final StringBuilder buf = new StringBuilder(); for (int i = 0; i < propertyTable.getRowCount(); ++i) { buf.append(STATE_DELIMITOR); } return buf.toString(); } } class TickPanel extends JPanel implements ActionListener, FocusListener, DocumentListener { private static final long serialVersionUID = 1L; private int numTicks; private int maxTicks; private int panelType; private JTextField valField; private JTextField maxField; private TickLabel ticks; private List<ActionListener> actionListeners = new ArrayList<ActionListener>(); private List<DocumentListener> documentListeners = new ArrayList<DocumentListener>(); public TickPanel(String value, int type) { super(new GridBagLayout()); set(value); panelType = type; GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.BOTH; c.ipadx = 1; c.weightx = 0.0; c.gridx = 0; c.gridy = 0; Dimension minSize; if (panelType == TICKS_VAL || panelType == TICKS_VALMAX) { valField = new JTextField(Integer.toString(numTicks)); minSize = valField.getMinimumSize(); minSize.width = 24; valField.setMinimumSize(minSize); valField.setPreferredSize(minSize); valField.addActionListener(this); valField.addFocusListener(this); add(valField, c); ++c.gridx; } if (panelType == TICKS_MAX || panelType == TICKS_VALMAX) { maxField = new JTextField(Integer.toString(maxTicks)); minSize = maxField.getMinimumSize(); minSize.width = 24; maxField.setMinimumSize(minSize); maxField.setPreferredSize(minSize); maxField.addActionListener(this); maxField.addFocusListener(this); if (panelType == TICKS_VALMAX) { add(new JLabel("/"), c); ++c.gridx; } add(maxField, c); ++c.gridx; } ticks = new TickLabel(numTicks, maxTicks, panelType); ticks.addActionListener(this); c.weightx = 1.0; add(ticks, c); doLayout(); } public void updateValue(String value) { set(value); updateFields(); } private void set(String value) { set(atoi(value), atoiRight(value)); } private boolean set(int num, int max) { boolean changed = false; if (numTicks == 0 && maxTicks == 0 && num == 0 && max > 0) { // num = max; // This causes a bug in which ticks set to zero go to max after save/reload of a game changed = true; } if (numTicks == 0 && maxTicks == 0 && max == 0 && num > 0) { max = num; changed = true; } numTicks = Math.min(max, num); maxTicks = max; return changed; } public String getValue() { commitTextFields(); return Integer.toString(numTicks) + VALUE_DELIMINATOR + maxTicks; } private void commitTextFields() { if (valField != null || maxField != null) { if (set(valField != null ? atoi(valField.getText()) : numTicks, maxField != null ? atoi(maxField.getText()) : maxTicks)) { updateFields(); } } } private void updateFields() { if (valField != null) { valField.setText(Integer.toString(numTicks)); } if (maxField != null) { maxField.setText(Integer.toString(maxTicks)); } ticks.set(numTicks, maxTicks); } private boolean areFieldValuesValid() { int max = maxField == null ? maxTicks : atoi(maxField.getText()); int val = valField == null ? numTicks : atoi(valField.getText()); return val < max && val >= 0; } // field changed public void actionPerformed(ActionEvent event) { if (event.getSource() == maxField || event.getSource() == valField) { commitTextFields(); ticks.set(numTicks, maxTicks); fireActionEvent(); } else if (event.getSource() == ticks) { commitTextFields(); numTicks = ticks.getNumTicks(); if (maxField == null) { maxTicks = ticks.getMaxTicks(); } updateFields(); fireDocumentEvent(); } } public void addActionListener(ActionListener listener) { actionListeners.add(listener); } public void fireActionEvent() { for (ActionListener l : actionListeners) { l.actionPerformed(new ActionEvent(this, 0, null)); } } void addDocumentListener(DocumentListener listener) { if (valField != null) valField.getDocument().addDocumentListener(this); if (maxField != null) maxField.getDocument().addDocumentListener(this); documentListeners.add(listener); } public void fireDocumentEvent() { for (DocumentListener l : documentListeners) { l.changedUpdate(null); } } // FocusListener Interface public void focusLost(FocusEvent event) { commitTextFields(); ticks.set(numTicks, maxTicks); } public void focusGained(FocusEvent event) { } public void changedUpdate(DocumentEvent event) { // do not propagate events unless min/max is valid. We don't want to trigger both // a state update. A state update might trigger a fix-min/max operation, which would if (areFieldValuesValid()) { fireDocumentEvent(); } } public void insertUpdate(DocumentEvent event) { changedUpdate(event); } public void removeUpdate(DocumentEvent event) { changedUpdate(event); } } class TickLabel extends JLabel implements MouseListener { private static final long serialVersionUID = 1L; private int numTicks = 0; private int maxTicks = 0; protected int panelType; private List<ActionListener> actionListeners = new ArrayList<ActionListener>(); public int getNumTicks() { return numTicks; } public int getMaxTicks() { return maxTicks; } public void addActionListener(ActionListener listener) { actionListeners.add(listener); } public TickLabel(int numTicks, int maxTicks, int panelType) { super(" "); //Debug.trace("TickLabel( " + maxTicks + ", " + numTicks + " )"); set(numTicks, maxTicks); this.panelType = panelType; addMouseListener(this); } protected int topMargin = 2; protected int leftMargin = 2; protected int numRows; protected int numCols; protected int dx = 1; public void paint(Graphics g) { //Debug.trace("TickLabcmdel.paint(" + numTicks + "/" + maxTicks + ")"); //Debug.trace(" width=" + getWidth() + " height=" + getHeight()); if (maxTicks > 0) { // prefered width is 10 // min width before resize is 6 int displayWidth = getWidth() - 2; dx = Math.min(displayWidth / maxTicks, 10); // if dx < 2, we have a problem numRows = dx < 3 ? 3 : dx < 6 ? 2 : 1; dx = Math.min(displayWidth * numRows / maxTicks, Math.min(getHeight() / numRows, 10)); numCols = (maxTicks + numRows - 1) / numRows; int dy = dx; topMargin = (getHeight() - dy * numRows + 2) / 2; int tick = 0; int row, col; if (dx > 4) { for (; tick < maxTicks; ++tick) { row = tick / numCols; col = tick % numCols; g.setColor(Color.BLACK); g.drawRect(leftMargin + col * dx, topMargin + row * dy, dx - 3, dy - 3); g.setColor(tick < numTicks ? Color.BLACK : Color.WHITE); g.fillRect(leftMargin + 1 + col * dx, topMargin + 1 + row * dy, dx - 4, dy - 4); } } else { g.setColor(Color.GRAY); g.fillRect(0, topMargin - 2, numCols * dx + leftMargin * 2, numRows * dy + 4); for (; tick < maxTicks; ++tick) { row = tick / numCols; col = tick % numCols; g.setColor(tick < numTicks ? Color.BLACK : Color.WHITE); g.fillRect(leftMargin + col * dx, topMargin + row * dy, dx - 1, dy - 1); } } } } public void mouseClicked(MouseEvent event) { if ((event.isMetaDown() || event.isShiftDown()) && panelType != TICKS_VALMAX) { new EditTickLabelValueDialog(this); return; } int col = Math.min((event.getX() - leftMargin + 1) / dx, numCols - 1); int row = Math.min((event.getY() - topMargin + 1) / dx, numRows - 1); int num = row * numCols + col + 1; // Checkbox behavior; toggle the box clicked on // numTicks = num > numTicks ? num : num - 1; // Slider behavior; set the box clicked on and all to left and clear all boxes to right, // UNLESS user clicked on last set box (which would do nothing), in this case, toggle the // box clicked on. This is the only way the user can clear the first box. numTicks = (num == numTicks) ? num - 1 : num; fireActionEvent(); repaint(); } public void fireActionEvent() { for (ActionListener l : actionListeners) { l.actionPerformed(new ActionEvent(this, 0, null)); } } public void set(int newNumTicks, int newMaxTicks) { //Debug.trace("TickLabel.set( " + newNumTicks + "," + newMaxTicks + " ) was " + numTicks + "/" + maxTicks); numTicks = newNumTicks; maxTicks = newMaxTicks; String tip = numTicks + "/" + maxTicks; if (panelType != TICKS_VALMAX) { tip += " (right-click to edit)"; } setToolTipText(tip); repaint(); } public void mouseEntered(MouseEvent event) { } public void mouseExited(MouseEvent event) { } public void mousePressed(MouseEvent event) { } public void mouseReleased(MouseEvent event) { } public class EditTickLabelValueDialog extends JPanel implements ActionListener, DocumentListener, FocusListener { private static final long serialVersionUID = 1L; TickLabel theTickLabel; JLayeredPane editorParent; JTextField valueField; public EditTickLabelValueDialog(TickLabel owner) { super(new BorderLayout()); theTickLabel = owner; // Find containing dialog Container theDialog = theTickLabel.getParent(); while (!(theDialog instanceof JDialog) && theDialog != null) { theDialog = theDialog.getParent(); } if (theDialog != null) { editorParent = ((JDialog) theDialog).getLayeredPane(); Rectangle newBounds = SwingUtilities.convertRectangle(theTickLabel.getParent(), theTickLabel.getBounds(), editorParent); setBounds(newBounds); JButton okButton = new JButton("Ok"); switch (panelType) { case TICKS_VAL: valueField = new JTextField(Integer.toString(owner.getMaxTicks())); valueField.setToolTipText("max value"); break; case TICKS_MAX: valueField = new JTextField(Integer.toString(owner.getNumTicks())); valueField.setToolTipText("current value"); break; case TICKS: default: valueField = new JTextField(owner.numTicks + "/" + owner.maxTicks); valueField.setToolTipText("current value / max value"); break; } valueField.addActionListener(this); valueField.addFocusListener(this); valueField.getDocument().addDocumentListener(this); add(valueField, BorderLayout.CENTER); okButton.addActionListener(this); add(okButton, BorderLayout.EAST); editorParent.add(this, JLayeredPane.MODAL_LAYER); setVisible(true); valueField.grabFocus(); } } public void storeValues() { String value = valueField.getText(); switch (panelType) { case TICKS_VAL: theTickLabel.set(theTickLabel.getNumTicks(), atoi(value)); break; case TICKS_MAX: theTickLabel.set(atoi(value), theTickLabel.getMaxTicks()); break; case TICKS: default: theTickLabel.set(atoi(value), atoiRight(value)); break; } theTickLabel.fireActionEvent(); } public void actionPerformed(ActionEvent event) { storeValues(); editorParent.remove(this); } public void changedUpdate(DocumentEvent event) { theTickLabel.fireActionEvent(); } public void insertUpdate(DocumentEvent event) { theTickLabel.fireActionEvent(); } public void removeUpdate(DocumentEvent event) { theTickLabel.fireActionEvent(); } public void focusGained(FocusEvent event) { } public void focusLost(FocusEvent event) { storeValues(); } } } }
package bitronix.tm.mock; import bitronix.tm.TransactionManagerServices; import bitronix.tm.mock.resource.jms.MockXAConnectionFactory; import bitronix.tm.recovery.RecoveryException; import bitronix.tm.resource.common.XAPool; import bitronix.tm.resource.jms.PoolingConnectionFactory; import junit.framework.TestCase; import javax.jms.Connection; import javax.jms.JMSException; import javax.jms.Session; import javax.jms.Queue; import javax.jms.MessageProducer; import java.lang.reflect.Field; /** * * @author lorban */ public class JmsPoolTest extends TestCase { private PoolingConnectionFactory pcf; protected void setUp() throws Exception { TransactionManagerServices.getConfiguration().setJournal("null").setGracefulShutdownInterval(0); TransactionManagerServices.getTransactionManager(); MockXAConnectionFactory.setStaticCloseXAConnectionException(null); MockXAConnectionFactory.setStaticCreateXAConnectionException(null); pcf = new PoolingConnectionFactory(); pcf.setMinPoolSize(1); pcf.setMaxPoolSize(2); pcf.setMaxIdleTime(1); pcf.setClassName(MockXAConnectionFactory.class.getName()); pcf.setUniqueName("pcf"); pcf.setAllowLocalTransactions(true); pcf.setAcquisitionTimeout(1); pcf.init(); } protected void tearDown() throws Exception { pcf.close(); TransactionManagerServices.getTransactionManager().shutdown(); } public void testInitFailure() throws Exception { pcf.close(); pcf = new PoolingConnectionFactory(); pcf.setMinPoolSize(0); pcf.setMaxPoolSize(2); pcf.setMaxIdleTime(1); pcf.setClassName(MockXAConnectionFactory.class.getName()); pcf.setUniqueName("pcf"); pcf.setAllowLocalTransactions(true); pcf.setAcquisitionTimeout(1); TransactionManagerServices.getTransactionManager().begin(); MockXAConnectionFactory.setStaticCreateXAConnectionException(new JMSException("not yet started")); try { pcf.init(); } catch (Exception e) { } MockXAConnectionFactory.setStaticCreateXAConnectionException(null); pcf.init(); pcf.createConnection().createSession(true, 0).createProducer(null).send(null); TransactionManagerServices.getTransactionManager().commit(); } public void testReEnteringRecovery() throws Exception { pcf.startRecovery(); try { pcf.startRecovery(); fail("excpected RecoveryException"); } catch (RecoveryException ex) { assertEquals("recovery already in progress on a PoolingConnectionFactory with an XAPool of resource pcf with 1 connection(s) (0 still available)", ex.getMessage()); } // make sure startRecovery() can be called again once endRecovery() has been called pcf.endRecovery(); pcf.startRecovery(); pcf.endRecovery(); } public void testPoolNotStartingTransactionManager() throws Exception { // make sure TM is not running TransactionManagerServices.getTransactionManager().shutdown(); PoolingConnectionFactory pcf = new PoolingConnectionFactory(); pcf.setMinPoolSize(1); pcf.setMaxPoolSize(2); pcf.setMaxIdleTime(1); pcf.setClassName(MockXAConnectionFactory.class.getName()); pcf.setUniqueName("pcf2"); pcf.setAllowLocalTransactions(true); pcf.setAcquisitionTimeout(1); pcf.init(); assertFalse(TransactionManagerServices.isTransactionManagerRunning()); Connection c = pcf.createConnection(); Session s = c.createSession(false, 0); Queue q = s.createQueue("q"); MessageProducer mp = s.createProducer(q); mp.send(s.createTextMessage("test123")); mp.close(); s.close(); c.close(); assertFalse(TransactionManagerServices.isTransactionManagerRunning()); pcf.close(); assertFalse(TransactionManagerServices.isTransactionManagerRunning()); } public void testPoolShrink() throws Exception { Field poolField = pcf.getClass().getDeclaredField("pool"); poolField.setAccessible(true); XAPool pool = (XAPool) poolField.get(pcf); assertEquals(1, pool.inPoolSize()); assertEquals(1, pool.totalPoolSize()); Connection c1 = pcf.createConnection(); assertEquals(0, pool.inPoolSize()); assertEquals(1, pool.totalPoolSize()); Connection c2 = pcf.createConnection(); assertEquals(0, pool.inPoolSize()); assertEquals(2, pool.totalPoolSize()); c1.close(); c2.close(); Thread.sleep(1200); // leave enough time for the ide connections to expire TransactionManagerServices.getTaskScheduler().interrupt(); // wake up the task scheduler Thread.sleep(1200); // leave enough time for the scheduled shrinking task to do its work assertEquals(1, pool.inPoolSize()); assertEquals(1, pool.totalPoolSize()); } public void testPoolShrinkErrorHandling() throws Exception { Field poolField = pcf.getClass().getDeclaredField("pool"); poolField.setAccessible(true); XAPool pool = (XAPool) poolField.get(pcf); pcf.setMinPoolSize(0); pcf.reset(); pcf.setMinPoolSize(1); MockXAConnectionFactory.setStaticCloseXAConnectionException(new JMSException("close fails because connection factory broken")); pcf.reset(); // the pool is now loaded with one connection which will throw an exception when closed Thread.sleep(1100); // leave enough time for the ide connections to expire TransactionManagerServices.getTaskScheduler().interrupt(); // wake up the task scheduler Thread.sleep(100); // leave enough time for the scheduled shrinking task to do its work assertEquals(1, pool.inPoolSize()); MockXAConnectionFactory.setStaticCreateXAConnectionException(new JMSException("createXAConnection fails because connection factory broken")); Thread.sleep(1100); // leave enough time for the ide connections to expire TransactionManagerServices.getTaskScheduler().interrupt(); // wake up the task scheduler Thread.sleep(100); // leave enough time for the scheduled shrinking task to do its work assertEquals(0, pool.inPoolSize()); MockXAConnectionFactory.setStaticCreateXAConnectionException(null); Thread.sleep(1100); // leave enough time for the ide connections to expire TransactionManagerServices.getTaskScheduler().interrupt(); // wake up the task scheduler Thread.sleep(100); // leave enough time for the scheduled shrinking task to do its work assertEquals(1, pool.inPoolSize()); } public void testPoolReset() throws Exception { Field poolField = pcf.getClass().getDeclaredField("pool"); poolField.setAccessible(true); XAPool pool = (XAPool) poolField.get(pcf); assertEquals(1, pool.inPoolSize()); assertEquals(1, pool.totalPoolSize()); Connection c1 = pcf.createConnection(); assertEquals(0, pool.inPoolSize()); assertEquals(1, pool.totalPoolSize()); Connection c2 = pcf.createConnection(); assertEquals(0, pool.inPoolSize()); assertEquals(2, pool.totalPoolSize()); c1.close(); c2.close(); pcf.reset(); assertEquals(1, pool.inPoolSize()); assertEquals(1, pool.totalPoolSize()); } public void testPoolResetErrorHandling() throws Exception { Field poolField = pcf.getClass().getDeclaredField("pool"); poolField.setAccessible(true); XAPool pool = (XAPool) poolField.get(pcf); pcf.setMinPoolSize(0); pcf.reset(); pcf.setMinPoolSize(1); MockXAConnectionFactory.setStaticCloseXAConnectionException(new JMSException("close fails because connection factory broken")); pcf.reset(); // the pool is now loaded with one connection which will throw an exception when closed pcf.reset(); try { MockXAConnectionFactory.setStaticCreateXAConnectionException(new JMSException("createXAConnection fails because connection factory broken")); pcf.reset(); fail("expected JMSException"); } catch (JMSException ex) { assertEquals("createXAConnection fails because connection factory broken", ex.getMessage()); assertEquals(0, pool.inPoolSize()); } MockXAConnectionFactory.setStaticCreateXAConnectionException(null); pcf.reset(); assertEquals(1, pool.inPoolSize()); } }
package it.polimi.ingsw.client.cli; import it.polimi.ingsw.client.GameController; import it.polimi.ingsw.client.View; import it.polimi.ingsw.exception.CommandNotValidException; import it.polimi.ingsw.game.GameMap; import it.polimi.ingsw.game.card.object.ObjectCardBuilder; import it.polimi.ingsw.game.common.GameInfo; import it.polimi.ingsw.game.common.PlayerInfo; import it.polimi.ingsw.game.common.ViewCommand; import java.awt.Point; import java.util.List; import java.util.Set; /** CLI View * @author Alain Carlucci (alain.carlucci@mail.polimi.it) * @author Michele Albanese (michele.albanese@mail.polimi.it) * @since May 10, 2015 */ public class CLIView extends View { /** Game map */ private GameMap mMap; /** Controller */ private final GameController mController; /** Game info container */ private GameInfo mContainer; /** The constructor * @param c Game Controller */ public CLIView(GameController c) { super(c); mController = c; } /** Print a fancy border */ private static void printBorder() { IO.write("*******************************************************************************"); } /** Draw the starting banner */ private static void banner() { for(int i=0;i<2;i++) printBorder(); IO.write("*** ______ _____ _____ _____ ______ ***"); IO.write("*** | ____| / ____| / ____| /\\ | __ \\ | ____| ***"); IO.write("*** | |__ | (___ | | / \\ | |__) | | |__ ***"); IO.write("*** | __| \\___ \\ | | / /\\ \\ | ___/ | __| ***"); IO.write("*** | |____ ____) | | |____ / ____ \\ | | | |____ ***"); IO.write("*** |______| |_____/ \\_____| /_/ \\_\\ |_| |______| ***"); IO.write("*** ___ ___ ___ __ __ _____ _ _ ___ _ _ ___ ___ _ _ ___ ***"); IO.write("*** | __| _ \\/ _ \\| \\/ | |_ _| || | __| /_\\ | | |_ _| __| \\| / __| ***"); IO.write("*** | _|| / (_) | |\\/| | | | | __ | _| / _ \\| |__ | || _|| .` \\__ \\ ***"); IO.write("*** |_| |_|_\\\\___/|_| |_| |_| |_||_|___| /_/ \\_\\____|___|___|_|\\_|___/ ***"); IO.write("*** ___ _ _ ___ _ _ _____ ___ ___ ___ ___ _ ___ ___ ***"); IO.write("*** |_ _|| \\| | / _ \\ | | | ||_ _|| __|| _ \\ / __|| _ \\ /_\\ / __|| __| ***"); IO.write("*** | | | .` | | (_) || |_| | | | | _| | / \\__ \\| _ IO.write("*** |___||_|\\_| \\___/ \\___/ |_| |___||_|_\\ |___/|_| /_/ \\_\\\\___||___| ***"); IO.write("*** ***"); IO.write("*** Command line client by Michele Albanese & Alain Carlucci ***"); for(int i=0;i<2;i++) printBorder(); IO.write(""); } /** Invoked on startup * * @see it.polimi.ingsw.client.View#startup() */ @Override public void startup() { CLIView.banner(); } /** Method not used * * @see it.polimi.ingsw.client.View#run() */ @Override public void run() { /** unused */ } /** Ask for a connection type * * @see it.polimi.ingsw.client.View#askConnectionType(java.lang.String[]) */ @Override public int askConnectionType(String[] params) { IO.write("Which connection do you want to use?"); return IO.askInAList(params, false); } /** Ask for a username * * @see it.polimi.ingsw.client.View#askUsername(java.lang.String) */ @Override public String askUsername(String message) { String name; IO.write(message); name = IO.readString().trim(); return name; } /** Ask for a map * * @see it.polimi.ingsw.client.View#askMap(java.lang.String[]) */ @Override public Integer askMap(String[] mapList) { IO.write("Choose a map:"); return IO.askInAList(mapList, false); } /** Ask for a host * * @see it.polimi.ingsw.client.View#askHost() */ @Override public String askHost() { IO.write("Type the hostname"); return IO.readString(); } /** Ask for a view * * @see it.polimi.ingsw.client.View#askView(java.lang.String[]) */ @Override public Integer askView( String[] viewList ) { IO.write("Which view do you want to use?"); return IO.askInAList(viewList, false); } /** Display an error * * @see it.polimi.ingsw.client.View#showError(java.lang.String) */ @Override public void showError(String string) { IO.write("ERROR: " + string); } /** Update Login time on startup * * @see it.polimi.ingsw.client.View#updateLoginTime(int) */ @Override public void updateLoginTime(int i) { IO.write("Remaining time: " + i); } /** Update login statistics about players on startup * * @see it.polimi.ingsw.client.View#updateLoginStat(int) */ @Override public void updateLoginStat(int i) { IO.write("Players online: " + i); } /** Display map after login phase * * @see it.polimi.ingsw.client.View#switchToMainScreen(it.polimi.ingsw.game.common.GameInfo) */ @Override public void switchToMainScreen(GameInfo container) { mContainer = container; mMap = container.getMap(); CLIMapRenderer.renderMap(mMap, null, null); IO.write("Game is started! Good luck!"); IO.write("Your role is: " + (container.isHuman()?"HUMAN":"ALIEN")); IO.write(String.format("%d players in game:", container.getPlayersList().length)); for(PlayerInfo e : container.getPlayersList()) IO.write("-> " + e.getUsername()); } /** Handle a map view * * @param c ViewCommand * @param canGoBack True if user can go back * @return True if the command is handled successfully */ private boolean handleEnableMapView(ViewCommand c, boolean canGoBack) { Point newPos = null; Point curPos = null; int maxMoves = 0; Set<Point> enabledCells = null; if(c.getArgs().length > 0) { if(c.getArgs()[0] instanceof Point) curPos = (Point) c.getArgs()[0]; if(c.getArgs().length == 2) maxMoves = (int) c.getArgs()[1]; } if(maxMoves != 0) enabledCells = mController.getMap().getCellsWithMaxDistance(curPos, maxMoves, mContainer.isHuman()); CLIMapRenderer.renderMap(mMap, curPos, enabledCells); IO.write("Choose a position on the map" + (canGoBack?" (or type - to go back)":"")); do { newPos = IO.askMapPos(canGoBack); /** up in the menu */ if(newPos == null) return false; if( (enabledCells == null && mMap.isWithinBounds(newPos)) || (enabledCells != null && enabledCells.contains(newPos))) break; IO.write("Invalid position"); } while(true); mController.onMapPositionChosen(newPos); return true; } /** Handle a ChooseObjectCard command * * @param c ViewCommand * @param canGoBack True if user can go back * @return True if the command is handled successfully */ private boolean handleChooseObjectCard(ViewCommand c, boolean canGoBack) { if(c.getArgs().length > 0 && c.getArgs() instanceof String[]) { String[] objs = (String[]) c.getArgs(); IO.write("Which card do you want to use?" + (canGoBack?" (or type - to go back)":"")); Integer choice = IO.askInAList(objs, canGoBack); if(choice == null) return false; mController.sendChosenObjectCard(choice); return true; } else showError(""+c.getArgs().length); return false; } /** Handle a DiscardObjectCard Command * * @param c ViewCommand * @param canGoBack True if user can go back * @return True if the command is handled successfully */ private boolean handleDiscardObjectCard(ViewCommand c, boolean canGoBack) { if(c.getArgs().length > 0 && c.getArgs() instanceof String[]) { String[] objs = (String[]) c.getArgs(); IO.write("Which card do you want to discard?" + (canGoBack?" (or type - to go back)":"")); Integer i = IO.askInAList(objs, canGoBack); if(i == null) return false; mController.sendDiscardObjectCard(i); return true; } else { showError(""+c.getArgs().length); } return false; } /** Handle a view command received from the game controller * * @see it.polimi.ingsw.client.View#handleCommand(java.util.List) */ @Override protected void handleCommand(List<ViewCommand> cmd) { ViewCommand c; boolean loopMenu = true; while(loopMenu) { if(cmd.size() > 1) { IO.write("What do you want to do now?"); int choice = IO.askInAList(cmd, false); c = cmd.get(choice); } else if(cmd.size() == 1) { loopMenu = false; c = cmd.get(0); } else return; switch(c.getOpcode()) { case CMD_ENABLEMAPVIEW: /** loopMenu == false if this is the only choice */ if(handleEnableMapView(c, loopMenu)) loopMenu = false; break; case CMD_CHOOSEOBJECTCARD: if(handleChooseObjectCard(c, loopMenu)) loopMenu = false; break; case CMD_ATTACK: mController.attack(); loopMenu = false; break; case CMD_DISCARDOBJECTCARD: if(handleDiscardObjectCard(c, loopMenu)) loopMenu = false; break; case CMD_DRAWDANGEROUSCARD: mController.drawDangerousCard(); loopMenu = false; break; case CMD_ENDTURN: mController.endTurn(); loopMenu = false; break; default: throw new CommandNotValidException("Command not valid!"); } } } /** Display an info on console * * @see it.polimi.ingsw.client.View#showInfo(java.lang.String, java.lang.String) */ @Override public void showInfo(String user, String message) { if(user != null) IO.write("["+ user + "] " + message); else IO.write("--INFO-- " + message); } /** Display noise info * * @see it.polimi.ingsw.client.View#showNoiseInSector(java.lang.String, java.awt.Point) */ @Override public void showNoiseInSector(String user, Point p) { showInfo(user, "NOISE IN SECTOR " + mMap.pointToString(p)); } /** Display message on my turn start * * @see it.polimi.ingsw.client.View#onMyTurn() */ @Override public void onMyTurn() { showInfo(null, "It's your turn!"); } /** Display message when someone else's turn starts * * @see it.polimi.ingsw.client.View#onOtherTurn(java.lang.String) */ @Override public void onOtherTurn(String username) { showInfo(null, "It's " + username + "'s turn!"); } /** Show ending banner * * @see it.polimi.ingsw.client.View#showEnding(java.util.List, java.util.List) */ @Override public void showEnding(List<Integer> winnerList, List<Integer> loserList) { IO.write("*******************"); IO.write("** THE END **"); IO.write("*******************\n"); if(winnerList.isEmpty()) IO.write("Nobody won this game."); else { IO.write("==== Winners ===="); for(Integer i : winnerList) { IO.write(" -> " + mContainer.getPlayersList()[i].getUsername()); } } if(loserList.isEmpty()) { IO.write("Nobody lost this game."); } else { IO.write("==== Losers ===="); for(Integer i : loserList) { IO.write(" -> " + mContainer.getPlayersList()[i].getUsername()); } } mController.stop(); System.exit(0); } /** Display your object cards * * @see it.polimi.ingsw.client.View#notifyObjectCardListChange(java.util.List) */ @Override public void notifyObjectCardListChange(List<Integer> listOfCards) { StringBuilder cards = new StringBuilder(); cards.append("Your object cards: "); for(int i = 0;i < listOfCards.size(); i++) { cards.append( i == 0 ? "[ " : "| " ); cards.append(ObjectCardBuilder.idToString(listOfCards.get(i))); cards.append(" "); } if(listOfCards.isEmpty()) cards.append("[ YOU HAVE NO OBJECT CARDS ]"); else cards.append("]"); IO.write(cards.toString()); } /** Unused * * @see it.polimi.ingsw.client.View#updatePlayerInfoDisplay(int) */ @Override public void updatePlayerInfoDisplay( int idPlayer ) { /** unused */ } /** Display info about spotlight action * * @see it.polimi.ingsw.client.View#handleSpotlightResult(java.awt.Point, java.awt.Point[]) */ @Override public void handleSpotlightResult(Point chosenPoint, Point[] playersFound) { boolean spottedAtLeastOne = false; IO.write("***** SPOTLIGHT RESULTS (" + mContainer.getMap().pointToString(chosenPoint) + ") *****\n"); for(int i = 0; i < playersFound.length; i++) { Point p = playersFound[i]; if(p != null) { IO.write(" -> " + mContainer.getPlayersList()[i].getUsername() + " spotted in sector " + mContainer.getMap().pointToString(p)); spottedAtLeastOne = true; } } if(!spottedAtLeastOne) IO.write("No players are in those sectors\n"); IO.write("\n************************************\n"); } /** Display info about attacks in a sector * * @see it.polimi.ingsw.client.View#handleAttack(java.lang.String, java.awt.Point) */ @Override public void handleAttack(String user, Point p) { showInfo(user, "Player just attacked in sector " + mContainer.getMap().pointToString(p)); } }
package org.intermine.web; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.ServletContext; import java.util.Properties; import java.util.Map; import java.util.HashMap; import java.util.Set; import java.util.HashSet; import java.util.List; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.TreeSet; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.apache.struts.action.ActionServlet; import org.apache.struts.action.PlugIn; import org.apache.struts.config.ModuleConfig; import org.intermine.util.TypeUtil; import org.intermine.metadata.Model; import org.intermine.metadata.ClassDescriptor; import org.intermine.metadata.FieldDescriptor; import org.intermine.web.config.WebConfig; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.ObjectStoreException; import org.intermine.objectstore.ObjectStoreSummary; import org.intermine.objectstore.ObjectStoreFactory; /** * Initialiser for the InterMine web application * Anything that needs global initialisation goes here. * * @author Andrew Varley */ public class InitialiserPlugin implements PlugIn { private static final Logger LOG = Logger.getLogger(InitialiserPlugin.class); ProfileManager profileManager; /** * Init method called at Servlet initialisation * * @param servlet ActionServlet that is managing all the modules * in this web application * @param config ModuleConfig for the module with which this * plug-in is associated * * @throws ServletException if this <code>PlugIn</code> cannot * be successfully initialized */ public void init(ActionServlet servlet, ModuleConfig config) throws ServletException { ServletContext servletContext = servlet.getServletContext(); loadClassDescriptions(servletContext); loadWebProperties(servletContext); loadExampleQueries(servletContext); loadWebConfig(servletContext); ObjectStore os = null; try { os = ObjectStoreFactory.getObjectStore(); os.flushObjectById(); } catch (Exception e) { throw new ServletException("Unable to instantiate ObjectStore", e); } servletContext.setAttribute(Constants.OBJECTSTORE, os); loadClassCategories(servletContext, os); processWebConfig(servletContext, os); summarizeObjectStore(servletContext, os); createProfileManager(servletContext, os); // Loading shared template queries requires profile manager loadSuperUserDetails(servletContext); // Load default templates if required loadDefaultGlobalTemplateQueries(servletContext); loadGlobalTemplateQueries(servletContext); } /** * Load the displayer configuration */ private void loadWebConfig(ServletContext servletContext) throws ServletException { InputStream is = servletContext.getResourceAsStream("/WEB-INF/webconfig-model.xml"); if (is == null) { throw new ServletException("Unable to find webconfig-model.xml"); } try { servletContext.setAttribute(Constants.WEBCONFIG, WebConfig.parse(is)); } catch (Exception e) { throw new ServletException("Unable to parse webconfig-model.xml", e); } } /** * Load the user-friendly class descriptions */ private void loadClassDescriptions(ServletContext servletContext) throws ServletException { InputStream is = servletContext.getResourceAsStream("/WEB-INF/classDescriptions.properties"); if (is == null) { return; } Properties classDescriptions = new Properties(); try { classDescriptions.load(is); } catch (Exception e) { throw new ServletException("Error loading classDescriptions.properties", e); } servletContext.setAttribute("classDescriptions", classDescriptions); } /** * Read the example queries into the EXAMPLE_QUERIES servlet context attribute. */ private void loadWebProperties(ServletContext servletContext) throws ServletException { Properties webProperties = new Properties(); InputStream globalPropertiesStream = servletContext.getResourceAsStream("/WEB-INF/global.web.properties"); try { webProperties.load(globalPropertiesStream); } catch (Exception e) { throw new ServletException("Unable to find global.web.properties", e); } InputStream modelPropertiesStream = servletContext.getResourceAsStream("/WEB-INF/web.properties"); if (modelPropertiesStream == null) { // there are no model specific properties } else { try { webProperties.load(modelPropertiesStream); } catch (Exception e) { throw new ServletException("Unable to find web.properties", e); } } servletContext.setAttribute(Constants.WEB_PROPERTIES, webProperties); } /** * Summarize the ObjectStore to get class counts */ private void summarizeObjectStore(ServletContext servletContext, ObjectStore os) throws ServletException { Properties objectStoreSummaryProperties = new Properties(); InputStream objectStoreSummaryPropertiesStream = servletContext.getResourceAsStream("/WEB-INF/objectstoresummary.properties"); if (objectStoreSummaryPropertiesStream == null) { // there are no model specific properties } else { try { objectStoreSummaryProperties.load(objectStoreSummaryPropertiesStream); } catch (Exception e) { throw new ServletException("Unable to read objectstoresummary.properties", e); } } ObjectStoreSummary oss = new ObjectStoreSummary(objectStoreSummaryProperties); Model model = os.getModel(); Map classes = new LinkedHashMap(); Map classCounts = new LinkedHashMap(); for (Iterator i = new TreeSet(model.getClassNames()).iterator(); i.hasNext();) { String className = (String) i.next(); classes.put(className, TypeUtil.unqualifiedName(className)); try { //classCounts.put(className, new Integer(1)); classCounts.put(className, new Integer(oss.getClassCount(className))); } catch (Exception e) { throw new ServletException("Unable to get class count for " + className, e); } } servletContext.setAttribute(Constants.OBJECT_STORE_SUMMARY, oss); servletContext.setAttribute("classes", classes); servletContext.setAttribute("classCounts", classCounts); } /** * Read the example queries into the EXAMPLE_QUERIES servlet context attribute. */ private void loadExampleQueries(ServletContext servletContext) throws ServletException { InputStream exampleQueriesStream = servletContext.getResourceAsStream("/WEB-INF/example-queries.xml"); if (exampleQueriesStream == null) { return; } Reader exampleQueriesReader = new InputStreamReader(exampleQueriesStream); Map exampleQueries = null; try { exampleQueries = new PathQueryBinding().unmarshal(exampleQueriesReader); } catch (Exception e) { throw new ServletException("Unable to parse example-queries.xml", e); } servletContext.setAttribute(Constants.EXAMPLE_QUERIES, exampleQueries); } /** * Loads the default template queries into the superuser's account. * * @param servletContext current servlet context */ private void loadDefaultGlobalTemplateQueries(ServletContext servletContext) throws ServletException { InputStream templateQueriesStream = servletContext.getResourceAsStream("/WEB-INF/template-queries.xml"); if (templateQueriesStream == null) { return; } Reader templateQueriesReader = new InputStreamReader(templateQueriesStream); Map templateQueries = null; try { templateQueries = new TemplateQueryBinding().unmarshal(templateQueriesReader); } catch (Exception e) { throw new ServletException("Unable to parse template-queries.xml", e); } // Add them to superuser profile String superuser = (String) servletContext.getAttribute(Constants.SUPERUSER_ACCOUNT); ProfileManager pm = (ProfileManager) servletContext.getAttribute(Constants.PROFILE_MANAGER); if (superuser == null) { LOG.warn("No superuser account specified"); return; } Profile profile = null; if (!pm.hasProfile(superuser)) { LOG.info("Creating profile for superuser " + superuser); profile = new Profile(pm, superuser, new HashMap(), new HashMap(), new HashMap()); String password = RequestPasswordAction.generatePassword(); Map webProperties = (Map) servletContext.getAttribute(Constants.WEB_PROPERTIES); pm.saveProfile(profile); pm.setPassword(superuser, password); } else { profile = pm.getProfile(superuser, pm.getPassword(superuser)); } if (profile.getSavedTemplates().size() == 0) { Iterator iter = templateQueries.values().iterator(); while (iter.hasNext()) { TemplateQuery template = (TemplateQuery) iter.next(); profile.saveTemplate(template.getName(), template); } } } /** * Load superuser account name into servlet context attribute SUPERUSER_ACCOUNT * * @param servetContext servlet context in which to place attribute */ private void loadSuperUserDetails(ServletContext servletContext) throws ServletException { Properties properties = new Properties(); InputStream propertiesStream = servletContext.getResourceAsStream("/WEB-INF/global.web.properties"); try { properties.load(propertiesStream); } catch (Exception e) { throw new ServletException("Unable to find model.properties", e); } String superuser = properties.getProperty("superuser.account"); servletContext.setAttribute(Constants.SUPERUSER_ACCOUNT, superuser); } /** * Read the template queries into the GLOBAL_TEMPLATE_QUERIES servlet context attribute and set * CATEGORY_TEMPLATES and CLASS_CATEGORY_TEMPLATES. * This is also called when the superuser updates his or her templates. * * @param servletContext servlet context in which to place template map * @throws ServletException if something goes wrong */ public static void loadGlobalTemplateQueries(ServletContext servletContext) throws ServletException { Map templateMap = Collections.synchronizedMap(new HashMap()); ProfileManager pm = (ProfileManager) servletContext.getAttribute(Constants.PROFILE_MANAGER); String superuser = (String) servletContext.getAttribute(Constants.SUPERUSER_ACCOUNT); if (superuser != null && pm.hasProfile(superuser)) { Profile profile = pm.getProfile(superuser, pm.getPassword(superuser)); if (profile != null) { templateMap = Collections.synchronizedMap(new HashMap(profile.getSavedTemplates())); } else { LOG.warn("failed to getch profile for superuser " + superuser); } } else { LOG.warn("superuser.account not specified"); } servletContext.setAttribute(Constants.GLOBAL_TEMPLATE_QUERIES, templateMap); // Sort into categories Map categoryTemplates = new HashMap(); // a Map from class name to a Map from category to template Map classCategoryTemplates = new HashMap(); // a Map from class name to a Map from template name to field name List - the field // names/expressions are the ones that should be set when a template is linked to from the // object details page eg. Gene.identifier Map classTemplateExprs = new HashMap(); Iterator iter = templateMap.values().iterator(); while (iter.hasNext()) { TemplateQuery template = (TemplateQuery) iter.next(); List list = (List) categoryTemplates.get(template.getCategory()); if (list == null) { list = new ArrayList(); categoryTemplates.put(template.getCategory(), list); } list.add(template); Object osObject = servletContext.getAttribute(Constants.OBJECTSTORE); ObjectStore os = (ObjectStore) osObject; setClassesForTemplate(os, template, classCategoryTemplates, classTemplateExprs); } servletContext.setAttribute(Constants.CATEGORY_TEMPLATES, categoryTemplates); servletContext.setAttribute(Constants.CLASS_CATEGORY_TEMPLATES, classCategoryTemplates); servletContext.setAttribute(Constants.CLASS_TEMPLATE_EXPRS, classTemplateExprs); } /** * Return a List of the names of the classes for which this template is relevant - ie. it * should appear on the object details page for objects of the class. */ private static void setClassesForTemplate(ObjectStore os, TemplateQuery template, Map classCategoryTemplates, Map classTemplateExprs) { List constraints = template.getAllConstraints(); Model model = os.getModel(); Iterator constraintIter = constraints.iterator(); // look for ClassName.fieldname (Gene.identifier) // or ClassName.fieldname.fieldname.fieldname... (eg. Gene.organism.name) while (constraintIter.hasNext()) { Constraint c = (Constraint) constraintIter.next(); String constraintIdentifier = c.getIdentifier(); String[] bits = constraintIdentifier.split("\\."); if (bits.length == 2) { String className = model.getPackageName() + "." + bits[0]; String fieldName = bits[1]; String fieldExpr = TypeUtil.unqualifiedName(className) + "." + fieldName; ClassDescriptor cd = model.getClassDescriptorByName(className); if (cd != null && cd.getFieldDescriptorByName(fieldName) != null) { Set subClasses = model.getAllSubs(cd); Set thisAndSubClasses = new HashSet(); thisAndSubClasses.addAll(subClasses); thisAndSubClasses.add(cd); Iterator thisAndSubClassesIterator = thisAndSubClasses.iterator(); while (thisAndSubClassesIterator.hasNext()) { ClassDescriptor thisCD = (ClassDescriptor) thisAndSubClassesIterator.next(); String thisClassName = thisCD.getName(); if (!classCategoryTemplates.containsKey(thisClassName)) { classCategoryTemplates.put(thisClassName, new HashMap()); } Map categoryTemplatesMap = (Map) classCategoryTemplates.get(thisClassName); if (!categoryTemplatesMap.containsKey(template.getCategory())) { categoryTemplatesMap.put(template.getCategory(), new ArrayList()); } ((List) categoryTemplatesMap.get(template.getCategory())).add(template); if (!classTemplateExprs.containsKey(thisClassName)) { classTemplateExprs.put(thisClassName, new HashMap()); } Map fieldNameTemplatesMap = (Map) classTemplateExprs.get(thisClassName); if (!fieldNameTemplatesMap.containsKey(template.getName())) { fieldNameTemplatesMap.put(template.getName(), new ArrayList()); } ((List) fieldNameTemplatesMap.get(template.getName())).add(fieldExpr); } } } } } /** * Load the CATEGORY_CLASSES and CATEGORIES servlet context attribute. Loads cateogires and * subcateogires from roperties file /WEB-INF/classCategories.properties<p> * * The properties file should look something like: * <pre> * category.0.name = People * category.0.subcategories = Employee Manager CEO Contractor Secretary * category.1.name = Entities * category.1.subcategories = Bank Address Department * </pre> * * If a specified class cannot be found in the model, the class is ignored and not added to * the category. * * @param servletContext the servlet context * @param os the main object store */ private void loadClassCategories(ServletContext servletContext, ObjectStore os) throws ServletException { List categories = new ArrayList(); Map subcategories = new HashMap(); InputStream in = servletContext.getResourceAsStream("/WEB-INF/classCategories.properties"); if (in == null) { return; } Properties properties = new Properties(); try { properties.load(in); } catch (IOException err) { throw new ServletException(err); } int n = 0; String catname; while ((catname = properties.getProperty("category." + n + ".name")) != null) { String sc = properties.getProperty("category." + n + ".classes"); String subcats[] = StringUtils.split(sc, ' '); List subcatlist = new ArrayList(); subcats = StringUtils.stripAll(subcats); for (int i = 0; subcats != null && i < subcats.length; i++) { String className = os.getModel().getPackageName() + "." + subcats[i]; if (os.getModel().hasClassDescriptor(className)) { subcatlist.add(subcats[i]); } else { LOG.warn("Category \"" + catname + "\" contains unknown class \"" + subcats[i] + "\""); } } categories.add(catname); subcategories.put(catname, subcatlist); n++; } servletContext.setAttribute(Constants.CATEGORIES, categories); servletContext.setAttribute(Constants.CATEGORY_CLASSES, subcategories); } /** * Create the DISPLAYERS ServletContext attribute by looking at the model and the WebConfig. * * @param servletContext the servlet context * @param os the main object store */ private void processWebConfig(ServletContext servletContext, ObjectStore os) throws ServletException { try { Model model = os.getModel(); WebConfig wc = (WebConfig) servletContext.getAttribute(Constants.WEBCONFIG); Map wcTypeMap = (Map) wc.getTypes(); Map displayersMap = new HashMap(); for (Iterator modelIter = new TreeSet(model.getClassNames()).iterator(); modelIter.hasNext();) { String className = (String) modelIter.next(); Set cds = model.getClassDescriptorsForClass(Class.forName(className)); List cdList = new ArrayList(cds); Collections.reverse(cdList); for (Iterator cdIter = cdList.iterator(); cdIter.hasNext(); ) { ClassDescriptor cd = (ClassDescriptor) cdIter.next(); if (wcTypeMap.get(cd.getName()) != null) { displayersMap.put(className, wcTypeMap.get(cd.getName())); } for (Iterator fdIter = cd.getFieldDescriptors().iterator(); fdIter.hasNext();) { FieldDescriptor fd = (FieldDescriptor) fdIter.next(); String newKey = cd.getName() + " " + fd.getName(); if (wcTypeMap.get(newKey) != null) { displayersMap.put(className + " " + fd.getName(), wcTypeMap.get(newKey)); } } } } servletContext.setAttribute(Constants.DISPLAYERS, displayersMap); } catch (ClassNotFoundException e) { throw new ServletException("Unable to process webconfig", e); } } /** * Create the profile manager and place it into to the servlet context. */ private void createProfileManager(ServletContext servletContext, ObjectStore os) throws ServletException { try { profileManager = new ProfileManager(os); } catch (ObjectStoreException e) { //throw new ServletException("Unable to create profile manager", e); } servletContext.setAttribute(Constants.PROFILE_MANAGER, profileManager); } /** * Destroy method called at Servlet destroy */ public void destroy() { profileManager.close(); } }
// -*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: // @homepage@ package example; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.HierarchyEvent; import java.awt.font.FontRenderContext; import java.awt.font.GlyphMetrics; import java.awt.font.GlyphVector; import java.awt.font.LineMetrics; import java.awt.geom.Line2D; import javax.swing.*; public final class MainPanel extends JPanel { private MainPanel() { super(new BorderLayout()); add(new MarqueePanel()); setPreferredSize(new Dimension(320, 240)); } public static void main(String[] args) { EventQueue.invokeLater(MainPanel::createAndShowGui); } private static void createAndShowGui() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); Toolkit.getDefaultToolkit().beep(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } class MarqueePanel extends JComponent implements ActionListener { private final Timer animator = new Timer(10, this); private final GlyphVector gv; private final LineMetrics lm; private final float corpusSize; // the x-height private float xx; private float baseline; protected MarqueePanel() { super(); addHierarchyListener(e -> { if ((e.getChangeFlags() & HierarchyEvent.DISPLAYABILITY_CHANGED) != 0 && !e.getComponent().isDisplayable()) { animator.stop(); } }); String text = "abcdefghijklmnopqrstuvwxyz"; Font font = new Font(Font.SERIF, Font.PLAIN, 100); FontRenderContext frc = new FontRenderContext(null, true, true); gv = font.createGlyphVector(frc, text); lm = font.getLineMetrics(text, frc); GlyphMetrics xgm = gv.getGlyphMetrics(23); corpusSize = (float) xgm.getBounds2D().getHeight(); animator.start(); } @Override protected void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g.create(); // g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); // g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); float w = getWidth(); g2.setPaint(Color.RED); g2.draw(new Line2D.Float(0f, baseline, w, baseline)); g2.setPaint(Color.GREEN); float ascent = baseline - lm.getAscent(); g2.draw(new Line2D.Float(0f, ascent, w, ascent)); g2.setPaint(Color.BLUE); float descent = baseline + lm.getDescent(); g2.draw(new Line2D.Float(0f, descent, w, descent)); g2.setPaint(Color.ORANGE); float leading = baseline + lm.getDescent() + lm.getLeading(); g2.draw(new Line2D.Float(0f, leading, w, leading)); g2.setPaint(Color.CYAN); float xh = baseline - corpusSize; g2.draw(new Line2D.Float(0f, xh, w, xh)); g2.setPaint(Color.BLACK); g2.drawGlyphVector(gv, w - xx, baseline); g2.dispose(); } @Override public void actionPerformed(ActionEvent e) { xx = getWidth() + gv.getVisualBounds().getWidth() - xx > 0 ? xx + 2f : 0f; baseline = getHeight() / 2f; repaint(); } }
package de.velcommuta.libvicbf; import static org.junit.Assert.*; import java.io.IOException; import org.junit.Test; public class VICBFTest { @Test public void test_slot_calculation() { VICBF test = new VICBF(10000, 3); int v = test.calculateSlot("123".getBytes(), 0); assertEquals(v, (short) 9653); v = test.calculateSlot("testvicbf".getBytes(), 0); assertEquals(v, (short) 8525); v = test.calculateSlot("decafbad".getBytes(), 0); assertEquals(v, (short) 7634); } @Test public void test_increment_calculation() { VICBF test = new VICBF(10000, 3); byte t = test.calculateIncrement("123".getBytes(), 0); assertEquals(t, (byte) 5); t = test.calculateIncrement("testvicbf".getBytes(), 0); assertEquals(t, (byte) 7); t = test.calculateIncrement("decafbad".getBytes(), 0); assertEquals(t, (byte) 5); } @Test public void test_insert_query() { VICBF test = new VICBF(10000, 3); assertEquals(test.getSize(), 0); assertFalse(test.query("deadbeef".getBytes())); test.insert("deadbeef".getBytes()); assertEquals(test.getSize(), 1); assertTrue(test.query("deadbeef".getBytes())); assertFalse(test.query("deafbeet".getBytes())); } @Test public void test_insert_delete() { VICBF test = new VICBF(10000, 3); test.insert("decafbad".getBytes()); assertEquals(test.getSize(), 1); assertTrue(test.query("decafbad".getBytes())); try { test.remove("decafbad".getBytes()); } catch (Exception e) { assertTrue(false); } assertFalse(test.query("decafbad".getBytes())); assertEquals(test.getSize(), 0); } @Test public void test_delete_not_inserted() { VICBF test = new VICBF(10000, 3); try { test.remove("decafbad".getBytes()); assertFalse(true); } catch (Exception e) { assertTrue(true); } } @Test public void test_multi_insert_one_delete() { VICBF test = new VICBF(10000, 3); test.insert("decafbad".getBytes()); test.insert("deadbeef".getBytes()); test.insert("carebearstare".getBytes()); try { test.remove("decafbad".getBytes()); } catch (Exception e) { assertTrue(false); } assertFalse(test.query("decafbad".getBytes())); assertTrue(test.query("deadbeef".getBytes())); assertTrue(test.query("carebearstare".getBytes())); } @Test public void test_delete_regression_1() { // This test aims to check a specific bordercase in the deletion routine // that could result in an inconsistent VICBF when triggered. VICBF test = new VICBF(10000, 3); test.insert("106".getBytes()); test.insert("771".getBytes()); try { test.remove("132".getBytes()); assertFalse(true); } catch (Exception e) { assertTrue(true); } try { test.remove("106".getBytes()); } catch (Exception e) { assertFalse(true); } assertTrue(test.query("771".getBytes())); } @Test public void test_deserialize_python_full() throws IOException { // Serialization of VICBF with 1000 slots, containing all numbers from 0 to 500 String ser = "03000003e8000001f44806100a0009070612000c050000000b0400040507060f0d00160c1200000c0504040905050f00050400100c0005110700070c0d120e0011000b0d0517000b090600040009060c0b071d0e0004141000061006140700060506140c14090b0d1109050c09040c060c070004120005040b060e0005050a050f0c070507211a0606090006150a0c0d0c000000040b0005090a060a0004050006130505070000170b0d0b08090006061115000f070d0900051a070008060b10050008001211000711060c0800040e0f040507000d060b0c0012060005000418000008141206071a0000040f00040600000704000005071014050b180a0c0411000b000b051205050b0b0d0b100004000606141a1200000006120e07000c000b00130e040a040500000a000700000d0c0008050908000807000c0e10070507001c0f0c0d0d070e17111a18060c0000050b09050e11180c0007050405060d00040b00000b0906000e190c000b000b00140e0d06000c171100040e1100050000000c090a06000c0b0b0c0e0b00210c000c0b0607060c0e09250b0406000d0413000c0808000c002210040b05070400060b00140a050c050c0d05170a04200016000a1006080705070012120a14041100100007070e000905120b07000005000404040806040d0000190504060b060e04000900050007051305050607060e101907080000050008130b001205050700001911040600060b0f1c100016070b0b041b0505040b0b040d16070000140700120500040704000c15070e0a26070c0a0d060a000914001c00051007000d0015040e160513041a06000405040005060412000c000d061507050a07050b0009120d1d070f07000a0709050b0000071e0018040f160a0700050b120d13000b181b0019000b0009130a0e0515090705150a10000005050005000d1304001305000006040608060c000c0e0c001407140e0e070c05060906060011000d0f00080b000b06070507040d12000a000006060b0819140006071106000900060011000d070000060b04040b0f000a000a000900001904001105040a0d150a000b1106060b000000050c17000006050a041822050007000713041117110e0c04000c0b15060410050005000c0e0c0000070004050700000409060407070604040a00040f00101700060505050b0515050c0e050b0011040504000d00080c0b13000b1b04060b0d040a07070b000705000610050b06050004041004050f00000f000404060004000a0000050c050900050f000007050b04070e00000d070b04070a07130005050d000b0d05070a050c07000c0009080d050b0e000f13000c001207000a04110c13000e141606000008051507060c0400160b040500040000090b0c05110b040e060700"; VICBF v = VICBF.deserialize(ser); for (int i = 0; i < 500; i++) { assertTrue(v.query(Integer.toString(i).getBytes())); } assertEquals(v.getSize(), 500); assertFalse(v.query("501".getBytes())); v.insert("501".getBytes()); assertTrue(v.query("501".getBytes())); assertEquals(v.getSize(), 501); } @Test public void test_deserialize_python_partial() throws IOException { // Serialization of VICBF with 10000 slots, containing numbers 123 and 126 String ser = "830000271000000002482663070f850419ab0701b20525b505069a07"; VICBF v = VICBF.deserialize(ser); assertTrue(v.query("123".getBytes())); assertTrue(v.query("126".getBytes())); assertFalse(v.query("1337".getBytes())); assertEquals(v.getSize(), 2); v.insert("1337".getBytes()); assertTrue(v.query("1337".getBytes())); assertEquals(v.getSize(), 3); } @Test public void test_bytestoint() { byte[] bytes1 = {(byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xFF}; byte[] bytes2 = {(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00}; byte[] bytes3 = {(byte) 0x00}; byte[] bytes4 = {(byte) 0x01, (byte) 0x31}; assertEquals(VICBF.bytesToInt(bytes1), -1); assertEquals(VICBF.bytesToInt(bytes2), 0); assertEquals(VICBF.bytesToInt(bytes3), 0); assertEquals(VICBF.bytesToInt(bytes4), 305); } }
package cmcc.iot.onenet.javasdk; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.json.JSONObject; import org.junit.Test; import cmcc.iot.onenet.javasdk.api.bindata.AddBindataApi; import cmcc.iot.onenet.javasdk.api.bindata.GetBindataApi; import cmcc.iot.onenet.javasdk.api.cmds.QueryCmdsRespApi; import cmcc.iot.onenet.javasdk.api.cmds.QueryCmdsStatus; import cmcc.iot.onenet.javasdk.api.cmds.SendCmdsApi; import cmcc.iot.onenet.javasdk.api.datapoints.AddDatapointsApi; import cmcc.iot.onenet.javasdk.api.datapoints.GetDatapointsListApi; import cmcc.iot.onenet.javasdk.api.datastreams.AddDatastreamsApi; import cmcc.iot.onenet.javasdk.api.datastreams.DeleteDatastreamsApi; import cmcc.iot.onenet.javasdk.api.datastreams.FindDatastreamListApi; import cmcc.iot.onenet.javasdk.api.datastreams.GetDatastreamApi; import cmcc.iot.onenet.javasdk.api.datastreams.ModifyDatastramsApi; import cmcc.iot.onenet.javasdk.api.device.AddDevicesApi; import cmcc.iot.onenet.javasdk.api.device.DeleteDeviceApi; import cmcc.iot.onenet.javasdk.api.device.FindDevicesListApi; import cmcc.iot.onenet.javasdk.api.device.GetDeviceApi; import cmcc.iot.onenet.javasdk.api.device.ModifyDevicesApi; import cmcc.iot.onenet.javasdk.api.device.RegisterDeviceApi; import cmcc.iot.onenet.javasdk.api.key.AddKeyApi; import cmcc.iot.onenet.javasdk.api.key.DeleteKeyApi; import cmcc.iot.onenet.javasdk.api.key.FindKeyList; import cmcc.iot.onenet.javasdk.api.key.ModifyKeyApi; import cmcc.iot.onenet.javasdk.api.mqtt.CreateMqttTopicApi; import cmcc.iot.onenet.javasdk.api.mqtt.DeleteUserTopic; import cmcc.iot.onenet.javasdk.api.mqtt.FindTopicDevices; import cmcc.iot.onenet.javasdk.api.mqtt.GetDevicesTopicsApi; import cmcc.iot.onenet.javasdk.api.mqtt.GetUserTopics; import cmcc.iot.onenet.javasdk.api.mqtt.SendMqttApi; import cmcc.iot.onenet.javasdk.api.triggers.AddTriggersApi; import cmcc.iot.onenet.javasdk.api.triggers.DeleteTriggersApi; import cmcc.iot.onenet.javasdk.api.triggers.FindTriggersListApi; import cmcc.iot.onenet.javasdk.api.triggers.GetTriggersApi; import cmcc.iot.onenet.javasdk.api.triggers.ModifyTriggersApi; import cmcc.iot.onenet.javasdk.model.Data; import cmcc.iot.onenet.javasdk.model.Datapoints; import cmcc.iot.onenet.javasdk.model.Devices; import cmcc.iot.onenet.javasdk.model.Location; import cmcc.iot.onenet.javasdk.model.Permissions; import cmcc.iot.onenet.javasdk.response.BasicResponse; import cmcc.iot.onenet.javasdk.response.bindata.NewBindataResponse; import cmcc.iot.onenet.javasdk.response.cmds.CmdsResponse; import cmcc.iot.onenet.javasdk.response.cmds.NewCmdsResponse; import cmcc.iot.onenet.javasdk.response.datapoints.DatapointsList; import cmcc.iot.onenet.javasdk.response.datastreams.DatastreamsResponse; import cmcc.iot.onenet.javasdk.response.datastreams.NewdatastramsResponse; import cmcc.iot.onenet.javasdk.response.device.DeviceList; import cmcc.iot.onenet.javasdk.response.device.DeviceResponse; import cmcc.iot.onenet.javasdk.response.device.NewDeviceResponse; import cmcc.iot.onenet.javasdk.response.device.RegDeviceResponse; import cmcc.iot.onenet.javasdk.response.key.KeyList; import cmcc.iot.onenet.javasdk.response.key.NewKeyResponse; import cmcc.iot.onenet.javasdk.response.mqtt.TopicDeviceList; import cmcc.iot.onenet.javasdk.response.triggers.NewTriggersResponse; import cmcc.iot.onenet.javasdk.response.triggers.TriggersList; import cmcc.iot.onenet.javasdk.response.triggers.TriggersResponse; public class ApiTest { @Test public void testAdddevices() { String key = "9ylHzkz25nre41i=SuJR=F=k5kU="; String title = "devices_test"; String desc = "devices_test"; String protocol = "HTTP"; Location location =new Location(106,29,370); List<String> tags = new ArrayList<String>(); tags.add("china"); tags.add("mobile"); String auth_info = "201503041a5829151"; /**** * * * @param title String * @param protocol HTTP,String * @param desc ,String * @param tags ,List<String> * @param location {"", "", ""},Location * @param isPrivate ,Booleanture * @param authInfo ,Object * @param other ,Map<String, Object> * @param interval MODBUS ,Integer * @param key masterkey,String */ AddDevicesApi api = new AddDevicesApi(title, protocol, desc, tags, location, null, auth_info, null, null, key); api.build(); BasicResponse<NewDeviceResponse> response = api.executeApi(); System.out.println("errno:"+response.errno+" error:"+response.error); System.out.println(response.getJson()); } @Test public void testModifydevices() { String id = "1674527"; String key = "9ylHzkz25nre41i=SuJR=F=k5kU="; String title = "devices_test2"; String desc = "devices_test2"; String protocol = "HTTP"; List<String> tags = new ArrayList<String>(); tags.add("china"); tags.add("mobile"); String auth_info = "201503041a5829151"; /*** * * * @param id ID,String * @param title String * @param protocol HTTPString * @param desc String * @param tags List<String> * @param location {"", "", ""},Location * @param isPrivate Boolean * @param authInfo Object * @param other Map<String, Object> * @param interval MODBUS ,Integer * @param key masterkey apikey,String */ ModifyDevicesApi api = new ModifyDevicesApi(id, title, protocol, desc, tags,null,null,auth_info, null, null,key); api.build(); BasicResponse<Void> response = api.executeApi(); System.out.println("errno:"+response.errno+" error:"+response.error); } @Test public void testGetdevice() { String id = "1674527"; String key = "9ylHzkz25nre41i=SuJR=F=k5kU="; /** * * * @param devid:String * @param key:masterkey apikey,String */ GetDeviceApi api = new GetDeviceApi(id, key); api.build(); BasicResponse<DeviceResponse> response = api.executeApi(); System.out.println("errno:"+response.errno+" error:"+response.error); System.out.println(response.getJson()); } @Test public void testFinddevicesList() { String key = "9ylHzkz25nre41i=SuJR=F=k5kU="; /** * * * @param keywords:idtitle,String * @param authinfo:sn,Object * @param devid: ID100,String * @param begin:,Date * @param end:,Date * @param tags:,List<String> * @param isPrivate Boolean * @param page:10000,Integer * @param perpage:30100,Integer * @param isOnline: * @param key:masterkey */ FindDevicesListApi api = new FindDevicesListApi(null, null, null, null, null, null, null, null, null, null, key); api.build(); BasicResponse<DeviceList> response = api.executeApi(); System.out.println("errno:"+response.errno+" error:"+response.error); System.out.println(response.getJson()); } @Test public void testRemovedevice() { String id = "1674526"; String key = "9ylHzkz25nre41i=SuJR=F=k5kU="; /** * * * @param devid: ID,String * @param key: masterkey key */ DeleteDeviceApi api = new DeleteDeviceApi(id, key); api.build(); BasicResponse<Void> response = api.executeApi(); System.out.println("errno:"+response.errno+" error:"+response.error); } @Test public void testRegisterDeviceApi() { String key = "9ylHzkz25nre41i=SuJR=F=k5kU="; String sn = "2017031401421"; String title = "myddddvvv2s"; String code = "ZSAuX3f1QPNp2n1m"; /** * * * @param code,String * @param macmac32 * @param snString512 * @param title: 32 * @param key: */ RegisterDeviceApi api = new RegisterDeviceApi(code, null, sn, title, key); api.build(); BasicResponse<RegDeviceResponse> response = api.executeApi(); System.out.println("errno:"+response.errno+" error:"+response.error); System.out.println(response.getData().key); } @Test public void testAddDatastreamsApi() { String key = "9ylHzkz25nre41i=SuJR=F=k5kU="; String id = "temperature2"; String devId = "1674527"; List<String> tags = new ArrayList<String>(); tags.add("china"); tags.add("mobile"); String unit = "celsius"; String unitsymbol = "C"; String cmd = "0003000000184411"; int interval = 60; String formula = "(A0+A1)*A2"; /** * * @param id String * @param devId:ID,String * @param tags:,List<Stirng> * @param unit:,String * @param unitSymbol:,String * @param cmd:MODBUS16 * @param interval:MODBUS,Integer * @param formula:MODBUS,String * @param key:masterkey apikey */ AddDatastreamsApi api = new AddDatastreamsApi(id, devId, tags, unit, unitsymbol, cmd, interval, formula, key); api.build(); BasicResponse<NewdatastramsResponse> response = api.executeApi(); System.out.println("errno:"+response.errno+" error:"+response.error); System.out.println(response.getData().id); } @Test public void testModifyDatastreamsApi() { String dsid = "temperature2"; String key = "9ylHzkz25nre41i=SuJR=F=k5kU="; String devId = "1674527"; List<String> tags = new ArrayList<String>(); tags.add("china"); tags.add("mobile"); String unit = "celsius"; String unitsymbol = "C"; String cmd = "0003000000184411"; int interval = 80; String formula = "(A0+A1)*A2"; /** * * @param dsid: ,String * @param devId:ID,String * @param tags: * @param unit:,String * @param unitSymbol:,String * @param cmd:MODBUS16 * @param interval:MODBUS,Integer * @param formula:MODBUS,String * @param key:masterkey apikey */ ModifyDatastramsApi api = new ModifyDatastramsApi(dsid, devId, tags, unit, unitsymbol, cmd, interval, formula, key); api.build(); BasicResponse<Void> response = api.executeApi(); System.out.println("errno:"+response.errno+" error:"+response.error); } @Test public void testGetDatastream() { String devId = "212141"; String id = "datastream_idxx"; String key = "m4EubNp9WCeAxjFu4lVw=kn2idE="; /** * * @param devid:ID,String * @param datastreamid: ,String * @param key:masterkey apikey */ GetDatastreamApi api = new GetDatastreamApi(devId, id, key); api.build(); BasicResponse<DatastreamsResponse> response = api.executeApi(); System.out.println("errno:"+response.errno+" error:"+response.error); System.out.println(response.getData().getId()); } @Test public void testFindDatastreamsListApi() { String datastreamids = "datastream_idxx,datastream_idxy"; String devid = "212141"; String key = "m4EubNp9WCeAxjFu4lVw=kn2idE="; /** * * @param datastreamids: ,String * @param devid:ID,String * @param key:masterkey apikey */ FindDatastreamListApi api = new FindDatastreamListApi(datastreamids, devid, key); api.build(); BasicResponse<List<DatastreamsResponse>> response = api.executeApi(); System.out.println("errno:"+response.errno+" error:"+response.error); System.out.println(response.getJson()); } @Test public void testRemoveDatastreamApi() { String dsid = "temperature2"; String key = "9ylHzkz25nre41i=SuJR=F=k5kU="; String devId = "1674527"; /** * * @param devid:ID,String * @param datastreamid: ,String * @param key:masterkey apikey */ DeleteDatastreamsApi api = new DeleteDatastreamsApi(devId, dsid, key); api.build(); BasicResponse<Void> response = api.executeApi(); System.out.println("errno:"+response.errno+" error:"+response.error); } @Test public void testAddDatapointsApi() { String devid = "212141"; String key = "m4EubNp9WCeAxjFu4lVw=kn2idE="; List<Datapoints> list = new ArrayList<Datapoints>(); List<Data> dl = new ArrayList<Data>(); dl.add(new Data("2013-04-22T00:35:43", 11)); dl.add(new Data("2013-04-22T00:36:43", 12)); list.add(new Datapoints("datastream_idxx", dl)); list.add(new Datapoints("datastream_idxy", dl)); Map<String, List<Datapoints>> map = new HashMap<String, List<Datapoints>>(); map.put("datastreams", list); /** * * @param map :,Map<String,List<Datapoints>> * @param data:,String * * type=4 * data="{\"temperature\":{\"2015-03-22T22:31:12\":22.5}}"; * type=5 * data=",;temperature,2015-03-22T22:31:12,22.5;pm2.5,89"; * @param type:JSONHTTP * @param devId:ID,String * @param key:masterkey apikey */ AddDatapointsApi api = new AddDatapointsApi(map, null, null, devid, key); api.build(); BasicResponse<Void> response = api.executeApi(); System.out.println("errno:"+response.errno+" error:"+response.error); } //type=4 @Test public void testAddDatapointsTypefourApi() { String devid = "212141"; int type=4; String key = "m4EubNp9WCeAxjFu4lVw=kn2idE="; String data="{\"datastream_idxx\":{\"2015-03-22T22:31:12\":22.5}}"; /** * * @param map :,Map<String,List<Datapoints>> * @param data:,String * * type=4 * data="{\"temperature\":{\"2015-03-22T22:31:12\":22.5}}"; * type=5 * data=",;temperature,2015-03-22T22:31:12,22.5;pm2.5,89"; * @param type:JSONHTTP * @param devId:ID,String * @param key:masterkey apikey */ AddDatapointsApi api = new AddDatapointsApi(null, data, type, devid, key); api.build(); BasicResponse<Void> response = api.executeApi(); System.out.println("errno:"+response.errno+" error:"+response.error); } @Test public void testGetDatapointsApi() { String datastreamids = "datastream_idxx,datastream_idxy"; String devid = "212141"; String key = "m4EubNp9WCeAxjFu4lVw=kn2idE="; /** * * @param datastreamids:,String * @param start:,String * @param end:,String * @param devid:ID,String * * @param duration:,Integer * start+durationstart * end+durationend * * @param limit:0<n<=60001440,Integer * @param cursor:cursor,Integer * @param interval:interval,Integer * @param metd:,String * @param first:1-0-1,Integer * @param sort:DESC|ASCDESC:ASC,String * @param key:masterkey apikey */ GetDatapointsListApi api = new GetDatapointsListApi(datastreamids, null, null, devid, null, null, null, null, null, null, null, key); api.build(); BasicResponse<DatapointsList> response = api.executeApi(); System.out.println(response.getJson()); } @Test public void testAddtriggersApi() { String dsid = "datastream_idxx"; String url = "http://xx.bb.com"; String type = "=="; int threshold = 100; String key = "m4EubNp9WCeAxjFu4lVw=kn2idE="; /** * * @param title:,String * @param dsid:id,String * @param devids:ID,List<String> * @param dsuuids:uuid,List<String> * @param desturl:url,String * @param type:String * @param threshold:type,Integer * @param key:masterkey apikey */ AddTriggersApi api = new AddTriggersApi(null, dsid, null, null, url, type, threshold, key); api.build(); BasicResponse<NewTriggersResponse> response = api.executeApi(); System.out.println(response.getJson()); } @Test public void testModifyTriggersApi() { String url = "http://xx.bbc.com"; String type = "=="; int threshold = 100; List<String> dsuuids = new ArrayList<String>(); dsuuids.add("28ccffa8-9eab-53d0-8365-84928950c473"); String key = "m4EubNp9WCeAxjFu4lVw=kn2idE="; String tirggerid = "288"; /** * * @param tirggerid:ID,String * @param title:,String * @param dsidid,String * @param devids:ID,List<String> * @param dsuuids:uuid,List<String> * @param desturl:url,String * @param type:String * @param threshold:type,Integer * @param key:masterkey apikey */ ModifyTriggersApi api = new ModifyTriggersApi(tirggerid, null, null, null, dsuuids, url, type, threshold, key); api.build(); BasicResponse<Void> response = api.executeApi(); System.out.println("errno:"+response.errno+" error:"+response.error); } @Test public void testGetTriggersApi() { String tirggerid = "288"; String key = "m4EubNp9WCeAxjFu4lVw=kn2idE="; /** * * @param tirggerid:ID,String * @param key:masterkey apikey */ GetTriggersApi api = new GetTriggersApi(tirggerid, key); api.build(); BasicResponse<TriggersResponse> response = api.executeApi(); System.out.println(response.getJson()); } @Test public void testFindTriggersListApi() { String title = "test"; String key = "m4EubNp9WCeAxjFu4lVw=kn2idE="; /** * * @param title:,String * @param page:10000,Integer * @param perpage:30100,Integer * @param key:masterkey apikey */ FindTriggersListApi api = new FindTriggersListApi(title, null, null, key); api.build(); BasicResponse<TriggersList> response = api.executeApi(); System.out.println(response.getJson()); } @Test public void testRemoveTriggersApi() { String tirggerid = "3228"; String key = "9ylHzkz25nre41i=SuJR=F=k5kU="; /** * * @param tirggerid:ID,String * @param key:masterkey apikey */ DeleteTriggersApi api = new DeleteTriggersApi(tirggerid, key); api.build(); BasicResponse<Void> response = api.executeApi(); System.out.println("errno:"+response.errno+" error:"+response.error); } @Test public void testAddBindataApi() { String devId = "212141"; String datastreamid = "datastream_idxy"; String key = "m4EubNp9WCeAxjFu4lVw=kn2idE="; String filename = "a"; String filepath = "E://data.txt"; /** * * * @param devId:,String * @param datastreamid:,String * @param key:masterkey key * @param filename:,String * @param filepath,String */ AddBindataApi api = new AddBindataApi(devId, datastreamid, key, filename, filepath); api.build(); BasicResponse<NewBindataResponse> response = api.executeApi(); System.out.println(response.getJson()); } @Test public void testGetBindataApi() { String index = "212141_1490712458735_datastream_idxx"; String key = "m4EubNp9WCeAxjFu4lVw=kn2idE="; /** * * @param index:,String * @param key:masterkey key */ GetBindataApi api = new GetBindataApi(index, key); api.build(); System.out.println(api.executeApi()); } @Test public void testAddKeyApi() { String title = "sharing key"; List<Permissions> permissions = new ArrayList<Permissions>(); List<Devices> resources = new ArrayList<Devices>(); List<String> accessMethods = new ArrayList<String>(); resources.add(new Devices("212141")); accessMethods.add("POST"); accessMethods.add("GET"); accessMethods.add("PUT"); permissions.add(new Permissions(resources, accessMethods)); String key = "m4EubNp9WCeAxjFu4lVw=kn2idE="; AddKeyApi api = new AddKeyApi(title, permissions, key); api.build(); BasicResponse<NewKeyResponse> response = api.executeApi(); System.out.println(response.getData().getKey()); System.out.println(response.getJson()); } @Test public void testModifyKeyApi() { String title = "sharing key"; String apikey = "A1HzNFR344JgmZCZ3=O9FsQ9q=s="; List<Permissions> permissions = new ArrayList<Permissions>(); List<Devices> resources = new ArrayList<Devices>(); List<String> accessMethods = new ArrayList<String>(); resources.add(new Devices("212141")); accessMethods.add("POST"); accessMethods.add("GET"); accessMethods.add("PUT"); permissions.add(new Permissions(resources, accessMethods)); String key = "m4EubNp9WCeAxjFu4lVw=kn2idE="; ModifyKeyApi api = new ModifyKeyApi(title, apikey, permissions, key); api.build(); BasicResponse<Void> response = api.executeApi(); System.out.println("errno:"+response.errno+" error:"+response.error); } @Test public void testFindKeyList() { String devId = "212141"; String key = "m4EubNp9WCeAxjFu4lVw=kn2idE="; /** * API key * @param apikeyapikey,String * @param page:10000,Integer * @param perpage:30100,Integer * @param devid,master-key,String * @param keymasterkey(master-key) */ FindKeyList api = new FindKeyList(null, null, null, devId, key); api.build(); BasicResponse<KeyList> response = api.executeApi(); System.out.println(response.getJson()); } @Test public void testRemoveKeyApi() { String keystr = "A1HzNFR344JgmZCZ3=O9FsQ9q=s="; String key = "m4EubNp9WCeAxjFu4lVw=kn2idE="; /** * API key * @param keystrapikey,String * @param keymasterkey(master-key) */ DeleteKeyApi api = new DeleteKeyApi(keystr, key); api.build(); BasicResponse<Void> response = api.executeApi(); System.out.println("errno:"+response.errno+" error:"+response.error); } @Test public void testSendBytesCmdsApi() throws IOException { String devId = "9288"; String key = "JKRfIzneAwXLdI6V0Yy83XOavb8="; File file = new File("E://data.txt"); long fileSize = file.length(); FileInputStream fi = new FileInputStream(file); byte[] buffer = new byte[(int) fileSize]; int offset = 0; int numRead = 0; while (offset < buffer.length && (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) { offset += numRead; } if (offset != buffer.length) { throw new IOException("Could not completely read file " + file.getName()); } fi.close(); /** * * @param devIdIDString * @param qos:0,Integer * 0 * 1(timeout * * type=0 * @param timeOut:0,Integer * 0, * >0 timeout0~2678400 * type=0 * @param type://00CMD_REQ1PUSH_DATA * @param contents:jsonstring64K * @param key:masterkeyapikey */ SendCmdsApi api = new SendCmdsApi(devId, null, null, null, buffer, key); api.build(); BasicResponse<NewCmdsResponse> response = api.executeApi(); System.out.println(response.getJson()); } // String @Test public void testSendStrCmdsApi() throws IOException { String devId = "9288"; String key = "JKRfIzneAwXLdI6V0Yy83XOavb8="; String text = "xxxxxxxxxxxxxxxxx"; /** * * @param devIdIDString * @param qos:0,Integer * 0 * 1(timeout * * type=0 * @param timeOut:0,Integer * 0, * >0 timeout0~2678400 * type=0 * @param type://00CMD_REQ1PUSH_DATA * @param contents:jsonstring64K * @param key:masterkeyapikey */ SendCmdsApi api = new SendCmdsApi(devId, null, null, null, text, key); api.build(); BasicResponse<NewCmdsResponse> response = api.executeApi(); System.out.println(response.getJson()); } // json @Test public void testSendJsonCmdsApi() throws IOException { String devId = "9288"; String key = "JKRfIzneAwXLdI6V0Yy83XOavb8="; JSONObject json = new JSONObject(); json.put("title", "xxxxxxxxxxx"); /** * * @param devIdID,String * @param qos:0,Integer * 0 * 1(timeout * * type=0 * @param timeOut:0,Integer * 0, * >0 timeout0~2678400 * type=0 * @param type://00CMD_REQ1PUSH_DATA * @param contents:jsonstring64K * @param key:masterkeyapikey */ SendCmdsApi api = new SendCmdsApi(devId, null, null, null, json, key); api.build(); BasicResponse<NewCmdsResponse> response = api.executeApi(); System.out.println(response.getJson()); } @Test public void testQueryCmdsStatusApi(){ String cmdUuid="3a7b478e-f07d-56e6-b312-2362ac15f13f"; String key="JKRfIzneAwXLdI6V0Yy83XOavb8="; /** * * @param cmduuid:id,String * @param key:masterkeyapikey */ QueryCmdsStatus api=new QueryCmdsStatus(cmdUuid,key); api.build(); BasicResponse<CmdsResponse> response = api.executeApi(); System.out.println(response.getJson()); } @Test public void testQueryCmdsRespApi(){ String cmdUuid="3a7b478e-f07d-56e6-b312-2362ac15f13f"; String key="JKRfIzneAwXLdI6V0Yy83XOavb8="; /** * * @param cmduuid:id,String * @param key:masterkeyapikey */ QueryCmdsRespApi api=new QueryCmdsRespApi(cmdUuid,key); api.build(); BasicResponse<Void> response = api.executeApi(); System.out.println("errno:"+response.errno+" error:"+response.error); } @Test public void testCreateMqttTopicApi(){ String name="testtopic"; String key="JKRfIzneAwXLdI6V0Yy83XOavb8="; /** * Topic * @param name:,String * @param keymasterkey */ CreateMqttTopicApi api=new CreateMqttTopicApi(name,key); api.build(); BasicResponse<Void> response = api.executeApi(); System.out.println("errno:"+response.errno+" error:"+response.error); } @Test public void testSendMqttsApi(){ String topic="testtopic"; String key="JKRfIzneAwXLdI6V0Yy83XOavb8="; JSONObject json = new JSONObject(); json.put("title", "wangxiaojun is laosiji"); /** *Topic * @param topic,String * @param contents:jsonstring64K * @param keymasterkey */ SendMqttApi api = new SendMqttApi(topic, json, key); api.build(); BasicResponse<Void> response = api.executeApi(); System.out.println("errno:"+response.errno+" error:"+response.error); } @Test public void testFindDevicesListApi(){ String topic="testtopic"; String key="JKRfIzneAwXLdI6V0Yy83XOavb8="; int page=1; int perPage=1; /** * Topic * @param page. ,1,Integer * @param perPage. 1-1000,Integer * @param topic,String * @param keymasterkey */ FindTopicDevices api=new FindTopicDevices(page, perPage, topic, key); api.build(); BasicResponse<TopicDeviceList> response = api.executeApi(); System.out.println(response.getJson()); } @Test public void testGetTopicsApi(){ String devId="9288"; String key="JKRfIzneAwXLdI6V0Yy83XOavb8="; /** * Topic * @param devIdID,String * @param keymasterkey */ GetDevicesTopicsApi api=new GetDevicesTopicsApi(devId,key); api.build(); BasicResponse<List<String>> response = api.executeApi(); System.out.println(response.getJson()); } @Test public void testGetUserTopicsApi(){ String key="JKRfIzneAwXLdI6V0Yy83XOavb8="; /** * Topic * @param keymasterkey */ GetUserTopics api=new GetUserTopics(key); api.build(); BasicResponse<List<String>> response = api.executeApi(); System.out.println(response.getJson()); } @Test public void testRemoveUserTopic(){ String key="JKRfIzneAwXLdI6V0Yy83XOavb8="; String name="testtopic"; /** * Topic * @param nametopic * @param keymasterkey */ DeleteUserTopic api=new DeleteUserTopic(name,key); api.build(); BasicResponse<Void> response = api.executeApi(); System.out.println(response.getJson()); } }
package org.unitime.timetable.solver.ui; import java.io.Serializable; import java.util.BitSet; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import org.unitime.timetable.model.PreferenceLevel; import org.unitime.timetable.util.Constants; import net.sf.cpsolver.coursett.constraint.GroupConstraint; import net.sf.cpsolver.coursett.constraint.RoomConstraint; import net.sf.cpsolver.coursett.model.Lecture; import net.sf.cpsolver.coursett.model.Placement; import net.sf.cpsolver.coursett.model.RoomLocation; import net.sf.cpsolver.coursett.model.TimeLocation; import net.sf.cpsolver.coursett.model.TimetableModel; import net.sf.cpsolver.ifs.util.ToolBox; /** * @author Tomas Muller */ public class RoomReport implements Serializable { public static int[] sGroupSizes = new int[] {0, 10, 20, 40, 60, 80, 100, 150, 200, 400, Integer.MAX_VALUE}; private static final long serialVersionUID = 1L; private HashSet iGroups = new HashSet(); private Long iRoomType = null; private BitSet iSessionDays = null; private int iStartDayDayOfWeek = 0; private double iNrWeeks = 0.0; public RoomReport(TimetableModel model, BitSet sessionDays, int startDayDayOfWeek, Long roomType) { iSessionDays = sessionDays; iStartDayDayOfWeek = startDayDayOfWeek; iRoomType = roomType; // count number of weeks as a number of working days / 5 // (this is to avoid problems when the default date pattern does not contain Saturdays and/or Sundays) int dow = iStartDayDayOfWeek; int nrDays[] = new int[] {0, 0, 0, 0, 0, 0, 0}; for (int day = iSessionDays.nextSetBit(0); day < iSessionDays.length(); day++) { if (iSessionDays.get(day)) nrDays[dow]++; dow = (dow + 1) % 7; } iNrWeeks = 0.2 * ( nrDays[Constants.DAY_MON] + nrDays[Constants.DAY_TUE] + nrDays[Constants.DAY_WED] + nrDays[Constants.DAY_THU] + nrDays[Constants.DAY_FRI] ); for (int i=0;i<sGroupSizes.length-1;i++) { iGroups.add(new RoomAllocationGroup(sGroupSizes[i],sGroupSizes[i+1])); } for (RoomConstraint rc: model.getRoomConstraints()) { if (!ToolBox.equals(iRoomType,rc.getType())) continue; for (Iterator i=iGroups.iterator();i.hasNext();) { RoomAllocationGroup g = (RoomAllocationGroup)i.next(); g.add(rc); } } for (Lecture lecture: model.variables()) { for (Iterator i=iGroups.iterator();i.hasNext();) { RoomAllocationGroup g = (RoomAllocationGroup)i.next(); g.add(lecture); } } } public Set getGroups() { return iGroups; } public class RoomAllocationGroup implements Serializable { private static final long serialVersionUID = 1L; private int iMinRoomSize = 0; private int iMaxRoomSize = 0; private int iNrRooms = 0; private int iNrRoomsThisSizeOrBigger = 0; private double iSlotsUse = 0; private double iSlotsMustUse= 0; private double iSlotsMustUseThisSizeOrBigger= 0; private double iSlotsCanUse = 0; private int iLecturesUse = 0; private int iLecturesMustUse= 0; private int iLecturesMustUseThisSizeOrBigger= 0; private int iLecturesCanUse = 0; private int iRealMinRoomSize = 0; private int iRealMaxRoomSize = 0; private int iLecturesShouldUse = 0; private double iSlotsShouldUse = 0; public RoomAllocationGroup(int minSize, int maxSize) { iMinRoomSize = minSize; iMaxRoomSize = maxSize; iRealMinRoomSize = maxSize; iRealMaxRoomSize = minSize; } public int getMinRoomSize() { return iMinRoomSize; } public int getMaxRoomSize() { return iMaxRoomSize; } public int getActualMinRoomSize() { return iRealMinRoomSize; } public int getActualMaxRoomSize() { return iRealMaxRoomSize; } public int getNrRooms() { return iNrRooms; } public int getNrRoomsThisSizeOrBigger() { return iNrRoomsThisSizeOrBigger; } public double getSlotsUse() { return iSlotsUse; } public double getSlotsCanUse() { return iSlotsCanUse; } public double getSlotsMustUse() { return iSlotsMustUse; } public double getSlotsMustUseThisSizeOrBigger() { return iSlotsMustUseThisSizeOrBigger; } public double getSlotsShouldUse() { return iSlotsShouldUse; } public int getLecturesUse() { return iLecturesUse; } public int getLecturesCanUse() { return iLecturesCanUse; } public int getLecturesMustUse() { return iLecturesMustUse; } public int getLecturesMustUseThisSizeOrBigger() { return iLecturesMustUseThisSizeOrBigger; } public int getLecturesShouldUse() { return iLecturesShouldUse; } public void add(RoomConstraint rc) { if (iMinRoomSize<=rc.getCapacity() && rc.getCapacity()<iMaxRoomSize) { iNrRooms++; iRealMinRoomSize = Math.min(iRealMinRoomSize,rc.getCapacity()); iRealMaxRoomSize = Math.max(iRealMaxRoomSize,rc.getCapacity()); } if (iMinRoomSize<=rc.getCapacity()) iNrRoomsThisSizeOrBigger++; } public void add(Lecture lecture) { if (lecture.getNrRooms()==0) return; boolean skip = false; if (lecture.canShareRoom()) { for (Iterator i=lecture.canShareRoomConstraints().iterator();i.hasNext();) { GroupConstraint gc = (GroupConstraint)i.next(); for (Lecture other: gc.variables()) { if (other.getClassId().compareTo(lecture.getClassId())<0) skip=true; } } } if (skip) return; skip = true; boolean canUse = false, mustUse = true, mustUseThisSizeOrBigger = true; for (RoomLocation r: lecture.roomLocations()) { if (r.getRoomConstraint()==null) continue; if (PreferenceLevel.sProhibited.equals(PreferenceLevel.int2prolog(r.getPreference()))) continue; if (!ToolBox.equals(iRoomType,r.getRoomConstraint().getType())) { mustUse = false; mustUseThisSizeOrBigger = false; continue; } skip = false; if (iMinRoomSize<=r.getRoomSize() && r.getRoomSize()<iMaxRoomSize) canUse = true; else mustUse = false; if (r.getRoomSize()<iMinRoomSize) mustUseThisSizeOrBigger = false; } if (skip) return; boolean shouldUse = canUse && mustUseThisSizeOrBigger; if (canUse) { iSlotsCanUse += getSlotsAWeek(lecture.timeLocations()) * lecture.getNrRooms(); iLecturesCanUse += lecture.getNrRooms(); } if (mustUse) { iSlotsMustUse += getSlotsAWeek(lecture.timeLocations()) * lecture.getNrRooms(); iLecturesMustUse += lecture.getNrRooms(); } if (mustUseThisSizeOrBigger) { iSlotsMustUseThisSizeOrBigger += getSlotsAWeek(lecture.timeLocations()) * lecture.getNrRooms(); iLecturesMustUseThisSizeOrBigger += lecture.getNrRooms(); } if (shouldUse) { iSlotsShouldUse += getSlotsAWeek(lecture.timeLocations()) * lecture.getNrRooms(); iLecturesShouldUse += lecture.getNrRooms(); } int use = 0; if (lecture.getAssignment()!=null) { Placement placement = (Placement)lecture.getAssignment(); if (placement.isMultiRoom()) { for (RoomLocation r: placement.getRoomLocations()) { if (r.getRoomConstraint()==null) continue; if (!ToolBox.equals(iRoomType,r.getRoomConstraint().getType())) continue; if (iMinRoomSize<=r.getRoomSize() && r.getRoomSize()<iMaxRoomSize) use++; } } else { if (placement.getRoomLocation().getRoomConstraint()!=null && ToolBox.equals(iRoomType,placement.getRoomLocation().getRoomConstraint().getType()) && iMinRoomSize<=placement.getRoomLocation().getRoomSize() && placement.getRoomLocation().getRoomSize()<iMaxRoomSize ) use++; } if (use>0) { TimeLocation t = placement.getTimeLocation(); iSlotsUse += getSlotsAWeek(t) * use; iLecturesUse += use; } } } public double getSlotsAWeek(Collection<TimeLocation> times) { if (times.isEmpty()) return 0; double totalHoursAWeek = 0; for (TimeLocation t: times) totalHoursAWeek += getSlotsAWeek(t); return ((double)totalHoursAWeek) / times.size(); } public double getSlotsAWeek(TimeLocation t) { return getAverageDays(t) * t.getNrSlotsPerMeeting(); } public double getAverageDays(TimeLocation t) { int nrDays = 0; int dow = iStartDayDayOfWeek; for (int day = iSessionDays.nextSetBit(0); day < iSessionDays.length(); day++) { if (iSessionDays.get(day) && t.getWeekCode().get(day) && (t.getDayCode() & Constants.DAY_CODES[dow]) != 0) nrDays++; dow = (dow + 1) % 7; } return ((double)nrDays) / iNrWeeks; } } }
package com.intellij.psi.util; import com.intellij.aspects.psi.PsiIdPattern; import com.intellij.aspects.psi.PsiTypeNamePattern; import com.intellij.aspects.psi.PsiTypeNamePatternElement; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileTypes.StdFileTypes; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.infos.CandidateInfo; import com.intellij.psi.jsp.JspFile; import com.intellij.psi.meta.PsiMetaData; import com.intellij.psi.meta.PsiMetaOwner; import com.intellij.psi.tree.IElementType; import com.intellij.util.IncorrectOperationException; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.regex.Pattern; public final class PsiUtil { private static final Logger LOG = Logger.getInstance("#com.intellij.psi.util.PsiUtil"); public static final int ACCESS_LEVEL_PUBLIC = 4; public static final int ACCESS_LEVEL_PROTECTED = 3; public static final int ACCESS_LEVEL_PACKAGE_LOCAL = 2; public static final int ACCESS_LEVEL_PRIVATE = 1; public static final Key<Boolean> VALID_VOID_TYPE_IN_CODE_FRAGMENT = Key.create("VALID_VOID_TYPE_IN_CODE_FRAGMENT"); private PsiUtil() {} public static boolean isOnAssignmentLeftHand(PsiExpression expr) { PsiElement parent = expr.getParent(); return parent instanceof PsiAssignmentExpression && expr.equals(((PsiAssignmentExpression) parent).getLExpression()); } public static boolean isAccessibleFromPackage(PsiModifierListOwner element, PsiPackage aPackage) { if (element.hasModifierProperty(PsiModifier.PUBLIC)) return true; if (element.hasModifierProperty(PsiModifier.PRIVATE)) return false; return element.getManager().isInPackage(element, aPackage); } public static boolean isAccessedForWriting(PsiExpression expr) { if (isOnAssignmentLeftHand(expr)) return true; PsiElement parent = expr.getParent(); if (parent instanceof PsiPrefixExpression) { PsiJavaToken sign = ((PsiPrefixExpression) parent).getOperationSign(); IElementType tokenType = sign.getTokenType(); return tokenType == JavaTokenType.PLUSPLUS || tokenType == JavaTokenType.MINUSMINUS; } else if (parent instanceof PsiPostfixExpression) { PsiJavaToken sign = ((PsiPostfixExpression) parent).getOperationSign(); IElementType tokenType = sign.getTokenType(); return tokenType == JavaTokenType.PLUSPLUS || tokenType == JavaTokenType.MINUSMINUS; } else { return false; } } public static boolean isAccessedForReading(PsiExpression expr) { PsiElement parent = expr.getParent(); if (parent instanceof PsiAssignmentExpression && expr.equals(((PsiAssignmentExpression) parent).getLExpression())) { return ((PsiAssignmentExpression)parent).getOperationSign().getTokenType() != JavaTokenType.EQ; } else { return true; } } public static boolean isAccessible(PsiMember member, PsiElement place, PsiClass accessObjectClass) { return place.getManager().getResolveHelper().isAccessible(member, place, accessObjectClass); } public static ResolveResult getAccessObjectClass(PsiExpression accessObject) { if (accessObject instanceof PsiSuperExpression) { final PsiJavaCodeReferenceElement qualifier = ((PsiSuperExpression) accessObject).getQualifier(); if (qualifier != null) { // E.super.f final ResolveResult result = qualifier.advancedResolve(false); final PsiElement resolve = result.getElement(); if (resolve instanceof PsiClass) { final PsiClass psiClass; final PsiSubstitutor substitutor; if (resolve instanceof PsiTypeParameter) { final PsiClassType parameterType = resolve.getManager().getElementFactory().createType((PsiTypeParameter) resolve); final PsiType superType = result.getSubstitutor().substitute(parameterType); if (superType instanceof PsiArrayType) { return resolve.getManager().getElementFactory().getArrayClassType(((PsiArrayType)superType).getComponentType()).resolveGenerics(); } else if (superType instanceof PsiClassType) { final PsiClassType type = (PsiClassType)superType; substitutor = type.resolveGenerics().getSubstitutor(); psiClass = type.resolve(); } else { psiClass = null; substitutor = PsiSubstitutor.EMPTY; } } else { psiClass = (PsiClass) resolve; substitutor = PsiSubstitutor.EMPTY; } if (psiClass != null) { return new CandidateInfo(psiClass, substitutor); } else return ResolveResult.EMPTY; } return ResolveResult.EMPTY; } else { PsiElement scope = accessObject.getContext(); PsiElement lastParent = accessObject; while (scope != null) { if (scope instanceof PsiClass) { if (scope instanceof PsiAnonymousClass) { if (lastParent instanceof PsiExpressionList) { lastParent = scope; scope = scope.getContext(); continue; } } return new CandidateInfo(scope, PsiSubstitutor.EMPTY); } lastParent = scope; scope = scope.getContext(); } return ResolveResult.EMPTY; } } else { PsiType type = accessObject.getType(); if (!(type instanceof PsiClassType || type instanceof PsiArrayType)) return ResolveResult.EMPTY; return PsiUtil.resolveGenericsClassInType(type); } } public static boolean isConstantExpression(PsiExpression expression) { if (expression == null) return false; IsConstantExpressionVisitor visitor = new IsConstantExpressionVisitor(); expression.accept(visitor); return visitor.myIsConstant; } // todo: move to PsiThrowsList? public static void addException(PsiMethod method, String exceptionFQName) throws IncorrectOperationException { PsiClass exceptionClass = method.getManager().findClass(exceptionFQName, method.getResolveScope()); addException(method, exceptionClass, exceptionFQName); } public static void addException(PsiMethod method, PsiClass exceptionClass) throws IncorrectOperationException { addException(method, exceptionClass, exceptionClass.getQualifiedName()); } private static void addException(PsiMethod method, PsiClass exceptionClass, String exceptionName) throws IncorrectOperationException { PsiReferenceList throwsList = method.getThrowsList(); PsiJavaCodeReferenceElement[] refs = throwsList.getReferenceElements(); for (PsiJavaCodeReferenceElement ref : refs) { if (ref.isReferenceTo(exceptionClass)) return; PsiClass aClass = (PsiClass)ref.resolve(); if (exceptionClass != null && aClass != null) { if (aClass.isInheritor(exceptionClass, true)) { PsiElementFactory factory = method.getManager().getElementFactory(); PsiJavaCodeReferenceElement ref1; if (exceptionName != null) { ref1 = factory.createReferenceElementByFQClassName(exceptionName, method.getResolveScope()); } else { PsiClassType type = factory.createType(exceptionClass); ref1 = factory.createReferenceElementByType(type); } ref.replace(ref1); return; } else if (exceptionClass.isInheritor(aClass, true)) { return; } } } PsiElementFactory factory = method.getManager().getElementFactory(); PsiJavaCodeReferenceElement ref; if (exceptionName != null) { ref = factory.createReferenceElementByFQClassName(exceptionName, method.getResolveScope()); } else { PsiClassType type = factory.createType(exceptionClass); ref = factory.createReferenceElementByType(type); } throwsList.add(ref); } // todo: move to PsiThrowsList? public static void removeException(PsiMethod method, String exceptionClass) throws IncorrectOperationException { PsiJavaCodeReferenceElement[] refs = method.getThrowsList().getReferenceElements(); for (PsiJavaCodeReferenceElement ref : refs) { if (ref.getCanonicalText().equals(exceptionClass)) { ref.delete(); } } } public static boolean isVariableNameUnique(String name, PsiElement place) { PsiResolveHelper helper = place.getManager().getResolveHelper(); PsiVariable refVar = helper.resolveReferencedVariable(name, place); if (refVar != null) return false; return true; } /** * @deprecated Use {@link PsiManager#isInProject(com.intellij.psi.PsiElement)} */ public static boolean isInProject(PsiElement element) { return element.getManager().isInProject(element); } public static void updatePackageStatement(PsiFile file) throws IncorrectOperationException { if (!(file instanceof PsiJavaFile)) return; PsiManager manager = file.getManager(); PsiElementFactory factory = manager.getElementFactory(); PsiDirectory dir = file.getContainingDirectory(); PsiPackage aPackage = dir.getPackage(); if (aPackage == null) return; String packageName = aPackage.getQualifiedName(); PsiPackageStatement statement = ((PsiJavaFile) file).getPackageStatement(); if (statement != null) { if (packageName.length() > 0) { statement.getPackageReference().bindToElement(aPackage); } else { statement.delete(); } } else { if (packageName.length() > 0) { String text = "package " + packageName + ";"; String ext = StdFileTypes.JAVA.getDefaultExtension(); PsiJavaFile dummyFile = (PsiJavaFile) factory.createFileFromText("_Dummy_." + ext, text); statement = dummyFile.getPackageStatement(); if (statement == null) { throw new IncorrectOperationException(); } file.add(statement); } } } /** * @return enclosing outermost (method or class initializer) body but not higher than scope */ public static PsiElement getTopLevelEnclosingCodeBlock(PsiElement element, PsiElement scope) { PsiElement blockSoFar = null; while (element != null) { // variable can be defined in for loop initializer if (element instanceof PsiCodeBlock || element instanceof PsiForStatement || element instanceof PsiForeachStatement) { blockSoFar = element; } final PsiElement parent = element.getParent(); if (parent instanceof PsiMethod && parent.getParent() instanceof PsiClass && !isLocalOrAnonymousClass((PsiClass)parent.getParent())) break; if (parent instanceof PsiClassInitializer && !(parent.getParent() instanceof PsiAnonymousClass)) break; if (parent instanceof PsiField && ((PsiField) parent).getInitializer() == element) { blockSoFar = element; } if (element instanceof PsiClass && !isLocalOrAnonymousClass((PsiClass)element)) { break; } if (element instanceof JspFile) { return element; } if (element == scope) break; element = parent; } return blockSoFar; } public static boolean isLocalOrAnonymousClass(PsiClass psiClass) { return psiClass instanceof PsiAnonymousClass || isLocalClass(psiClass); } public static boolean isLocalClass(PsiClass psiClass) { PsiElement parent = psiClass.getParent(); return parent instanceof PsiDeclarationStatement && parent.getParent() instanceof PsiCodeBlock; } /** * @return codeblock topmost codeblock where variable makes sense */ public static PsiElement getVariableCodeBlock(PsiVariable variable, PsiElement context) { PsiElement codeBlock = null; if (variable instanceof PsiParameter) { PsiElement declarationScope = ((PsiParameter)variable).getDeclarationScope(); if (declarationScope instanceof PsiCatchSection) { codeBlock = ((PsiCatchSection)declarationScope).getCatchBlock(); } else if (declarationScope instanceof PsiForeachStatement) { codeBlock = (((PsiForeachStatement)declarationScope)).getBody(); } else if (declarationScope instanceof PsiMethod) { codeBlock = ((PsiMethod)declarationScope).getBody(); } } else if (variable instanceof PsiLocalVariable && variable.getParent() instanceof PsiForStatement) { return variable.getParent(); } else if (variable instanceof PsiField && context != null) { final PsiClass aClass = ((PsiField) variable).getContainingClass(); while (context != null && context.getParent() != aClass) { context = context.getParent(); } return context instanceof PsiMethod ? ((PsiMethod) context).getBody() : context instanceof PsiClassInitializer ? ((PsiClassInitializer) context).getBody() : null; } else { final PsiElement scope = variable.getParent() == null ? null : variable.getParent().getParent(); codeBlock = getTopLevelEnclosingCodeBlock(variable, scope); if (codeBlock != null && codeBlock.getParent() instanceof PsiSwitchStatement) codeBlock = codeBlock.getParent().getParent(); } return codeBlock; } public static boolean isIncrementDecrementOperation(PsiElement element) { if (element instanceof PsiPostfixExpression) { final IElementType sign = ((PsiPostfixExpression) element).getOperationSign().getTokenType(); if (sign == JavaTokenType.PLUSPLUS || sign == JavaTokenType.MINUSMINUS) return true; } else if (element instanceof PsiPrefixExpression) { final IElementType sign = ((PsiPrefixExpression) element).getOperationSign().getTokenType(); if (sign == JavaTokenType.PLUSPLUS || sign == JavaTokenType.MINUSMINUS) return true; } return false; } public static int getAccessLevel(PsiModifierList modifierList) { if (modifierList.hasModifierProperty(PsiModifier.PRIVATE)) { return ACCESS_LEVEL_PRIVATE; } else if (modifierList.hasModifierProperty(PsiModifier.PACKAGE_LOCAL)) { return ACCESS_LEVEL_PACKAGE_LOCAL; } else if (modifierList.hasModifierProperty(PsiModifier.PROTECTED)) { return ACCESS_LEVEL_PROTECTED; } else { return ACCESS_LEVEL_PUBLIC; } } public static String getAccessModifier(int accessLevel) { return accessLevel > accessModifiers.length ? null : accessModifiers[accessLevel - 1]; } private static final String[] accessModifiers = new String[]{ PsiModifier.PRIVATE, PsiModifier.PACKAGE_LOCAL, PsiModifier.PROTECTED, PsiModifier.PUBLIC }; public static PsiFile findRelativeFile(String uri, PsiElement base) { if (base instanceof PsiFile) { PsiFile baseFile = (PsiFile) base; if (baseFile.getOriginalFile() != null) return findRelativeFile(uri, baseFile.getOriginalFile()); VirtualFile file = VfsUtil.findRelativeFile(uri, baseFile.getVirtualFile()); if (file == null) return null; return base.getManager().findFile(file); } else if (base instanceof PsiDirectory) { PsiDirectory baseDir = (PsiDirectory) base; VirtualFile file = VfsUtil.findRelativeFile(uri, baseDir.getVirtualFile()); if (file == null) return null; return base.getManager().findFile(file); } return null; } public static PsiDirectory findRelativeDirectory(String uri, PsiElement base) { if (base instanceof PsiFile) { PsiFile baseFile = (PsiFile) base; if (baseFile.getOriginalFile() != null) return findRelativeDirectory(uri, baseFile.getOriginalFile()); VirtualFile file = VfsUtil.findRelativeFile(uri, baseFile.getVirtualFile()); if (file == null) return null; return base.getManager().findDirectory(file); } else if (base instanceof PsiDirectory) { PsiDirectory baseDir = (PsiDirectory) base; VirtualFile file = VfsUtil.findRelativeFile(uri, baseDir.getVirtualFile()); if (file == null) return null; return base.getManager().findDirectory(file); } return null; } /** * @return true if element specified is statement or expression statement. see JLS 14.5-14.8 */ public static boolean isStatement(PsiElement element) { PsiElement parent = element.getParent(); if (element instanceof PsiExpressionListStatement) { // statement list allowed in for() init or update only if (!(parent instanceof PsiForStatement)) return false; final PsiForStatement forStatement = (PsiForStatement)parent; if (!(element == forStatement.getInitialization() || element == forStatement.getUpdate())) return false; final PsiExpressionList expressionList = ((PsiExpressionListStatement) element).getExpressionList(); final PsiExpression[] expressions = expressionList.getExpressions(); for (PsiExpression expression : expressions) { if (!isStatement(expression)) return false; } return true; } else if (element instanceof PsiExpressionStatement) { final PsiExpression expression = ((PsiExpressionStatement) element).getExpression(); if (expression == null) return false; return isStatement(expression); } if (element instanceof PsiDeclarationStatement) { if (parent instanceof PsiCodeBlock) return true; if (parent instanceof PsiCodeFragment) return true; if (!(parent instanceof PsiForStatement) || ((PsiForStatement)parent).getBody() == element) { return false; } } if (element instanceof PsiStatement) return true; if (element instanceof PsiAssignmentExpression) return true; if (isIncrementDecrementOperation(element)) return true; if (element instanceof PsiMethodCallExpression) return true; if (element instanceof PsiNewExpression) { return !(((PsiNewExpression) element).getType() instanceof PsiArrayType); } if (element instanceof PsiCodeBlock) return true; return false; } public static PsiElement getEnclosingStatement(PsiElement element) { while (element != null) { if (element.getParent() instanceof PsiCodeBlock) return element; element = element.getParent(); } return null; } public static PsiElement getElementInclusiveRange(PsiElement scope, TextRange range) { PsiElement psiElement = scope.findElementAt(range.getStartOffset()); while (!psiElement.getTextRange().contains(range)) { if (psiElement == scope) return null; psiElement = psiElement.getParent(); } return psiElement; } private static final Key<Pattern> REGEXP_IN_TYPE_NAME_PATTERN = Key.create("REGEXP_IN_TYPE_NAME_PATTERN"); public static Pattern convertToRegexp(PsiIdPattern idPattern) { Pattern result = idPattern.getUserData(REGEXP_IN_TYPE_NAME_PATTERN); if (result == null) { StringBuffer buf = new StringBuffer(); convertToRegexp(idPattern, buf); result = Pattern.compile(buf.toString()); idPattern.putUserData(REGEXP_IN_TYPE_NAME_PATTERN, result); } return result; } public static Pattern convertToRegexp(PsiTypeNamePattern typeNamePattern) { Pattern result = typeNamePattern.getUserData(REGEXP_IN_TYPE_NAME_PATTERN); if (result == null) { StringBuffer regexp; PsiTypeNamePatternElement[] namePatternElements = typeNamePattern.getNamePatternElements(); regexp = new StringBuffer(); boolean doubleDot = false; for (int i = 0; i < namePatternElements.length; i++) { if (i > 0 && !doubleDot) { regexp.append("\\."); // dot } PsiTypeNamePatternElement typePatternElement = namePatternElements[i]; PsiIdPattern pattern = typePatternElement.getPattern(); if (pattern != null) { convertToRegexp(pattern, regexp); doubleDot = false; } else { regexp.append("(.*\\.)?"); // Empty string or any string that ends up with dot. doubleDot = true; } } result = Pattern.compile(regexp.toString()); typeNamePattern.putUserData(REGEXP_IN_TYPE_NAME_PATTERN, result); } return result; } private static void convertToRegexp(PsiIdPattern pattern, StringBuffer regexp) { final String canonicalText = pattern.getCanonicalText(); for (int j = 0; j < canonicalText.length(); j++) { final char c = canonicalText.charAt(j); if (c == '*') { regexp.append("[^\\.]*"); } else { regexp.append(c); } } } public static PsiClass resolveClassInType(PsiType type) { if (type instanceof PsiClassType) { return ((PsiClassType) type).resolve(); } if (type instanceof PsiArrayType) { return resolveClassInType(((PsiArrayType) type).getComponentType()); } return null; } public static PsiClassType.ClassResolveResult resolveGenericsClassInType(PsiType type) { if (type instanceof PsiClassType) { final PsiClassType classType = (PsiClassType) type; return classType.resolveGenerics(); } if (type instanceof PsiArrayType) { return resolveGenericsClassInType(((PsiArrayType) type).getComponentType()); } return PsiClassType.ClassResolveResult.EMPTY; } public static PsiType convertAnonymousToBaseType(PsiType type) { PsiClass psiClass = resolveClassInType(type); if (psiClass instanceof PsiAnonymousClass) { int dims = type.getArrayDimensions(); type = ((PsiAnonymousClass) psiClass).getBaseClassType(); while (dims != 0) { type = type.createArrayType(); dims } } return type; } /** @return name for element using element structure info * TODO: Extend functionality for XML/JSP */ public static String getName(PsiElement element) { String name = null; if (element instanceof PsiMetaOwner) { final PsiMetaData data = ((PsiMetaOwner) element).getMetaData(); if (data != null) name = data.getName(element); } if (name == null && element instanceof PsiNamedElement) { name = ((PsiNamedElement) element).getName(); } return name; } public static boolean isApplicable(PsiMethod method, PsiSubstitutor substitutorForMethod, PsiExpressionList argList) { PsiExpression[] args = argList == null ? PsiExpression.EMPTY_ARRAY : argList.getExpressions(); final PsiParameter[] parms = method.getParameterList().getParameters(); if (!method.isVarArgs()) { if (args == null || args.length != parms.length) { return false; } for (int i = 0; i < args.length; i++) { final PsiExpression arg = args[i]; final PsiType type = arg.getType(); if (type == null) return false; final PsiType parmType = parms[i].getType(); final PsiType substitutedParmType = substitutorForMethod.substituteAndCapture(parmType); if (!TypeConversionUtil.isAssignable(substitutedParmType, type)) { return false; } } } else { if (args == null || args.length < parms.length - 1) { return false; } PsiParameter lastParameter = parms[parms.length - 1]; PsiType lastParmType = lastParameter.getType(); if (!(lastParmType instanceof PsiArrayType)) return false; lastParmType = substitutorForMethod.substituteAndCapture(lastParmType); if (lastParameter.isVarArgs()) { for (int i = 0; i < parms.length - 1; i++) { PsiParameter parm = parms[i]; if (parm.isVarArgs()) return false; final PsiExpression arg = args[i]; final PsiType argType = arg.getType(); if (argType == null) return false; final PsiType parmType = parms[i].getType(); final PsiType substitutedParmType = substitutorForMethod.substituteAndCapture(parmType); if (!TypeConversionUtil.isAssignable(substitutedParmType, argType)) { return false; } } if (args.length == parms.length) { //call with array as vararg parameter PsiType lastArgType = args[args.length - 1].getType(); if (lastArgType != null && TypeConversionUtil.isAssignable(lastParmType, lastArgType)) return true; } lastParmType = ((PsiArrayType)lastParmType).getComponentType(); for (int i = parms.length - 1; i < args.length; i++) { PsiType argType = args[i].getType(); if (argType == null || !TypeConversionUtil.isAssignable(lastParmType, argType)) { return false; } } } else { return false; } } return true; } public static boolean equalOnClass(PsiSubstitutor s1, PsiSubstitutor s2, PsiClass aClass) { return equalOnEquivalentClasses(s1, aClass, s2, aClass); } public static boolean equalOnEquivalentClasses(PsiSubstitutor s1, PsiClass aClass, PsiSubstitutor s2, PsiClass bClass) { // assume generic class equals to non-generic if (aClass.hasTypeParameters() != bClass.hasTypeParameters()) return true; final PsiTypeParameter[] typeParameters1 = aClass.getTypeParameters(); final PsiTypeParameter[] typeParameters2 = bClass.getTypeParameters(); if (typeParameters1.length != typeParameters2.length) return false; for (int i = 0; i < typeParameters1.length; i++) { if (!Comparing.equal(s1.substitute(typeParameters1[i]), s2.substitute(typeParameters2[i]))) return false; } if (aClass.hasModifierProperty(PsiModifier.STATIC)) return true; final PsiClass containingClass1 = aClass.getContainingClass(); final PsiClass containingClass2 = bClass.getContainingClass(); if (containingClass1 != null && containingClass2 != null) { return equalOnEquivalentClasses(s1, containingClass1, s2, containingClass2); } return containingClass1 == null && containingClass2 == null; } /** * JLS 15.28 */ public static boolean isCompileTimeConstant(final PsiField field) { return field.hasModifierProperty(PsiModifier.FINAL) && (TypeConversionUtil.isPrimitiveAndNotNull(field.getType()) || field.getType().equalsToText("java.lang.String")) && field.hasInitializer() && isConstantExpression(field.getInitializer()); } public static boolean allMethodsHaveSameSignature(PsiMethod[] methods) { if (methods.length == 0) return true; final MethodSignature methodSignature = methods[0].getSignature(PsiSubstitutor.EMPTY); for (int i = 1; i < methods.length; i++) { PsiMethod method = methods[i]; if (!methodSignature.equals(method.getSignature(PsiSubstitutor.EMPTY))) return false; } return true; } public static PsiExpression deparenthesizeExpression(PsiExpression rExpression) { if (rExpression instanceof PsiParenthesizedExpression) { return deparenthesizeExpression( ((PsiParenthesizedExpression)rExpression).getExpression()); } if (rExpression instanceof PsiTypeCastExpression) { return deparenthesizeExpression( ((PsiTypeCastExpression)rExpression).getOperand()); } return rExpression; } /** * Checks whether given class is inner (as opposed to nested) * * @param aClass * @return */ public static boolean isInnerClass(PsiClass aClass) { return !aClass.hasModifierProperty(PsiModifier.STATIC) && aClass.getContainingClass() != null; } public static PsiElement findModifierInList(final PsiModifierList modifierList, String modifier) { final PsiElement[] children = modifierList.getChildren(); for (PsiElement child : children) { if (child.getText().equals(modifier)) return child; } return null; } public static boolean isLoopStatement(PsiElement element) { return element instanceof PsiWhileStatement || element instanceof PsiForStatement || element instanceof PsiDoWhileStatement || element instanceof PsiForeachStatement; } public static PsiClass getTopLevelClass(PsiElement element) { final PsiFile file = element.getContainingFile(); if (file instanceof PsiJavaFile) { final PsiClass[] classes = ((PsiJavaFile)file).getClasses(); for (PsiClass aClass : classes) { if (PsiTreeUtil.isAncestor(aClass, element, false)) return aClass; } } return null; } /** * @return element with static modifier enclosing place and enclosed by aClass (if not null) */ public static PsiModifierListOwner getEnclosingStaticElement(PsiElement place, PsiClass aClass) { LOG.assertTrue(aClass == null || PsiTreeUtil.isAncestor(aClass, place, false)); PsiElement parent = place; while (parent != aClass) { if (parent instanceof PsiFile) break; if (parent instanceof PsiModifierListOwner && ((PsiModifierListOwner)parent).hasModifierProperty(PsiModifier.STATIC)) { return (PsiModifierListOwner)parent; } parent = parent.getParent(); } return null; } public static PsiType getTypeByPsiElement(final PsiElement element) { if (element instanceof PsiVariable) { return ((PsiVariable)element).getType(); } else if (element instanceof PsiMethod) return ((PsiMethod)element).getReturnType(); return null; } private static class TypeParameterIterator implements Iterator<PsiTypeParameter> { private int myIndex; private PsiTypeParameterListOwner myCurrentOwner; private boolean myNextObtained; private PsiTypeParameter[] myCurrentParams; private PsiTypeParameter myNext; private TypeParameterIterator(PsiTypeParameterListOwner owner) { myCurrentOwner = owner; obtainCurrentParams(owner); myNextObtained = false; } private void obtainCurrentParams(PsiTypeParameterListOwner owner) { myCurrentParams = owner.getTypeParameters(); myIndex = myCurrentParams.length - 1; } public boolean hasNext() { nextElement(); return myNext != null; } public PsiTypeParameter next() { nextElement(); if (myNext == null) throw new NoSuchElementException(); myNextObtained = false; return myNext; } public void remove() { throw new UnsupportedOperationException("TypeParameterIterator.remove"); } private void nextElement() { if (myNextObtained) return; if (myIndex >= 0) { myNext = myCurrentParams[myIndex myNextObtained = true; return; } if (myCurrentOwner.hasModifierProperty(PsiModifier.STATIC) || myCurrentOwner.getContainingClass() == null) { myNext = null; myNextObtained = true; return; } myCurrentOwner = myCurrentOwner.getContainingClass(); obtainCurrentParams(myCurrentOwner); nextElement(); } } /** * Returns iterator of type parameters visible in owner. Type parameters are iterated in * inner-to-outer, right-to-left order. * @param owner * @return */ public static Iterator<PsiTypeParameter> typeParametersIterator(PsiTypeParameterListOwner owner) { return new TypeParameterIterator(owner); } public static boolean canBeOverriden(PsiMethod method) { PsiClass parentClass = method.getContainingClass(); if (parentClass == null) return false; if (method.isConstructor()) return false; if (method.hasModifierProperty(PsiModifier.STATIC)) return false; if (method.hasModifierProperty(PsiModifier.FINAL)) return false; if (method.hasModifierProperty(PsiModifier.PRIVATE)) return false; if (parentClass instanceof PsiAnonymousClass) return false; if (parentClass.hasModifierProperty(PsiModifier.FINAL)) return false; return true; } public static PsiElement[] mapElements(CandidateInfo[] candidates) { PsiElement[] result = new PsiElement[candidates.length]; for (int i = 0; i < candidates.length; i++) { result[i] = candidates[i].getElement(); } return result; } public static boolean hasErrorElementChild(PsiElement element) { for (PsiElement child = element.getFirstChild(); child != null; child = child.getNextSibling()) { if (child instanceof PsiErrorElement) return true; } return false; } public static PsiMember findEnclosingConstructorOrInitializer(PsiElement expression) { PsiElement parent = PsiTreeUtil.getParentOfType(expression, new Class[]{PsiClassInitializer.class, PsiMethod.class}); if (parent instanceof PsiMethod && !((PsiMethod)parent).isConstructor()) return null; return (PsiMember)parent; } public static boolean checkName(PsiElement element, String name) { if (element instanceof PsiMetaOwner) { final PsiMetaData data = ((PsiMetaOwner) element).getMetaData(); if (data != null) return name.equals(data.getName(element)); } if (element instanceof PsiNamedElement) { return name.equals(((PsiNamedElement) element).getName()); } return false; } public static boolean isInCovariantPosition(PsiExpression expression) { return isAccessedForWriting(expression) || isArrayExpressionInSelector(expression); } private static boolean isArrayExpressionInSelector(PsiExpression expression) { return expression.getParent() instanceof PsiArrayAccessExpression && ((PsiArrayAccessExpression)expression.getParent()).getArrayExpression() == expression; } public static boolean isRawSubstitutor (PsiTypeParameterListOwner owner, PsiSubstitutor substitutor) { final Iterator<PsiTypeParameter> iterator = PsiUtil.typeParametersIterator(owner); while (iterator.hasNext()) { PsiTypeParameter parameter = iterator.next(); if (substitutor.substitute(parameter) == null) return true; } return false; } public static boolean isUnderPsiRoot(PsiFile root, PsiElement element) { PsiElement[] psiRoots = root.getPsiRoots(); for (PsiElement psiRoot : psiRoots) { if (PsiTreeUtil.isAncestor(psiRoot, element, false)) return true; } return false; } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:18-05-27"); this.setApiVersion("3.3.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:19-09-01"); this.setApiVersion("15.6.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:18-04-25"); this.setApiVersion("3.3.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platforms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:21-11-03"); this.setApiVersion("17.12.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:18-10-25"); this.setApiVersion("14.7.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:19-10-29"); this.setApiVersion("15.9.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:20-02-21"); this.setApiVersion("15.17.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platforms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:22-10-17"); this.setApiVersion("18.16.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param language language */ public void setLanguage(String language){ this.requestConfiguration.put("language", language); } /** * language * * @return String */ public String getLanguage(){ if(this.requestConfiguration.containsKey("language")){ return(String) this.requestConfiguration.get("language"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:20-11-20"); this.setApiVersion("16.11.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:19-10-05"); this.setApiVersion("15.8.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:20-11-29"); this.setApiVersion("16.12.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:20-01-22"); this.setApiVersion("15.15.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platforms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:21-12-28"); this.setApiVersion("17.16.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
package com.plattysoft.leonids; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.Timer; import java.util.TimerTask; import com.plattysoft.leonids.initializers.AccelerationInitializer; import com.plattysoft.leonids.initializers.ParticleInitializer; import com.plattysoft.leonids.initializers.RotationInitiazer; import com.plattysoft.leonids.initializers.RotationSpeedInitializer; import com.plattysoft.leonids.initializers.ScaleInitializer; import com.plattysoft.leonids.initializers.SpeeddByComponentsInitializer; import com.plattysoft.leonids.initializers.SpeeddModuleAndRangeInitializer; import com.plattysoft.leonids.modifiers.AlphaModifier; import com.plattysoft.leonids.modifiers.ParticleModifier; import android.animation.Animator; import android.animation.Animator.AnimatorListener; import android.animation.ValueAnimator; import android.animation.ValueAnimator.AnimatorUpdateListener; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.drawable.AnimationDrawable; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.util.DisplayMetrics; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.view.animation.Interpolator; import android.view.animation.LinearInterpolator; public class ParticleSystem { private static final long TIMMERTASK_INTERVAL = 50; private ViewGroup mParentView; private int mMaxParticles; private Random mRandom; private ParticleField mDrawingView; private ArrayList<Particle> mParticles; private ArrayList<Particle> mActiveParticles; private long mTimeToLive; private long mCurrentTime = 0; private float mParticlesPerMilisecond; private int mActivatedParticles; private long mEmitingTime; private List<ParticleModifier> mModifiers; private List<ParticleInitializer> mInitializers; private ValueAnimator mAnimator; private Timer mTimer; private float mDpToPxScale; private int[] mParentLocation; private int mEmiterXMin; private int mEmiterXMax; private int mEmiterYMin; private int mEmiterYMax; private ParticleSystem(Activity a, int maxParticles, long timeToLive) { mRandom = new Random(); mParentView = (ViewGroup) a.findViewById(android.R.id.content); mModifiers = new ArrayList<ParticleModifier>(); mInitializers = new ArrayList<ParticleInitializer>(); mMaxParticles = maxParticles; // Create the particles mActiveParticles = new ArrayList<Particle>(); mParticles = new ArrayList<Particle> (); mTimeToLive = timeToLive; mParentLocation = new int[2]; mParentView.getLocationInWindow(mParentLocation); } /** * Creates a particle system with the given parameters * * @param a The parent activity * @param maxParticles The maximum number of particles * @param drawableRedId The drawable resource to use as particle (supports Bitmaps and Animations) * @param timeToLive The time to live for the particles */ public ParticleSystem(Activity a, int maxParticles, int drawableRedId, long timeToLive) { this(a, maxParticles, a.getResources().getDrawable(drawableRedId), timeToLive); } /** * Utility constructor that receives a Drawable * * @param a The parent activity * @param maxParticles The maximum number of particles * @param drawable The drawable to use as particle (supports Bitmaps and Animations) * @param timeToLive The time to live for the particles */ public ParticleSystem(Activity a, int maxParticles, Drawable drawable, long timeToLive) { this(a, maxParticles, timeToLive); if (drawable instanceof BitmapDrawable) { Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap(); for (int i=0; i<mMaxParticles; i++) { mParticles.add (new Particle (bitmap)); } } else if (drawable instanceof AnimationDrawable) { AnimationDrawable animation = (AnimationDrawable) drawable; for (int i=0; i<mMaxParticles; i++) { mParticles.add (new AnimatedParticle (animation)); } } else { // Not supported, no particles are being created } DisplayMetrics displayMetrics = a.getResources().getDisplayMetrics(); mDpToPxScale = (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT); } public float dpToPx(float dp) { return dp * mDpToPxScale; } /** * Utility constructor that receives a Bitmap * * @param a The parent activity * @param maxParticles The maximum number of particles * @param bitmap The bitmap to use as particle * @param timeToLive The time to live for the particles */ public ParticleSystem(Activity a, int maxParticles, Bitmap bitmap, long timeToLive) { this(a, maxParticles, timeToLive); for (int i=0; i<mMaxParticles; i++) { mParticles.add (new Particle (bitmap)); } } /** * Utility constructor that receives an AnimationDrawble * * @param a The parent activity * @param maxParticles The maximum number of particles * @param animation The animation to use as particle * @param timeToLive The time to live for the particles */ public ParticleSystem(Activity a, int maxParticles, AnimationDrawable animation, long timeToLive) { this(a, maxParticles, timeToLive); // Create the particles for (int i=0; i<mMaxParticles; i++) { mParticles.add (new AnimatedParticle (animation)); } } /** * Adds a modifier to the Particle system, it will be executed on each update. * * @param modifier * @return */ public ParticleSystem addModifier(ParticleModifier modifier) { mModifiers.add(modifier); return this; } public ParticleSystem setSpeedRange(float speedMin, float speedMax) { mInitializers.add(new SpeeddModuleAndRangeInitializer(dpToPx(speedMin), dpToPx(speedMax), 0, 360)); return this; } public ParticleSystem setSpeedModuleAndAngleRange(float speedMin, float speedMax, int minAngle, int maxAngle) { mInitializers.add(new SpeeddModuleAndRangeInitializer(dpToPx(speedMin), dpToPx(speedMax), minAngle, maxAngle)); return this; } public ParticleSystem setSpeedByComponentsRange(float speedMinX, float speedMaxX, float speedMinY, float speedMaxY) { mInitializers.add(new SpeeddByComponentsInitializer(dpToPx(speedMinX), dpToPx(speedMaxX), dpToPx(speedMinY), dpToPx(speedMaxY))); return this; } public ParticleSystem setInitialRotationRange (int minAngle, int maxAngle) { mInitializers.add(new RotationInitiazer(minAngle, maxAngle)); return this; } public ParticleSystem setScaleRange(float minScale, float maxScale) { mInitializers.add(new ScaleInitializer(minScale, maxScale)); return this; } public ParticleSystem setRotationSpeed(float rotationSpeed) { mInitializers.add(new RotationSpeedInitializer(rotationSpeed, rotationSpeed)); return this; } public ParticleSystem setRotationSpeedRange(float minRotationSpeed, float maxRotationSpeed) { mInitializers.add(new RotationSpeedInitializer(minRotationSpeed, maxRotationSpeed)); return this; } public ParticleSystem setAccelerationModuleAndAndAngleRange(float minAcceleration, float maxAcceleration, int minAngle, int maxAngle) { mInitializers.add(new AccelerationInitializer(dpToPx(minAcceleration), dpToPx(maxAcceleration), minAngle, maxAngle)); return this; } public ParticleSystem setAcceleration(float acceleration, int angle) { mInitializers.add(new AccelerationInitializer(acceleration, acceleration, angle, angle)); return this; } public ParticleSystem setParentViewGroup(ViewGroup viewGroup) { mParentView = viewGroup; return this; } public ParticleSystem setStartTime(int time) { mCurrentTime = time; return this; } /** * Configures a fade out for the particles when they disappear * * @param duration fade out duration in miliseconds * @param interpolator the interpolator for the fade out (default is linear) */ public ParticleSystem setFadeOut(long milisecondsBeforeEnd, Interpolator interpolator) { mModifiers.add(new AlphaModifier(255, 0, mTimeToLive-milisecondsBeforeEnd, mTimeToLive, interpolator)); return this; } /** * Configures a fade out for the particles when they disappear * * @param duration fade out duration in miliseconds */ public ParticleSystem setFadeOut(long duration) { return setFadeOut(duration, new LinearInterpolator()); } /** * Starts emiting particles from a specific view. If at some point the number goes over the amount of particles availabe on create * no new particles will be created * * @param emiter View from which center the particles will be emited * @param gravity Which position among the view the emission takes place * @param particlesPerSecond Number of particles per second that will be emited (evenly distributed) * @param timeToLive miliseconds the particles will be displayed * @param emitingTime time the emiter will be emiting particles */ public void emitWithGravity (View emiter, int gravity, int particlesPerSecond, int emitingTime) { // Setup emiter configureEmiter(emiter, gravity); startEmiting(particlesPerSecond, emitingTime); } /** * Starts emiting particles from a specific view. If at some point the number goes over the amount of particles availabe on create * no new particles will be created * * @param emiter View from which center the particles will be emited * @param particlesPerSecond Number of particles per second that will be emited (evenly distributed) * @param timeToLive miliseconds the particles will be displayed * @param emitingTime time the emiter will be emiting particles */ public void emit (View emiter, int particlesPerSecond, int emitingTime) { emitWithGravity(emiter, Gravity.CENTER, particlesPerSecond, emitingTime); } /** * Starts emiting particles from a specific view. If at some point the number goes over the amount of particles availabe on create * no new particles will be created * * @param emiter View from which center the particles will be emited * @param particlesPerSecond Number of particles per second that will be emited (evenly distributed) */ public void emit (View emiter, int particlesPerSecond) { // Setup emiter emitWithGravity(emiter, Gravity.CENTER, particlesPerSecond); } /** * Starts emiting particles from a specific view. If at some point the number goes over the amount of particles availabe on create * no new particles will be created * * @param emiter View from which center the particles will be emited * @param gravity Which position among the view the emission takes place * @param particlesPerSecond Number of particles per second that will be emited (evenly distributed) */ public void emitWithGravity (View emiter, int gravity, int particlesPerSecond) { // Setup emiter configureEmiter(emiter, gravity); startEmiting(particlesPerSecond); } private void startEmiting(int particlesPerSecond) { mActivatedParticles = 0; mParticlesPerMilisecond = particlesPerSecond/1000f; // Add a full size view to the parent view mDrawingView = new ParticleField(mParentView.getContext()); mParentView.addView(mDrawingView); mEmitingTime = -1; // Meaning infinite mDrawingView.setParticles (mActiveParticles); updateParticlesBeforeStartTime(particlesPerSecond); mTimer = new Timer(); mTimer.schedule(new TimerTask() { @Override public void run() { onUpdate(mCurrentTime); mCurrentTime += TIMMERTASK_INTERVAL; } }, 0, TIMMERTASK_INTERVAL); } public void emit (int emitterX, int emitterY, int particlesPerSecond, int emitingTime) { configureEmiter(emitterX, emitterY); startEmiting(particlesPerSecond, emitingTime); } private void configureEmiter(int emitterX, int emitterY) { // We configure the emiter based on the window location to fix the offset of action bar if present mEmiterXMin = emitterX - mParentLocation[0]; mEmiterXMax = mEmiterXMin; mEmiterYMin = emitterY - mParentLocation[1]; mEmiterYMax = mEmiterYMin; } private void startEmiting(int particlesPerSecond, int emitingTime) { mActivatedParticles = 0; mParticlesPerMilisecond = particlesPerSecond/1000f; // Add a full size view to the parent view mDrawingView = new ParticleField(mParentView.getContext()); mParentView.addView(mDrawingView); mDrawingView.setParticles (mActiveParticles); updateParticlesBeforeStartTime(particlesPerSecond); mEmitingTime = emitingTime; startAnimator(new LinearInterpolator(), emitingTime+mTimeToLive); } public void emit (int emitterX, int emitterY, int particlesPerSecond) { configureEmiter(emitterX, emitterY); startEmiting(particlesPerSecond); } public void updateEmitPoint (int emitterX, int emitterY) { configureEmiter(emitterX, emitterY); } /** * Launches particles in one Shot * * @param emiter View from which center the particles will be emited * @param numParticles number of particles launched on the one shot */ public void oneShot(View emiter, int numParticles) { oneShot(emiter, numParticles, new LinearInterpolator()); } /** * Launches particles in one Shot using a special Interpolator * * @param emiter View from which center the particles will be emited * @param numParticles number of particles launched on the one shot * @param interpolator the interpolator for the time */ public void oneShot(View emiter, int numParticles, Interpolator interpolator) { configureEmiter(emiter, Gravity.CENTER); mActivatedParticles = 0; mEmitingTime = mTimeToLive; // We create particles based in the parameters for (int i=0; i<numParticles && i<mMaxParticles; i++) { activateParticle(0); } // Add a full size view to the parent view mDrawingView = new ParticleField(mParentView.getContext()); mParentView.addView(mDrawingView); mDrawingView.setParticles (mActiveParticles); // We start a property animator that will call us to do the update // Animate from 0 to timeToLiveMax startAnimator(interpolator, mTimeToLive); } private void startAnimator(Interpolator interpolator, long animnationTime) { mAnimator = ValueAnimator.ofInt(new int[] {0, (int) animnationTime}); mAnimator.setDuration(animnationTime); mAnimator.addUpdateListener(new AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { int miliseconds = (Integer) animation.getAnimatedValue(); onUpdate(miliseconds); } }); mAnimator.addListener(new AnimatorListener() { @Override public void onAnimationStart(Animator animation) {} @Override public void onAnimationRepeat(Animator animation) {} @Override public void onAnimationEnd(Animator animation) { cleanupAnimation(); } @Override public void onAnimationCancel(Animator animation) { cleanupAnimation(); } }); mAnimator.setInterpolator(interpolator); mAnimator.start(); } private void configureEmiter(View emiter, int gravity) { // It works with an emision range int[] location = new int[2]; emiter.getLocationInWindow(location); // Check horizontal gravity and set range if (hasGravity(gravity, Gravity.LEFT)) { mEmiterXMin = location[0] - mParentLocation[0]; mEmiterXMax = mEmiterXMin; } else if (hasGravity(gravity, Gravity.RIGHT)) { mEmiterXMin = location[0] + emiter.getWidth() - mParentLocation[0]; mEmiterXMax = mEmiterXMin; } else if (hasGravity(gravity, Gravity.CENTER_HORIZONTAL)){ mEmiterXMin = location[0] + emiter.getWidth()/2 - mParentLocation[0]; mEmiterXMax = mEmiterXMin; } else { // All the range mEmiterXMin = location[0] - mParentLocation[0]; mEmiterXMax = location[0] + emiter.getWidth() - mParentLocation[0]; } // Now, vertical gravity and range if (hasGravity(gravity, Gravity.TOP)) { mEmiterYMin = location[1] - mParentLocation[1]; mEmiterYMax = mEmiterXMin; } else if (hasGravity(gravity, Gravity.BOTTOM)) { mEmiterYMin = location[1] + emiter.getHeight() - mParentLocation[1]; mEmiterYMax = mEmiterXMin; } else if (hasGravity(gravity, Gravity.CENTER_VERTICAL)){ mEmiterYMin = location[1] + emiter.getHeight()/2 - mParentLocation[1]; mEmiterYMax = mEmiterXMin; } else { // All the range mEmiterYMin = location[1] - mParentLocation[1]; mEmiterYMax = location[1] + emiter.getWidth() - mParentLocation[1]; } } private boolean hasGravity(int gravity, int gravityToCheck) { return (gravity & gravityToCheck) == gravityToCheck; } private void activateParticle(long delay) { Particle p = mParticles.remove(0); p.init(); // Initialization goes before configuration, scale is required before can be configured properly for (int i=0; i<mInitializers.size(); i++) { mInitializers.get(i).initParticle(p, mRandom); } int particleX = getFromRange (mEmiterXMin, mEmiterXMax); int particleY = getFromRange (mEmiterYMin, mEmiterYMax); p.configure(mTimeToLive, particleX, particleY); p.activate(delay, mModifiers); mActiveParticles.add(p); mActivatedParticles++; } private int getFromRange(int minValue, int maxValue) { if (minValue == maxValue) { return minValue; } return mRandom.nextInt(maxValue-minValue) + minValue; } private void onUpdate(long miliseconds) { while (((mEmitingTime > 0 && miliseconds < mEmitingTime)|| mEmitingTime == -1) && // This point should emit !mParticles.isEmpty() && // We have particles in the pool mActivatedParticles < mParticlesPerMilisecond*miliseconds) { // and we are under the number of particles that should be launched // Activate a new particle activateParticle(miliseconds); } for (int i=0; i<mActiveParticles.size(); i++) { boolean active = mActiveParticles.get(i).update(miliseconds); if (!active) { Particle p = mActiveParticles.remove(i); i--; // Needed to keep the index at the right position mParticles.add(p); } } mDrawingView.postInvalidate(); } private void cleanupAnimation() { mParentView.removeView(mDrawingView); mDrawingView = null; mParentView.postInvalidate(); mParticles.addAll(mActiveParticles); } /** * Stops emitting new particles, but will draw the existing ones until their timeToLive expire * For an cancellation and stop drawing of the particles, use cancel instead. */ public void stopEmitting () { // The time to be emiting is the current time (as if it was a time-limited emiter mEmitingTime = mCurrentTime; } /** * Cancels the particle system and all the animations. * To stop emitting but animate until the end, use stopEmitting instead. */ public void cancel() { if (mAnimator != null && mAnimator.isRunning()) { mAnimator.cancel(); } if (mTimer != null) { mTimer.cancel(); mTimer.purge(); cleanupAnimation(); } } private void updateParticlesBeforeStartTime(int particlesPerSecond) { if (particlesPerSecond == 0) { return; } long currentTimeInMs = mCurrentTime / 1000; long framesCount = currentTimeInMs / particlesPerSecond; if (framesCount == 0) { return; } long frameTimeInMs = mCurrentTime / framesCount; for (int i = 1; i <= framesCount; i++) { onUpdate(frameTimeInMs * i + 1); } } }
package ctci.chapter2LinkedLists; import java.util.Random; public class q4 { /* * Partition * * Write code to partition a linked list around a value x, such that all nodes less than x come * before all nodes greater or equal to x. If x is contained within the list, the values of x only need to be * after the elements less than x (see below). The partition element x can appear anywhere in the "right * partition"; it does not need to appear between the left and right partition. * * EXAMPLE * Input: 3->5->8->5->10->2->1 (Partition=5) * Output: 3->1->2->10->5->5->8 * * */ public static Node partition(int value, Node node) { Node head = node; Node tail = node; /* Partition list */ while (node != null) { Node next = node.next; if (node.data < value) { /* Insert node at head. */ node.next = head; head = node; } else { /* Insert node at tail. */ tail.next = node; tail = node; } node = next; } tail.next = null; return head; } public static void main(String[] args) { Node first = new Node(10); Node node = first; Random rand = new Random(); for (int i = 0; i < 10; i++) { node.next = new Node(rand.nextInt(20)); node = node.next; } displayList(first); Node head = partition(5, first); displayList(head); } public static void displayList(Node node) { StringBuilder sb = new StringBuilder(); sb.append(node.data); while (node.next != null) { sb.append("->").append(node.data); node = node.next; } System.out.println(sb); } }
package net.somethingdreadful.MAL; import java.util.ArrayList; import java.util.Calendar; import net.somethingdreadful.MAL.NavigationItems.NavItem; import net.somethingdreadful.MAL.api.MALApi; import net.somethingdreadful.MAL.api.MALApi.ListType; import net.somethingdreadful.MAL.api.response.Anime; import net.somethingdreadful.MAL.api.response.Manga; import net.somethingdreadful.MAL.sql.MALSqlHelper; import net.somethingdreadful.MAL.tasks.AnimeNetworkTask; import net.somethingdreadful.MAL.tasks.AnimeNetworkTaskFinishedListener; import net.somethingdreadful.MAL.tasks.MangaNetworkTask; import net.somethingdreadful.MAL.tasks.MangaNetworkTaskFinishedListener; import net.somethingdreadful.MAL.tasks.TaskJob; import android.annotation.SuppressLint; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Color; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Build; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.app.NotificationCompat; import android.support.v4.view.GravityCompat; import android.support.v4.view.ViewPager; import android.support.v4.widget.DrawerLayout; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.ViewFlipper; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.app.SherlockDialogFragment; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import com.sherlock.navigationdrawer.compat.SherlockActionBarDrawerToggle; import de.keyboardsurfer.android.widget.crouton.Crouton; import de.keyboardsurfer.android.widget.crouton.Style; public class Home extends BaseActionBarSearchView implements ActionBar.TabListener, ItemGridFragment.IItemGridFragment, LogoutConfirmationDialogFragment.LogoutConfirmationDialogListener { /** * The {@link android.support.v4.view.PagerAdapter} that will provide fragments for each of the * sections. We use a {@link android.support.v4.app.FragmentPagerAdapter} derivative, which will * keep every loaded fragment in memory. If this becomes too memory intensive, it may be best * to switch to a {@link android.support.v4.app.FragmentStatePagerAdapter}. */ HomeSectionsPagerAdapter mSectionsPagerAdapter; /** * The {@link ViewPager} that will host the section contents. */ ViewPager mViewPager; Context context; PrefManager mPrefManager; public MALManager mManager; private boolean init = false; ItemGridFragment af; ItemGridFragment mf; public boolean instanceExists; boolean networkAvailable; BroadcastReceiver networkReceiver; MenuItem searchItem; int AutoSync = 0; //run or not to run. private DrawerLayout mDrawerLayout; private ListView listView; private SherlockActionBarDrawerToggle mDrawerToggle; private ActionBarHelper mActionBar; View mActiveView; View mPreviousView; boolean myList = true; //tracks if the user is on 'My List' or not private NavigationItemAdapter mNavigationItemAdapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); context = getApplicationContext(); mPrefManager = new PrefManager(context); init = mPrefManager.getInit(); //The following is state handling code instanceExists = savedInstanceState != null && savedInstanceState.getBoolean("instanceExists", false); networkAvailable = savedInstanceState == null || savedInstanceState.getBoolean("networkAvailable", true); if (savedInstanceState != null) { AutoSync = savedInstanceState.getInt("AutoSync"); } if (init) { setContentView(R.layout.activity_home); // Creates the adapter to return the Animu and Mango fragments mSectionsPagerAdapter = new HomeSectionsPagerAdapter(getSupportFragmentManager()); mDrawerLayout= (DrawerLayout)findViewById(R.id.drawer_layout); mDrawerLayout.setDrawerListener(new DemoDrawerListener()); mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); listView = (ListView)findViewById(R.id.left_drawer); NavigationItems mNavigationContent = new NavigationItems(); mNavigationItemAdapter = new NavigationItemAdapter(this, R.layout.item_navigation, mNavigationContent.ITEMS); listView.setAdapter(mNavigationItemAdapter); listView.setOnItemClickListener(new DrawerItemClickListener()); listView.setCacheColorHint(0); listView.setScrollingCacheEnabled(false); listView.setScrollContainer(false); listView.setFastScrollEnabled(true); listView.setSmoothScrollbarEnabled(true); mActionBar = createActionBarHelper(); mActionBar.init(); mDrawerToggle = new SherlockActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer_light, R.string.drawer_open, R.string.drawer_close); mDrawerToggle.syncState(); mManager = new MALManager(context); // Set up the action bar. final ActionBar actionBar = getSupportActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); // Set up the ViewPager with the sections adapter. mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setAdapter(mSectionsPagerAdapter); mViewPager.setPageMargin(32); // When swiping between different sections, select the corresponding // tab. // We can also use ActionBar.Tab#select() to do this if we have a // reference to the // Tab. mViewPager .setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { actionBar.setSelectedNavigationItem(position); } }); // Add tabs for the anime and manga lists for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) { // Create a tab with text corresponding to the page title // defined by the adapter. // Also specify this Activity object, which implements the // TabListener interface, as the // listener for when this tab is selected. actionBar.addTab(actionBar.newTab() .setText(mSectionsPagerAdapter.getPageTitle(i)) .setTabListener(this)); } networkReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { checkNetworkAndDisplayCrouton(); } }; } else { //If the app hasn't been configured, take us to the first run screen to sign in. Intent firstRunInit = new Intent(this, FirstTimeInit.class); firstRunInit.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(firstRunInit); finish(); } NfcHelper.disableBeam(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { getSupportMenuInflater().inflate(R.menu.activity_home, menu); searchItem = menu.findItem(R.id.action_search); super.onCreateOptionsMenu(menu); return true; } @Override public MALApi.ListType getCurrentListType() { String listName = getSupportActionBar().getSelectedTab().getText().toString(); return MALApi.getListTypeByString(listName); } public boolean isConnectedWifi() { ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); NetworkInfo Wifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (Wifi.isConnected()&& mPrefManager.getonly_wifiEnabled() ) { return true; } else { return false; } } @Override public boolean onOptionsItemSelected(MenuItem item) { if (mDrawerToggle.onOptionsItemSelected(item)) { return true; } switch (item.getItemId()) { case R.id.menu_settings: startActivity(new Intent(this, Settings.class)); break; case R.id.menu_logout: showLogoutDialog(); break; case R.id.menu_about: startActivity(new Intent(this, AboutActivity.class)); break; case R.id.listType_all: if (af != null && mf != null) { af.getRecords(TaskJob.GETLIST, Home.this.context, 0); mf.getRecords(TaskJob.GETLIST, Home.this.context, 0); supportInvalidateOptionsMenu(); } break; case R.id.listType_inprogress: if (af != null && mf != null) { af.getRecords(TaskJob.GETLIST, Home.this.context, 1); mf.getRecords(TaskJob.GETLIST, Home.this.context, 1); supportInvalidateOptionsMenu(); } break; case R.id.listType_completed: if (af != null && mf != null) { af.getRecords(TaskJob.GETLIST, Home.this.context, 2); mf.getRecords(TaskJob.GETLIST, Home.this.context, 2); supportInvalidateOptionsMenu(); } break; case R.id.listType_onhold: if (af != null && mf != null) { af.getRecords(TaskJob.GETLIST, Home.this.context, 3); mf.getRecords(TaskJob.GETLIST, Home.this.context, 3); supportInvalidateOptionsMenu(); } break; case R.id.listType_dropped: if (af != null && mf != null) { af.getRecords(TaskJob.GETLIST, Home.this.context, 4); mf.getRecords(TaskJob.GETLIST, Home.this.context, 4); supportInvalidateOptionsMenu(); } break; case R.id.listType_planned: if (af != null && mf != null) { af.getRecords(TaskJob.GETLIST, Home.this.context, 5); mf.getRecords(TaskJob.GETLIST, Home.this.context, 5); supportInvalidateOptionsMenu(); } break; case R.id.forceSync: if (af != null && mf != null) { af.getRecords(TaskJob.FORCESYNC, Home.this.context, af.currentList); mf.getRecords(TaskJob.FORCESYNC, Home.this.context, mf.currentList); syncNotify(); } break; } return super.onOptionsItemSelected(item); } @Override public void onResume() { super.onResume(); checkNetworkAndDisplayCrouton(); if (instanceExists && af.getMode() == TaskJob.GETLIST) { af.getRecords(TaskJob.GETLIST, Home.this.context, af.currentList); mf.getRecords(TaskJob.GETLIST, Home.this.context, mf.currentList); } registerReceiver(networkReceiver, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE")); if (mSearchView != null) { mSearchView.clearFocus(); mSearchView.setFocusable(false); mSearchView.setQuery("", false); searchItem.collapseActionView(); } } @Override public void onPause() { super.onPause(); instanceExists = true; unregisterReceiver(networkReceiver); } @Override public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } @Override public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { // When the given tab is selected, switch to the corresponding page in the ViewPager. mViewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } @Override public void fragmentReady() { //Interface implementation for knowing when the dynamically created fragment is finished loading //We use instantiateItem to return the fragment. Since the fragment IS instantiated, the method returns it. af = (net.somethingdreadful.MAL.ItemGridFragment) mSectionsPagerAdapter.instantiateItem(mViewPager, 0); mf = (net.somethingdreadful.MAL.ItemGridFragment) mSectionsPagerAdapter.instantiateItem(mViewPager, 1); af.setRecordType(ListType.ANIME); mf.setRecordType(ListType.MANGA); //auto-sync stuff if (mPrefManager.getsync_time_last() == 0 && AutoSync == 0 && networkAvailable == true){ mPrefManager.setsync_time_last(1); mPrefManager.commitChanges(); synctask(); } else if (mPrefManager.getsynchronisationEnabled() && AutoSync == 0 && networkAvailable == true){ Calendar localCalendar = Calendar.getInstance(); int Time_now = localCalendar.get(Calendar.DAY_OF_YEAR)*24*60; //will reset on new year ;) Time_now = Time_now + localCalendar.get(Calendar.HOUR_OF_DAY)*60; Time_now = Time_now + localCalendar.get(Calendar.MINUTE); int last_sync = mPrefManager.getsync_time_last(); if (last_sync >= Time_now && last_sync <= (Time_now + mPrefManager.getsync_time())){ //no sync needed (This is inside the time range) }else{ if (mPrefManager.getonly_wifiEnabled() == false){ synctask(); mPrefManager.setsync_time_last(Time_now + mPrefManager.getsync_time()); }else if (mPrefManager.getonly_wifiEnabled() && isConnectedWifi()){ //connected to Wi-Fi and sync only on Wi-Fi checked. synctask(); mPrefManager.setsync_time_last(Time_now + mPrefManager.getsync_time()); } } mPrefManager.commitChanges(); } } public void synctask(){ af.getRecords(TaskJob.FORCESYNC, this.context, af.currentList); mf.getRecords(TaskJob.FORCESYNC, this.context, mf.currentList); syncNotify(); AutoSync = 1; } @Override public void onSaveInstanceState(Bundle state) { //This is telling out future selves that we already have some things and not to do them state.putBoolean("instanceExists", true); state.putBoolean("networkAvailable", networkAvailable); state.putInt("AutoSync", AutoSync); super.onSaveInstanceState(state); } @Override public boolean onPrepareOptionsMenu(Menu menu) { MenuItem item = menu.findItem(R.id.menu_listType); if(!myList){//if not on my list then disable menu items like listType, etc item.setEnabled(false); item.setVisible(false); } else{ item.setEnabled(true); item.setVisible(true); } if (af != null) { //All this is handling the ticks in the switch list menu switch (af.currentList) { case 0: menu.findItem(R.id.listType_all).setChecked(true); break; case 1: menu.findItem(R.id.listType_inprogress).setChecked(true); break; case 2: menu.findItem(R.id.listType_completed).setChecked(true); break; case 3: menu.findItem(R.id.listType_onhold).setChecked(true); break; case 4: menu.findItem(R.id.listType_dropped).setChecked(true); break; case 5: menu.findItem(R.id.listType_planned).setChecked(true); } } if (networkAvailable) { if (myList){ menu.findItem(R.id.forceSync).setVisible(true); }else{ menu.findItem(R.id.forceSync).setVisible(false); } menu.findItem(R.id.action_search).setVisible(true); } else { menu.findItem(R.id.forceSync).setVisible(false); menu.findItem(R.id.action_search).setVisible(false); AutoSync = 1; } return true; } @SuppressLint("NewApi") @Override public void onLogoutConfirmed() { mPrefManager.setInit(false); mPrefManager.setUser(""); mPrefManager.setPass(""); mPrefManager.commitChanges(); context.deleteDatabase(MALSqlHelper.getHelper(context).getDatabaseName()); startActivity(new Intent(this, Home.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); finish(); } private void syncNotify() { Crouton.makeText(this, R.string.crouton_info_SyncMessage, Style.INFO).show(); Intent notificationIntent = new Intent(context, Home.class); PendingIntent contentIntent = PendingIntent.getActivity(context, 1, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT); NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); Notification syncNotification = new NotificationCompat.Builder(context).setOngoing(true) .setContentIntent(contentIntent) .setSmallIcon(R.drawable.icon) .setContentTitle(getString(R.string.app_name)) .setContentText(getString(R.string.crouton_info_SyncMessage)) .getNotification(); nm.notify(R.id.notification_sync, syncNotification); myList = true; supportInvalidateOptionsMenu(); } private void showLogoutDialog() { FragmentManager fm = getSupportFragmentManager(); LogoutConfirmationDialogFragment lcdf = new LogoutConfirmationDialogFragment(); if (Build.VERSION.SDK_INT >= 11) { lcdf.setStyle(SherlockDialogFragment.STYLE_NORMAL, android.R.style.Theme_Holo_Dialog); } else { lcdf.setStyle(SherlockDialogFragment.STYLE_NORMAL, 0); } lcdf.show(fm, "fragment_LogoutConfirmationDialog"); } public void checkNetworkAndDisplayCrouton() { if (!MALApi.isNetworkAvailable(context) && networkAvailable == true) { Crouton.makeText(this, R.string.crouton_error_noConnectivityOnRun, Style.ALERT).show(); af = (net.somethingdreadful.MAL.ItemGridFragment) mSectionsPagerAdapter.instantiateItem(mViewPager, 0); mf = (net.somethingdreadful.MAL.ItemGridFragment) mSectionsPagerAdapter.instantiateItem(mViewPager, 1); if (af.getMode() != null) { af.setMode(null); mf.setMode(null); af.getRecords(TaskJob.GETLIST, Home.this.context, af.currentList); mf.getRecords(TaskJob.GETLIST, Home.this.context, mf.currentList); myList = true; } } else if (MALApi.isNetworkAvailable(context) && networkAvailable == false) { Crouton.makeText(this, R.string.crouton_info_connectionRestored, Style.INFO).show(); synctask(); } if (!MALApi.isNetworkAvailable(context)) { networkAvailable = false; } else { networkAvailable = true; } supportInvalidateOptionsMenu(); } /*private classes for nav drawer*/ private ActionBarHelper createActionBarHelper() { return new ActionBarHelper(); } public class DrawerItemClickListener implements ListView.OnItemClickListener { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { /* do stuff when drawer item is clicked here */ af.scrollToTop(); mf.scrollToTop(); if (!networkAvailable && position > 2) { position = 1; Crouton.makeText(Home.this, R.string.crouton_error_noConnectivity, Style.ALERT).show(); } myList = (position == 1); switch (position){ case 0: Intent Profile = new Intent(context, net.somethingdreadful.MAL.ProfileActivity.class); Profile.putExtra("username", mPrefManager.getUser()); startActivity(Profile); break; case 1: af.getRecords(TaskJob.GETLIST, Home.this.context, af.currentList); mf.getRecords(TaskJob.GETLIST, Home.this.context, mf.currentList); break; case 2: Intent Friends = new Intent(context, net.somethingdreadful.MAL.FriendsActivity.class); startActivity(Friends); break; case 3: af.getRecords(TaskJob.GETTOPRATED, Home.this.context); mf.getRecords(TaskJob.GETTOPRATED, Home.this.context); af.scrollListener.resetPageNumber(); mf.scrollListener.resetPageNumber(); break; case 4: af.getRecords(TaskJob.GETMOSTPOPULAR, Home.this.context); mf.getRecords(TaskJob.GETMOSTPOPULAR, Home.this.context); af.scrollListener.resetPageNumber(); mf.scrollListener.resetPageNumber(); break; case 5: af.getRecords(TaskJob.GETJUSTADDED, Home.this.context); mf.getRecords(TaskJob.GETJUSTADDED, Home.this.context); af.scrollListener.resetPageNumber(); mf.scrollListener.resetPageNumber(); break; case 6: af.getRecords(TaskJob.GETUPCOMING, Home.this.context); mf.getRecords(TaskJob.GETUPCOMING, Home.this.context); af.scrollListener.resetPageNumber(); mf.scrollListener.resetPageNumber(); break; } Home.this.supportInvalidateOptionsMenu(); //This part is for figuring out which item in the nav drawer is selected and highlighting it with colors mPreviousView = mActiveView; if (mPreviousView != null) mPreviousView.setBackgroundColor(Color.parseColor("#333333")); //dark color mActiveView = view; mActiveView.setBackgroundColor(Color.parseColor("#38B2E1")); //blue color mDrawerLayout.closeDrawer(listView); } } private class DemoDrawerListener implements DrawerLayout.DrawerListener { @Override public void onDrawerOpened(View drawerView) { mDrawerToggle.onDrawerOpened(drawerView); mActionBar.onDrawerOpened(); } @Override public void onDrawerClosed(View drawerView) { mDrawerToggle.onDrawerClosed(drawerView); mActionBar.onDrawerClosed(); } @Override public void onDrawerSlide(View drawerView, float slideOffset) { mDrawerToggle.onDrawerSlide(drawerView, slideOffset); } @Override public void onDrawerStateChanged(int newState) { mDrawerToggle.onDrawerStateChanged(newState); } } private class ActionBarHelper { private final ActionBar mActionBar; private CharSequence mDrawerTitle; private CharSequence mTitle; private ActionBarHelper() { mActionBar = getSupportActionBar(); } public void init() { mActionBar.setDisplayHomeAsUpEnabled(true); mActionBar.setHomeButtonEnabled(true); mTitle = mDrawerTitle = getTitle(); } /** * When the drawer is closed we restore the action bar state reflecting * the specific contents in view. */ public void onDrawerClosed() { mActionBar.setTitle(mTitle); } /** * When the drawer is open we set the action bar to a generic title. The * action bar should only contain data relevant at the top level of the * nav hierarchy represented by the drawer, as the rest of your content * will be dimmed down and non-interactive. */ public void onDrawerOpened() { mActionBar.setTitle(mDrawerTitle); } } private class NavigationItemAdapter extends ArrayAdapter<NavItem> { private ArrayList<NavItem> items; public NavigationItemAdapter(Context context, int textViewResourceId, ArrayList<NavItem> objects) { super(context, textViewResourceId, objects); this.items = objects; } public View getView(int position, View convertView, ViewGroup parent) { View v = convertView; if (v == null) { LayoutInflater vi = getLayoutInflater(); v = vi.inflate(R.layout.item_navigation, null); } NavItem item = items.get(position); if (item != null) { ImageView mIcon = (ImageView) v .findViewById(R.id.nav_item_icon); TextView mTitle = (TextView) v.findViewById(R.id.nav_item_text); if (mIcon != null) { mIcon.setImageResource(item.icon); } else { Log.d("LISTITEM", "Null"); } if (mTitle != null) { mTitle.setText(item.title); } else { Log.d("LISTITEM", "Null"); } } return v; } } }
package example; //-*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: //@homepage@ import java.awt.*; import java.awt.event.*; import java.util.List; import java.util.ArrayList; import javax.swing.*; // import javax.swing.event.*; import javax.swing.table.*; // import javax.swing.text.*; public class MainPanel extends JPanel { private static final int AUTOWRAP_COLUMN = 1; public MainPanel() { super(new BorderLayout()); String[] columnNames = {"Default", "AutoWrap"}; Object[][] data = { {"123456789012345678901234567890", "123456789012345678901234567890"}, {"aaaa", "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddx"}, {"bbbbb", " {"ccccccccccccccccccc", ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>|"}, }; TableModel model = new DefaultTableModel(data, columnNames); final JTable table = new JTable(model) { // private final Color evenColor = new Color(230, 240, 255); // @Override public Component prepareRenderer(TableCellRenderer tcr, int row, int column) { // Component c = super.prepareRenderer(tcr, row, column); // if(isRowSelected(row)) { // c.setForeground(getSelectionForeground()); // c.setBackground(getSelectionBackground()); // }else{ // c.setForeground(getForeground()); // c.setBackground((row%2==0)?evenColor:getBackground()); // return c; // @Override public void doLayout() { // //System.out.println("doLayout"); // initPreferredHeight(); // super.doLayout(); // @Override public void columnMarginChanged(final ChangeEvent e) { // //System.out.println("columnMarginChanged"); // super.columnMarginChanged(e); // initPreferredHeight(); // private void initPreferredHeight() { // for(int row=0;row<getRowCount();row++) { // int maximum_height = 0; // for(int col=0;col<getColumnModel().getColumnCount();col++) { // Component c = prepareRenderer(getCellRenderer(row, col), row, col); // if(c instanceof JTextArea) { // JTextArea a = (JTextArea)c; // int h = getPreferredHeight(a); // + getIntercellSpacing().height; // maximum_height = Math.max(maximum_height, h); // setRowHeight(row, maximum_height); // private int getPreferredHeight(JTextComponent c) { // Insets insets = c.getInsets(); // //Insets margin = c.getMargin(); // //System.out.println(insets); // float f = view.getPreferredSpan(View.Y_AXIS); // //System.out.println(f); // int preferredHeight = (int)f; // return preferredHeight + insets.top + insets.bottom; }; table.setEnabled(false); table.setShowGrid(false); table.getColumnModel().getColumn(AUTOWRAP_COLUMN).setCellRenderer(new TextAreaCellRenderer()); //table.setIntercellSpacing(new Dimension(0,0)); add(new JScrollPane(table, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER)); setPreferredSize(new Dimension(320, 240)); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { createAndShowGUI(); } }); } public static void createAndShowGUI() { try{ UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); }catch(Exception e) { e.printStackTrace(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } class TextAreaCellRenderer extends JTextArea implements TableCellRenderer { //public static class UIResource extends TextAreaCellRenderer implements javax.swing.plaf.UIResource {} public TextAreaCellRenderer() { super(); setLineWrap(true); setBorder(BorderFactory.createEmptyBorder(2,2,2,2)); //setBorder(BorderFactory.createLineBorder(Color.RED,2)); //setMargin(new Insets(2,2,2,2)); //setBorder(BorderFactory.createEmptyBorder()); setName("Table.cellRenderer"); } @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { setFont(table.getFont()); setText((value ==null) ? "" : value.toString()); adjustRowHeight(table, row, column); return this; } private ArrayList<ArrayList<Integer>> rowColHeight = new ArrayList<ArrayList<Integer>>(); private void adjustRowHeight(JTable table, int row, int column) { //The trick to get this to work properly is to set the width of the column to the //textarea. The reason for this is that getPreferredSize(), without a width tries //to place all the text in one line. By setting the size with the with of the column, //getPreferredSize() returnes the proper height which the row should have in //order to make room for the text. //int cWidth = table.getTableHeader().getColumnModel().getColumn(column).getWidth(); //int cWidth = table.getCellRect(row, column, false).width; //Ignore IntercellSpacing //setSize(new Dimension(cWidth, 1000)); setBounds(table.getCellRect(row, column, false)); //doLayout(); int prefH = getPreferredSize().height; while(rowColHeight.size() <= row) { rowColHeight.add(new ArrayList<Integer>(column)); } List<Integer> colHeights = rowColHeight.get(row); while(colHeights.size() <= column) { colHeights.add(0); } colHeights.set(column, prefH); int maxH = prefH; for(Integer colHeight : colHeights) { if(colHeight > maxH) { maxH = colHeight; } } if(table.getRowHeight(row) != maxH) { table.setRowHeight(row, maxH); } } @Override public boolean isOpaque() { Color back = getBackground(); Component p = getParent(); if(p != null) { p = p.getParent(); } // p should now be the JTable. boolean colorMatch = back != null && p != null && back.equals(p.getBackground()) && p.isOpaque(); return !colorMatch && super.isOpaque(); } @Override protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) { //String literal pool //if(propertyName=="document" || ((propertyName == "font" || propertyName == "foreground") && oldValue != newValue)) { if("document".equals(propertyName) || oldValue != newValue && ("font".equals(propertyName) || "foreground".equals(propertyName))) { super.firePropertyChange(propertyName, oldValue, newValue); } } @Override public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) {} @Override public void repaint(long tm, int x, int y, int width, int height) {} @Override public void repaint(Rectangle r) {} @Override public void repaint() {} @Override public void invalidate() {} @Override public void validate() {} @Override public void revalidate() {} }
package example; //-*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: //@homepage@ import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; import javax.swing.event.*; public final class MainPanel extends JPanel { private MainPanel() { super(new BorderLayout()); DefaultListModel<String> model = new DefaultListModel<>(); model.addElement("11\n1"); model.addElement("222222222222222\n222222222222222"); model.addElement("3333333333333333333\n33333333333333333333\n33333333333333333"); model.addElement("444"); JList<String> list = new JList<String>(model) { private transient MouseInputListener cbml; @Override public void updateUI() { removeMouseListener(cbml); removeMouseMotionListener(cbml); super.updateUI(); setFixedCellHeight(-1); cbml = new CellButtonsMouseListener(this); addMouseListener(cbml); addMouseMotionListener(cbml); setCellRenderer(new ButtonsRenderer<String>(model)); } }; add(new JScrollPane(list)); setPreferredSize(new Dimension(320, 240)); } public static void main(String... args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { createAndShowGUI(); } }); } public static void createAndShowGUI() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } class CellButtonsMouseListener extends MouseInputAdapter { private int prevIndex = -1; private JButton prevButton; private final JList<String> list; protected CellButtonsMouseListener(JList<String> list) { super(); this.list = list; } @Override public void mouseMoved(MouseEvent e) { //JList list = (JList) e.getComponent(); Point pt = e.getPoint(); int index = list.locationToIndex(pt); if (!list.getCellBounds(index, index).contains(pt)) { if (prevIndex >= 0) { listRepaint(list, list.getCellBounds(prevIndex, prevIndex)); } index = -1; prevButton = null; return; } if (index >= 0) { JButton button = getButton(list, pt, index); ButtonsRenderer renderer = (ButtonsRenderer) list.getCellRenderer(); renderer.button = button; if (Objects.nonNull(button)) { button.getModel().setRollover(true); renderer.rolloverIndex = index; if (!button.equals(prevButton)) { listRepaint(list, list.getCellBounds(prevIndex, index)); } } else { renderer.rolloverIndex = -1; Rectangle r = null; if (prevIndex == index) { if (prevIndex >= 0 && Objects.nonNull(prevButton)) { r = list.getCellBounds(prevIndex, prevIndex); } } else { r = list.getCellBounds(index, index); } listRepaint(list, r); prevIndex = -1; } prevButton = button; } prevIndex = index; } @Override public void mousePressed(MouseEvent e) { //JList list = (JList) e.getComponent(); Point pt = e.getPoint(); int index = list.locationToIndex(pt); if (index >= 0) { JButton button = getButton(list, pt, index); if (Objects.nonNull(button)) { ButtonsRenderer renderer = (ButtonsRenderer) list.getCellRenderer(); renderer.pressedIndex = index; renderer.button = button; listRepaint(list, list.getCellBounds(index, index)); } } } @Override public void mouseReleased(MouseEvent e) { //JList list = (JList) e.getComponent(); Point pt = e.getPoint(); int index = list.locationToIndex(pt); if (index >= 0) { JButton button = getButton(list, pt, index); if (Objects.nonNull(button)) { ButtonsRenderer renderer = (ButtonsRenderer) list.getCellRenderer(); renderer.pressedIndex = -1; renderer.button = null; button.doClick(); listRepaint(list, list.getCellBounds(index, index)); } } } private static void listRepaint(JList list, Rectangle rect) { Optional.ofNullable(rect).ifPresent(list::repaint); // if (Objects.nonNull(rect)) { // list.repaint(rect); } private static JButton getButton(JList<String> list, Point pt, int index) { Component c = list.getCellRenderer().getListCellRendererComponent(list, "", index, false, false); Rectangle r = list.getCellBounds(index, index); c.setBounds(r); //c.doLayout(); //may be needed for mone LayoutManager pt.translate(-r.x, -r.y); // Component b = SwingUtilities.getDeepestComponentAt(c, pt.x, pt.y); // if (b instanceof JButton) { // return (JButton) b; // } else { // return null; return Optional.ofNullable(SwingUtilities.getDeepestComponentAt(c, pt.x, pt.y)) .filter(JButton.class::isInstance).map(JButton.class::cast).orElse(null); } } class ButtonsRenderer<E> extends JPanel implements ListCellRenderer<E> { private static final Color EVEN_COLOR = new Color(230, 255, 230); private final JTextArea textArea = new JTextArea(); private final JButton deleteButton = new JButton(new AbstractAction("delete") { @Override public void actionPerformed(ActionEvent e) { if (model.getSize() > 1) { model.remove(index); } } }); private final JButton copyButton = new JButton(new AbstractAction("copy") { @Override public void actionPerformed(ActionEvent e) { model.add(index, model.get(index)); } }); private final DefaultListModel<E> model; private int index; public int pressedIndex = -1; public int rolloverIndex = -1; public JButton button; protected ButtonsRenderer(DefaultListModel<E> model) { super(new BorderLayout()); this.model = model; setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 0)); setOpaque(true); textArea.setLineWrap(true); textArea.setOpaque(false); add(textArea); Box box = Box.createHorizontalBox(); for (JButton b: Arrays.asList(deleteButton, copyButton)) { b.setFocusable(false); b.setRolloverEnabled(false); box.add(b); box.add(Box.createHorizontalStrut(5)); } add(box, BorderLayout.EAST); } @Override public Dimension getPreferredSize() { Dimension d = super.getPreferredSize(); d.width = 0; // VerticalScrollBar as needed return d; } @Override public Component getListCellRendererComponent(JList<? extends E> list, E value, int index, boolean isSelected, boolean cellHasFocus) { textArea.setText(Objects.toString(value, "")); this.index = index; if (isSelected) { setBackground(list.getSelectionBackground()); textArea.setForeground(list.getSelectionForeground()); } else { setBackground(index % 2 == 0 ? EVEN_COLOR : list.getBackground()); textArea.setForeground(list.getForeground()); } resetButtonStatus(); if (Objects.nonNull(button)) { if (index == pressedIndex) { button.getModel().setSelected(true); button.getModel().setArmed(true); button.getModel().setPressed(true); } else if (index == rolloverIndex) { button.getModel().setRollover(true); } } return this; } private void resetButtonStatus() { for (JButton b: Arrays.asList(deleteButton, copyButton)) { ButtonModel m = b.getModel(); m.setRollover(false); m.setArmed(false); m.setPressed(false); m.setSelected(false); } } }
package com.sunzn.utils.library; import android.content.Context; import android.content.res.AssetManager; import org.apache.commons.io.FileUtils; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; public class DBUtils { /** * * Assets ZIP * * context * source Assets zip * target Database db * * void * */ public static void release(Context context, String source, String target) { if (context != null && source != null && target != null) { File GoalDB = context.getDatabasePath(target); if (!GoalDB.exists()) { copyFile(context, source); } } } public static void copyFile(Context context, String source) { File target = context.getDatabasePath(source); try { AssetManager manager = context.getAssets(); InputStream stream = manager.open(source); FileUtils.copyInputStreamToFile(stream, target); UZipFile(target.getAbsolutePath(), target.getParent() + "/"); } catch (IOException e) { e.printStackTrace(); } finally { FileUtils.deleteQuietly(target); } } private static void UZipFile(String zipFile, String targetDir) { int BUFFER = 4096; String strEntry; try { BufferedOutputStream dest; FileInputStream fis = new FileInputStream(zipFile); ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis)); ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { try { int count; byte[] data = new byte[BUFFER]; strEntry = entry.getName(); File entryFile = new File(targetDir + strEntry); File entryDir = new File(entryFile.getParent()); if (!entryDir.exists()) { entryDir.mkdirs(); } FileOutputStream fos = new FileOutputStream(entryFile); dest = new BufferedOutputStream(fos, BUFFER); while ((count = zis.read(data, 0, BUFFER)) != -1) { dest.write(data, 0, count); } dest.flush(); dest.close(); } catch (Exception ex) { ex.printStackTrace(); } } zis.close(); } catch (Exception cwj) { cwj.printStackTrace(); } } }
package com.purdue.CampusFeed.API; import android.content.Context; import android.net.http.HttpResponseCache; import android.util.Log; import com.google.gson.*; import com.google.gson.reflect.TypeToken; import java.io.*; import java.lang.reflect.Type; import java.net.HttpURLConnection; import java.net.URL; import java.util.Date; import java.util.List; import java.util.Scanner; /** * Make a static instance of this on app creation. Close it on shutdown * * @author Matthew */ public class Api implements Closeable { private static final String BASE_URL = "http://54.213.17.69:9000/"; private static Gson gson; private static Api instance; private Auth login; static { class DateSerializer implements JsonSerializer<Date>, JsonDeserializer<Date> { @Override public Date deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context) throws JsonParseException { return new Date(jsonElement.getAsLong()); } @Override public JsonElement serialize(Date date, Type type, JsonSerializationContext context) { return new JsonPrimitive(date.getTime()); } } gson = new GsonBuilder() .registerTypeAdapter(Date.class, new DateSerializer()) .create(); } private Api(Context context) { try { File httpCacheDir = new File(context.getCacheDir(), "http"); long httpCacheSize = 10 * 1024 * 1024; // 10 MiB HttpResponseCache.install(httpCacheDir, httpCacheSize); } catch (IOException e) { Log.i("Api", "HTTP response cache installation failed:" + e); } } public static Api getInstance(Context context) { if (instance == null) { instance = new Api(context); } return instance; } public Object getResponse(String method, String endpoint, String json, Type type) { try { HttpURLConnection conn = (HttpURLConnection) new URL(BASE_URL + endpoint).openConnection(); conn.setRequestProperty("Content-Type", "application/json; charset=utf-8"); conn.setRequestProperty("Content-Length", Integer.toString(json.length())); conn.setRequestMethod(method); //conn.setDoInput(true); HttpURLConnection.setFollowRedirects(false); if (method.equals("POST")) { conn.setDoOutput(true); OutputStream output = new BufferedOutputStream(conn.getOutputStream()); new OutputStreamWriter(output).append(json).close(); } InputStream input = new BufferedInputStream(conn.getInputStream()); Scanner in = new Scanner(input).useDelimiter("\\A"); String raw = in.next(); Log.i("raw", raw); Object response = gson.fromJson(raw, type); input.close(); return response; } catch (Exception e) { e.printStackTrace(); return null; } } static class LoginRequest { public String fb_user_id; public String access_token; public LoginRequest(String fb_user_id, String access_token) { this.fb_user_id = fb_user_id; this.access_token = access_token; } } static class LoginResponse { public String access_token; } public boolean login(String fb_user_id, String access_token) { LoginResponse resp = (LoginResponse) getResponse("POST", "login", gson.toJson(new LoginRequest(fb_user_id, access_token)), LoginResponse.class); if (resp != null) { login = new Auth(fb_user_id, resp.access_token); return true; } else { return false; } } public List<Event> advSearchEvent(AdvSearchQuery query) { query.setAuth(login); return (List<Event>) getResponse("POST", "adv_search_event", gson.toJson(query), new TypeToken<List<Event>>() { }.getType()); } public long createEvent(Event event) { if (login == null) { return -1; } class CreateEventRequest { public String desc; public String location; public String[] categories; public String title; public Auth auth; public int visibility; public long date_time; public CreateEventRequest(Event event) { desc = event.description; location = event.location; categories = event.categories; title = event.name; this.auth = Api.this.login; visibility = 1; date_time = event.getDatetimeLong(); } } class EventResponse { public long event_id; } EventResponse resp = (EventResponse) getResponse("POST", "create_event", gson.toJson(new CreateEventRequest(event)), EventResponse.class); if (resp != null) { return resp.event_id; } else { return -1; } } public boolean updateEvent(Event event) { if (login == null) { return false; } class UpdateEventRequest { public Auth auth; public String title; public String desc; public String location; public long date_time; public long id; public int visibility; public String[] categories; public UpdateEventRequest(Event event) { this.auth = login; this.title = event.description; this.desc = event.description; this.location = event.location; this.date_time = event.time; this.id = event.id; this.visibility = 1; this.categories = event.categories; } } class UpdateResponse { String ok; } UpdateResponse resp = (UpdateResponse) getResponse("POST", "update_event", gson.toJson(new Object()), UpdateResponse.class); return resp != null; } @Override public void close() throws IOException { HttpResponseCache cache = HttpResponseCache.getInstalled(); if (cache != null) { cache.flush(); } } }
package sample.javafx; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.stage.FileChooser; import javafx.stage.FileChooser.ExtensionFilter; import javafx.stage.Stage; import java.io.File; public class MainController { private Stage stage; @FXML public void openFileDialog() { FileChooser chooser = new FileChooser(); ObservableList<ExtensionFilter> extensionFilters = chooser.getExtensionFilters(); extensionFilters.add(new ExtensionFilter("", "*.*")); extensionFilters.add(new ExtensionFilter("", "*.jpg", "*.jpeg", "*.png", "*.gif")); extensionFilters.add(new ExtensionFilter("", "*.mp4")); File file = chooser.showOpenDialog(this.stage); System.out.println("file=" + file); } public void setStage(Stage stage) { this.stage = stage; } }
package jkind.xtext.typing; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.Deque; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import jkind.xtext.jkind.AbbreviationType; import jkind.xtext.jkind.Assertion; import jkind.xtext.jkind.BinaryExpr; import jkind.xtext.jkind.BoolExpr; import jkind.xtext.jkind.BoolType; import jkind.xtext.jkind.Constant; import jkind.xtext.jkind.Equation; import jkind.xtext.jkind.Expr; import jkind.xtext.jkind.Field; import jkind.xtext.jkind.IdExpr; import jkind.xtext.jkind.IfThenElseExpr; import jkind.xtext.jkind.IntExpr; import jkind.xtext.jkind.IntType; import jkind.xtext.jkind.JkindPackage; import jkind.xtext.jkind.NodeCallExpr; import jkind.xtext.jkind.ProjectionExpr; import jkind.xtext.jkind.Property; import jkind.xtext.jkind.RealExpr; import jkind.xtext.jkind.RealType; import jkind.xtext.jkind.RecordExpr; import jkind.xtext.jkind.RecordType; import jkind.xtext.jkind.SubrangeType; import jkind.xtext.jkind.Typedef; import jkind.xtext.jkind.UnaryExpr; import jkind.xtext.jkind.UserType; import jkind.xtext.jkind.Variable; import jkind.xtext.jkind.util.JkindSwitch; import jkind.xtext.util.Util; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.xtext.validation.ValidationMessageAcceptor; public class TypeChecker extends JkindSwitch<JType> { final private ValidationMessageAcceptor messageAcceptor; public TypeChecker(ValidationMessageAcceptor messageAcceptor) { this.messageAcceptor = messageAcceptor; } private static final JBuiltinType ERROR = JBuiltinType.ERROR; private static final JBuiltinType REAL = JBuiltinType.REAL; private static final JBuiltinType INT = JBuiltinType.INT; private static final JBuiltinType BOOL = JBuiltinType.BOOL; public void check(Constant c) { if (c.getType() != null) { expectAssignableType(doSwitch(c.getType()), c.getExpr()); } else { doSwitch(c.getExpr()); } } public void check(Property property) { expectAssignableType(BOOL, doSwitch(property.getRef()), property); } public void check(Assertion assertion) { expectAssignableType(BOOL, assertion.getExpr()); } public void check(Equation equation) { if (equation.getLhs().size() == 1) { Variable var = equation.getLhs().get(0); JType expected = doSwitch(var); expectAssignableType(expected, equation.getRhs()); } else { checkNodeCallAssignment(equation); } } private void checkNodeCallAssignment(Equation equation) { List<JType> expected = doSwitchList(equation.getLhs()); if (equation.getRhs() instanceof NodeCallExpr) { NodeCallExpr call = (NodeCallExpr) equation.getRhs(); List<JType> actual = visitNodeCallExpr(call); if (expected.size() != actual.size()) { error("Expected " + expected.size() + " values, but found " + actual.size(), equation.getRhs()); return; } for (int i = 0; i < expected.size(); i++) { expectAssignableType(expected.get(i), actual.get(i), equation.getLhs().get(i)); } } else { error("Expected node call for multiple variable assignment", equation.getRhs()); } } @Override public JType caseBinaryExpr(BinaryExpr e) { JType left = doSwitch(e.getLeft()); JType right = doSwitch(e.getRight()); if (left == ERROR || right == ERROR) { return ERROR; } switch (e.getOp()) { case "+": case "-": case "*": if (left == REAL && right == REAL) { return REAL; } if (isIntBased(left) && isIntBased(right)) { return INT; } break; case "/": if (left == REAL && right == REAL) { return REAL; } break; case "div": if (isIntBased(left) && isIntBased(right)) { return INT; } break; case "=": case "<>": if (joinTypes(left, right) != null) { return BOOL; } break; case ">": case "<": case ">=": case "<=": if (left == REAL && right == REAL) { return BOOL; } if (isIntBased(left) && isIntBased(right)) { return BOOL; } break; case "or": case "and": case "xor": case "=>": if (left == BOOL && right == BOOL) { return BOOL; } break; case "->": JType join = joinTypes(left, right); if (join != null) { return join; } break; } error("Operator '" + e.getOp() + "' not defined on types " + left + ", " + right, e); return ERROR; } @Override public JType caseUnaryExpr(UnaryExpr e) { JType type = doSwitch(e.getExpr()); if (type == ERROR) { return ERROR; } switch (e.getOp()) { case "pre": return type; case "not": if (type == BOOL) { return BOOL; } break; case "-": if (type == REAL) { return REAL; } if (type == INT) { return INT; } if (type instanceof JSubrangeType) { JSubrangeType subrange = (JSubrangeType) type; return new JSubrangeType(subrange.high.negate(), subrange.low.negate()); } break; } error("Operator '" + e.getOp() + "' not defined on type " + type, e); return ERROR; } @Override public JType caseIdExpr(IdExpr e) { return doSwitch(e.getId()); } @Override public JType caseConstant(Constant e) { if (e.getType() != null) { return doSwitch(e.getType()); } else { return doSwitch(e.getExpr()); } } @Override public JType caseBoolType(BoolType e) { return BOOL; } @Override public JType caseIntType(IntType e) { return INT; } @Override public JType caseRealType(RealType e) { return REAL; } @Override public JType caseSubrangeType(SubrangeType e) { return new JSubrangeType(e.getLow(), e.getHigh()); } private final Deque<Typedef> stack = new ArrayDeque<>(); @Override public JType caseUserType(UserType e) { if (stack.contains(e.getDef())) { return ERROR; } stack.push(e.getDef()); JType type = doSwitch(e.getDef()); stack.pop(); return type; } @Override public JType caseRecordType(RecordType e) { if (e.getName() == null) { // Suppress additional error messages for unlinked record types return ERROR; } Map<String, JType> fields = new HashMap<>(); for (int i = 0; i < e.getFields().size(); i++) { Field field = e.getFields().get(i); JType type = doSwitch(e.getTypes().get(i)); fields.put(field.getName(), type); } return new JRecordType(e.getName(), fields); } @Override public JType caseAbbreviationType(AbbreviationType e) { return doSwitch(e.getType()); } @Override public JType caseVariable(Variable e) { return doSwitch(Util.getType(e)); } @Override public JType caseIntExpr(IntExpr e) { return new JSubrangeType(e.getVal(), e.getVal()); } @Override public JType caseRealExpr(RealExpr e) { return REAL; } @Override public JType caseBoolExpr(BoolExpr e) { return BOOL; } @Override public JType caseIfThenElseExpr(IfThenElseExpr e) { expectAssignableType(BOOL, e.getCond()); JType t1 = doSwitch(e.getThen()); JType t2 = doSwitch(e.getElse()); if (t1 == ERROR || t2 == ERROR) { return ERROR; } JType join = joinTypes(t1, t2); if (join != null) { return join; } error("Branches have inconsistent types " + t1 + ", " + t2, e); return ERROR; } @Override public JType caseNodeCallExpr(NodeCallExpr e) { List<JType> types = visitNodeCallExpr(e); if (types.size() == 1) { return types.get(0); } else { // Prevent cascading errors if (e.getNode().getName() != null) { error("A node call within an expression must return a single value", e); } return ERROR; } } private List<JType> visitNodeCallExpr(NodeCallExpr e) { if (e.getNode().getName() == null) { // Prevent cascading errors return Collections.emptyList(); } List<Expr> args = e.getArgs(); List<Variable> formals = Util.getVariables(e.getNode().getInputs()); if (args.size() != formals.size()) { error("Expected " + formals.size() + " arguments, but found " + args.size(), e); } else { for (int i = 0; i < args.size(); i++) { expectAssignableType(doSwitch(formals.get(i)), args.get(i)); } } return doSwitchList(Util.getVariables(e.getNode().getOutputs())); } private List<JType> doSwitchList(List<? extends EObject> list) { List<JType> result = new ArrayList<>(); for (EObject e : list) { result.add(doSwitch(e)); } return result; } @Override public JType caseProjectionExpr(ProjectionExpr e) { JType type = doSwitch(e.getExpr()); if (type == ERROR) { return ERROR; } if (type instanceof JRecordType) { JRecordType record = (JRecordType) type; JType fieldType = record.fields.get(e.getField().getName()); if (fieldType != null) { return fieldType; } error("Field " + e.getField().getName() + " not defined in type " + type, e, JkindPackage.Literals.PROJECTION_EXPR__FIELD); return ERROR; } else { error("Expected record type, but found " + type, e.getExpr()); return ERROR; } } @Override public JType caseRecordExpr(RecordExpr e) { // For partial user input, these lists may have different size in which // case we can't correctly type check the fields; if (e.getFields().size() != e.getExprs().size()) { return doSwitch(e.getType()); } Map<String, Expr> fields = new HashMap<>(); for (int i = 0; i < e.getFields().size(); i++) { Field field = e.getFields().get(i); Expr expr = e.getExprs().get(i); fields.put(field.getName(), expr); } JType result = doSwitch(e.getType()); if (!(result instanceof JRecordType)) { return ERROR; } JRecordType expectedRecord = (JRecordType) result; for (Entry<String, JType> entry : expectedRecord.fields.entrySet()) { String expectedField = entry.getKey(); JType expectedType = entry.getValue(); if (!fields.containsKey(expectedField)) { error("Missing field " + expectedField, e, JkindPackage.Literals.RECORD_EXPR__TYPE); } else { Expr actualExpr = fields.get(expectedField); expectAssignableType(expectedType, actualExpr); } } return result; } private void expectAssignableType(JType expected, EObject source) { expectAssignableType(expected, doSwitch(source), source); } private void expectAssignableType(JType expected, JType actual, EObject source) { if (expected == ERROR || actual == ERROR) { return; } if (expected.equals(actual)) { return; } if (expected == INT && actual instanceof JSubrangeType) { return; } if (expected instanceof JSubrangeType && actual instanceof JSubrangeType) { JSubrangeType exRange = (JSubrangeType) expected; JSubrangeType acRange = (JSubrangeType) actual; if (acRange.low.compareTo(exRange.low) < 0 || acRange.high.compareTo(exRange.high) > 0) { error("Expected type " + exRange.toSubrangeString() + ", but found type " + acRange.toSubrangeString(), source); } return; } error("Expected type " + getExpected(expected) + ", but found type " + actual, source); } private String getExpected(JType expected) { if (expected instanceof JSubrangeType) { return ((JSubrangeType) expected).toSubrangeString(); } else { return expected.toString(); } } private JType joinTypes(JType t1, JType t2) { if (t1 instanceof JSubrangeType && t2 instanceof JSubrangeType) { JSubrangeType s1 = (JSubrangeType) t1; JSubrangeType s2 = (JSubrangeType) t2; return new JSubrangeType(s1.low.min(s2.low), s1.high.max(s2.high)); } else if (isIntBased(t1) && isIntBased(t2)) { return INT; } else if (t1.equals(t2)) { return t1; } else { return null; } } private boolean isIntBased(JType type) { return type == INT || type instanceof JSubrangeType; } private void error(String message, EObject e) { messageAcceptor.acceptError(message, e, null, 0, null); } private void error(String message, EObject e, EStructuralFeature feature) { messageAcceptor.acceptError(message, e, feature, 0, null); } }
package cn.jzvd; import android.graphics.Point; import android.graphics.SurfaceTexture; import android.media.AudioManager; import android.media.MediaPlayer; import android.os.Handler; import android.os.HandlerThread; import android.os.Looper; import android.os.Message; import android.util.Log; import android.view.Surface; import android.view.TextureView; import java.lang.reflect.Method; import java.util.Map; public class JZMediaManager implements TextureView.SurfaceTextureListener, MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnBufferingUpdateListener, MediaPlayer.OnSeekCompleteListener, MediaPlayer.OnErrorListener, MediaPlayer.OnInfoListener, MediaPlayer.OnVideoSizeChangedListener { public static final int HANDLER_PREPARE = 0; public static final int HANDLER_RELEASE = 2; public static final String TAG = "JiaoZiVideoPlayer"; public static JZResizeTextureView textureView; public static SurfaceTexture savedSurfaceTexture; public static Surface surface; public static String CURRENT_PLAYING_URL; public static boolean CURRENT_PLING_LOOP; public static Map<String, String> MAP_HEADER_DATA; private static JZMediaManager JZMediaManager; public MediaPlayer mediaPlayer = new MediaPlayer(); public int currentVideoWidth = 0; public int currentVideoHeight = 0; HandlerThread mMediaHandlerThread; MediaHandler mMediaHandler; Handler mainThreadHandler; public JZMediaManager() { mMediaHandlerThread = new HandlerThread(TAG); mMediaHandlerThread.start(); mMediaHandler = new MediaHandler((mMediaHandlerThread.getLooper())); mainThreadHandler = new Handler(); } public static JZMediaManager instance() { if (JZMediaManager == null) { JZMediaManager = new JZMediaManager(); } return JZMediaManager; } public Point getVideoSize() { if (currentVideoWidth != 0 && currentVideoHeight != 0) { return new Point(currentVideoWidth, currentVideoHeight); } else { return null; } } public void prepare() { releaseMediaPlayer(); Message msg = new Message(); msg.what = HANDLER_PREPARE; mMediaHandler.sendMessage(msg); } public void releaseMediaPlayer() { Message msg = new Message(); msg.what = HANDLER_RELEASE; mMediaHandler.sendMessage(msg); } @Override public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int i, int i1) { Log.i(TAG, "onSurfaceTextureAvailable [" + JZVideoPlayerManager.getCurrentJzvd().hashCode() + "] "); if (savedSurfaceTexture == null) { savedSurfaceTexture = surfaceTexture; prepare(); } else { textureView.setSurfaceTexture(savedSurfaceTexture); } } @Override public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int i, int i1) { // SurfaceTextureImageSizeChanged Log.i(TAG, "onSurfaceTextureSizeChanged [" + JZVideoPlayerManager.getCurrentJzvd().hashCode() + "] "); } @Override public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) { return savedSurfaceTexture == null; } @Override public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) { } @Override public void onPrepared(MediaPlayer mp) { mediaPlayer.start(); mainThreadHandler.post(new Runnable() { @Override public void run() { if (JZVideoPlayerManager.getCurrentJzvd() != null) { JZVideoPlayerManager.getCurrentJzvd().onPrepared(); } } }); } @Override public void onCompletion(MediaPlayer mp) { mainThreadHandler.post(new Runnable() { @Override public void run() { if (JZVideoPlayerManager.getCurrentJzvd() != null) { JZVideoPlayerManager.getCurrentJzvd().onAutoCompletion(); } } }); } @Override public void onBufferingUpdate(MediaPlayer mp, final int percent) { mainThreadHandler.post(new Runnable() { @Override public void run() { if (JZVideoPlayerManager.getCurrentJzvd() != null) { JZVideoPlayerManager.getCurrentJzvd().setBufferProgress(percent); } } }); } @Override public void onSeekComplete(MediaPlayer mp) { mainThreadHandler.post(new Runnable() { @Override public void run() { if (JZVideoPlayerManager.getCurrentJzvd() != null) { JZVideoPlayerManager.getCurrentJzvd().onSeekComplete(); } } }); } @Override public boolean onError(MediaPlayer mp, final int what, final int extra) { mainThreadHandler.post(new Runnable() { @Override public void run() { if (JZVideoPlayerManager.getCurrentJzvd() != null) { JZVideoPlayerManager.getCurrentJzvd().onError(what, extra); } } }); return true; } @Override public boolean onInfo(MediaPlayer mp, final int what, final int extra) { mainThreadHandler.post(new Runnable() { @Override public void run() { if (JZVideoPlayerManager.getCurrentJzvd() != null) { JZVideoPlayerManager.getCurrentJzvd().onInfo(what, extra); } } }); return false; } @Override public void onVideoSizeChanged(MediaPlayer mp, int width, int height) { currentVideoWidth = width; currentVideoHeight = height; mainThreadHandler.post(new Runnable() { @Override public void run() { if (JZVideoPlayerManager.getCurrentJzvd() != null) { JZVideoPlayerManager.getCurrentJzvd().onVideoSizeChanged(); } } }); } public class MediaHandler extends Handler { public MediaHandler(Looper looper) { super(looper); } @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case HANDLER_PREPARE: try { currentVideoWidth = 0; currentVideoHeight = 0; mediaPlayer.release(); mediaPlayer = new MediaPlayer(); mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mediaPlayer.setLooping(CURRENT_PLING_LOOP); mediaPlayer.setOnPreparedListener(JZMediaManager.this); mediaPlayer.setOnCompletionListener(JZMediaManager.this); mediaPlayer.setOnBufferingUpdateListener(JZMediaManager.this); mediaPlayer.setScreenOnWhilePlaying(true); mediaPlayer.setOnSeekCompleteListener(JZMediaManager.this); mediaPlayer.setOnErrorListener(JZMediaManager.this); mediaPlayer.setOnInfoListener(JZMediaManager.this); mediaPlayer.setOnVideoSizeChangedListener(JZMediaManager.this); Class<MediaPlayer> clazz = MediaPlayer.class; Method method = clazz.getDeclaredMethod("setDataSource", String.class, Map.class); method.invoke(mediaPlayer, CURRENT_PLAYING_URL, MAP_HEADER_DATA); mediaPlayer.prepareAsync(); if (surface != null) { surface.release(); } surface = new Surface(savedSurfaceTexture); mediaPlayer.setSurface(surface); } catch (Exception e) { e.printStackTrace(); } break; case HANDLER_RELEASE: mediaPlayer.release(); break; } } } }
package com.jme3.bullet; import com.jme3.app.AppTask; import com.jme3.asset.AssetManager; import com.jme3.bullet.collision.*; import com.jme3.bullet.collision.shapes.CollisionShape; import com.jme3.bullet.control.PhysicsControl; import com.jme3.bullet.control.RigidBodyControl; import com.jme3.bullet.joints.PhysicsJoint; import com.jme3.bullet.objects.PhysicsCharacter; import com.jme3.bullet.objects.PhysicsGhostObject; import com.jme3.bullet.objects.PhysicsRigidBody; import com.jme3.bullet.objects.PhysicsVehicle; import com.jme3.math.Transform; import com.jme3.math.Vector3f; import com.jme3.scene.Node; import com.jme3.scene.Spatial; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.Future; import java.util.logging.Level; import java.util.logging.Logger; /** * <p>PhysicsSpace - The central jbullet-jme physics space</p> * * @author normenhansen */ public class PhysicsSpace { private static final Logger logger = Logger.getLogger(PhysicsSpace.class.getName()); public static final int AXIS_X = 0; public static final int AXIS_Y = 1; public static final int AXIS_Z = 2; private long physicsSpaceId = 0; private static ThreadLocal<ConcurrentLinkedQueue<AppTask<?>>> pQueueTL = new ThreadLocal<ConcurrentLinkedQueue<AppTask<?>>>() { @Override protected ConcurrentLinkedQueue<AppTask<?>> initialValue() { return new ConcurrentLinkedQueue<AppTask<?>>(); } }; private ConcurrentLinkedQueue<AppTask<?>> pQueue = new ConcurrentLinkedQueue<AppTask<?>>(); private static ThreadLocal<PhysicsSpace> physicsSpaceTL = new ThreadLocal<PhysicsSpace>(); private BroadphaseType broadphaseType = BroadphaseType.DBVT; // private DiscreteDynamicsWorld dynamicsWorld = null; // private BroadphaseInterface broadphase; // private CollisionDispatcher dispatcher; // private ConstraintSolver solver; // private DefaultCollisionConfiguration collisionConfiguration; // private Map<GhostObject, PhysicsGhostObject> physicsGhostNodes = new ConcurrentHashMap<GhostObject, PhysicsGhostObject>(); private Map<Long, PhysicsGhostObject> physicsGhostObjects = new ConcurrentHashMap<Long, PhysicsGhostObject>(); private Map<Long, PhysicsCharacter> physicsCharacters = new ConcurrentHashMap<Long, PhysicsCharacter>(); private Map<Long, PhysicsRigidBody> physicsBodies = new ConcurrentHashMap<Long, PhysicsRigidBody>(); private Map<Long, PhysicsJoint> physicsJoints = new ConcurrentHashMap<Long, PhysicsJoint>(); private Map<Long, PhysicsVehicle> physicsVehicles = new ConcurrentHashMap<Long, PhysicsVehicle>(); private ArrayList<PhysicsCollisionListener> collisionListeners = new ArrayList<PhysicsCollisionListener>(); private ArrayDeque<PhysicsCollisionEvent> collisionEvents = new ArrayDeque<PhysicsCollisionEvent>(); private Map<Integer, PhysicsCollisionGroupListener> collisionGroupListeners = new ConcurrentHashMap<Integer, PhysicsCollisionGroupListener>(); private ConcurrentLinkedQueue<PhysicsTickListener> tickListeners = new ConcurrentLinkedQueue<PhysicsTickListener>(); private PhysicsCollisionEventFactory eventFactory = new PhysicsCollisionEventFactory(); private Vector3f worldMin = new Vector3f(-10000f, -10000f, -10000f); private Vector3f worldMax = new Vector3f(10000f, 10000f, 10000f); private float accuracy = 1f / 60f; private int maxSubSteps = 4, rayTestFlags = 1 << 2; private int solverNumIterations = 10; static { // System.loadLibrary("bulletjme"); // initNativePhysics(); } /** * Get the current PhysicsSpace <b>running on this thread</b><br/> For * parallel physics, this can also be called from the OpenGL thread to * receive the PhysicsSpace * * @return the PhysicsSpace running on this thread */ public static PhysicsSpace getPhysicsSpace() { return physicsSpaceTL.get(); } /** * Used internally * * @param space */ public static void setLocalThreadPhysicsSpace(PhysicsSpace space) { physicsSpaceTL.set(space); } public PhysicsSpace() { this(new Vector3f(-10000f, -10000f, -10000f), new Vector3f(10000f, 10000f, 10000f), BroadphaseType.DBVT); } public PhysicsSpace(BroadphaseType broadphaseType) { this(new Vector3f(-10000f, -10000f, -10000f), new Vector3f(10000f, 10000f, 10000f), broadphaseType); } public PhysicsSpace(Vector3f worldMin, Vector3f worldMax) { this(worldMin, worldMax, BroadphaseType.AXIS_SWEEP_3); } public PhysicsSpace(Vector3f worldMin, Vector3f worldMax, BroadphaseType broadphaseType) { this.worldMin.set(worldMin); this.worldMax.set(worldMax); this.broadphaseType = broadphaseType; create(); } /** * Has to be called from the (designated) physics thread */ public void create() { physicsSpaceId = createPhysicsSpace(worldMin.x, worldMin.y, worldMin.z, worldMax.x, worldMax.y, worldMax.z, broadphaseType.ordinal(), false); pQueueTL.set(pQueue); physicsSpaceTL.set(this); // collisionConfiguration = new DefaultCollisionConfiguration(); // dispatcher = new CollisionDispatcher(collisionConfiguration); // switch (broadphaseType) { // case SIMPLE: // broadphase = new SimpleBroadphase(); // break; // case AXIS_SWEEP_3: // broadphase = new AxisSweep3(Converter.convert(worldMin), Converter.convert(worldMax)); // break; // case AXIS_SWEEP_3_32: // broadphase = new AxisSweep3_32(Converter.convert(worldMin), Converter.convert(worldMax)); // break; // case DBVT: // broadphase = new DbvtBroadphase(); // break; // solver = new SequentialImpulseConstraintSolver(); // dynamicsWorld = new DiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration); // dynamicsWorld.setGravity(new javax.vecmath.Vector3f(0, -9.81f, 0)); // broadphase.getOverlappingPairCache().setInternalGhostPairCallback(new GhostPairCallback()); // GImpactCollisionAlgorithm.registerAlgorithm(dispatcher); // //register filter callback for tick / collision // setTickCallback(); // setContactCallbacks(); // //register filter callback for collision groups // setOverlapFilterCallback(); } private native long createPhysicsSpace(float minX, float minY, float minZ, float maxX, float maxY, float maxZ, int broadphaseType, boolean threading); private void preTick_native(float f) { AppTask task = pQueue.poll(); task = pQueue.poll(); while (task != null) { while (task.isCancelled()) { task = pQueue.poll(); } try { task.invoke(); } catch (Exception ex) { logger.log(Level.SEVERE, null, ex); } task = pQueue.poll(); } for (Iterator<PhysicsTickListener> it = tickListeners.iterator(); it.hasNext();) { PhysicsTickListener physicsTickCallback = it.next(); physicsTickCallback.prePhysicsTick(this, f); } } private void postTick_native(float f) { for (Iterator<PhysicsTickListener> it = tickListeners.iterator(); it.hasNext();) { PhysicsTickListener physicsTickCallback = it.next(); physicsTickCallback.physicsTick(this, f); } } private void addCollision_native() { } private boolean needCollision_native(PhysicsCollisionObject objectA, PhysicsCollisionObject objectB) { return false; } // private void setOverlapFilterCallback() { // OverlapFilterCallback callback = new OverlapFilterCallback() { // public boolean needBroadphaseCollision(BroadphaseProxy bp, BroadphaseProxy bp1) { // boolean collides = (bp.collisionFilterGroup & bp1.collisionFilterMask) != 0; // if (collides) { // collides = (bp1.collisionFilterGroup & bp.collisionFilterMask) != 0; // if (collides) { // assert (bp.clientObject instanceof com.bulletphysics.collision.dispatch.CollisionObject && bp.clientObject instanceof com.bulletphysics.collision.dispatch.CollisionObject); // com.bulletphysics.collision.dispatch.CollisionObject colOb = (com.bulletphysics.collision.dispatch.CollisionObject) bp.clientObject; // com.bulletphysics.collision.dispatch.CollisionObject colOb1 = (com.bulletphysics.collision.dispatch.CollisionObject) bp1.clientObject; // assert (colOb.getUserPointer() != null && colOb1.getUserPointer() != null); // PhysicsCollisionObject collisionObject = (PhysicsCollisionObject) colOb.getUserPointer(); // PhysicsCollisionObject collisionObject1 = (PhysicsCollisionObject) colOb1.getUserPointer(); // if ((collisionObject.getCollideWithGroups() & collisionObject1.getCollisionGroup()) > 0 // || (collisionObject1.getCollideWithGroups() & collisionObject.getCollisionGroup()) > 0) { // PhysicsCollisionGroupListener listener = collisionGroupListeners.get(collisionObject.getCollisionGroup()); // PhysicsCollisionGroupListener listener1 = collisionGroupListeners.get(collisionObject1.getCollisionGroup()); // if (listener != null) { // return listener.collide(collisionObject, collisionObject1); // } else if (listener1 != null) { // return listener1.collide(collisionObject, collisionObject1); // return true; // } else { // return false; // return collides; // dynamicsWorld.getPairCache().setOverlapFilterCallback(callback); // private void setTickCallback() { // final PhysicsSpace space = this; // InternalTickCallback callback2 = new InternalTickCallback() { // @Override // public void internalTick(DynamicsWorld dw, float f) { // //execute task list // AppTask task = pQueue.poll(); // task = pQueue.poll(); // while (task != null) { // while (task.isCancelled()) { // task = pQueue.poll(); // try { // task.invoke(); // } catch (Exception ex) { // logger.log(Level.SEVERE, null, ex); // task = pQueue.poll(); // for (Iterator<PhysicsTickListener> it = tickListeners.iterator(); it.hasNext();) { // PhysicsTickListener physicsTickCallback = it.next(); // physicsTickCallback.prePhysicsTick(space, f); // dynamicsWorld.setPreTickCallback(callback2); // InternalTickCallback callback = new InternalTickCallback() { // @Override // public void internalTick(DynamicsWorld dw, float f) { // for (Iterator<PhysicsTickListener> it = tickListeners.iterator(); it.hasNext();) { // PhysicsTickListener physicsTickCallback = it.next(); // physicsTickCallback.physicsTick(space, f); // dynamicsWorld.setInternalTickCallback(callback, this); // private void setContactCallbacks() { // BulletGlobals.setContactAddedCallback(new ContactAddedCallback() { // public boolean contactAdded(ManifoldPoint cp, com.bulletphysics.collision.dispatch.CollisionObject colObj0, // int partId0, int index0, com.bulletphysics.collision.dispatch.CollisionObject colObj1, int partId1, // int index1) { // System.out.println("contact added"); // return true; // BulletGlobals.setContactProcessedCallback(new ContactProcessedCallback() { // public boolean contactProcessed(ManifoldPoint cp, Object body0, Object body1) { // if (body0 instanceof CollisionObject && body1 instanceof CollisionObject) { // PhysicsCollisionObject node = null, node1 = null; // CollisionObject rBody0 = (CollisionObject) body0; // CollisionObject rBody1 = (CollisionObject) body1; // node = (PhysicsCollisionObject) rBody0.getUserPointer(); // node1 = (PhysicsCollisionObject) rBody1.getUserPointer(); // collisionEvents.add(eventFactory.getEvent(PhysicsCollisionEvent.TYPE_PROCESSED, node, node1, cp)); // return true; // BulletGlobals.setContactDestroyedCallback(new ContactDestroyedCallback() { // public boolean contactDestroyed(Object userPersistentData) { // System.out.println("contact destroyed"); // return true; private void addCollisionEvent_native(PhysicsCollisionObject node, PhysicsCollisionObject node1, long manifoldPointObjectId) { // System.out.println("addCollisionEvent:"+node.getObjectId()+" "+ node1.getObjectId()); collisionEvents.add(eventFactory.getEvent(PhysicsCollisionEvent.TYPE_PROCESSED, node, node1, manifoldPointObjectId)); } private boolean notifyCollisionGroupListeners_native(PhysicsCollisionObject node, PhysicsCollisionObject node1){ PhysicsCollisionGroupListener listener = collisionGroupListeners.get(node.getCollisionGroup()); PhysicsCollisionGroupListener listener1 = collisionGroupListeners.get(node1.getCollisionGroup()); boolean result = true; if(listener != null){ result = listener.collide(node, node1); } if(listener1 != null && node.getCollisionGroup() != node1.getCollisionGroup()){ result = listener1.collide(node, node1) && result; } return result; } /** * updates the physics space * * @param time the current time value */ public void update(float time) { update(time, maxSubSteps); } /** * updates the physics space, uses maxSteps<br> * * @param time the current time value * @param maxSteps */ public void update(float time, int maxSteps) { // if (getDynamicsWorld() == null) { // return; //step simulation stepSimulation(physicsSpaceId, time, maxSteps, accuracy); } private native void stepSimulation(long space, float time, int maxSteps, float accuracy); public void distributeEvents() { //add collision callbacks int clistsize = collisionListeners.size(); while( collisionEvents.isEmpty() == false ) { PhysicsCollisionEvent physicsCollisionEvent = collisionEvents.pop(); for(int i=0;i<clistsize;i++) { collisionListeners.get(i).collision(physicsCollisionEvent); } //recycle events eventFactory.recycle(physicsCollisionEvent); } } public static <V> Future<V> enqueueOnThisThread(Callable<V> callable) { AppTask<V> task = new AppTask<V>(callable); System.out.println("created apptask"); pQueueTL.get().add(task); return task; } /** * calls the callable on the next physics tick (ensuring e.g. force * applying) * * @param <V> * @param callable * @return Future object */ public <V> Future<V> enqueue(Callable<V> callable) { AppTask<V> task = new AppTask<V>(callable); pQueue.add(task); return task; } /** * adds an object to the physics space * * @param obj the PhysicsControl or Spatial with PhysicsControl to add */ public void add(Object obj) { if (obj instanceof PhysicsControl) { ((PhysicsControl) obj).setPhysicsSpace(this); } else if (obj instanceof Spatial) { Spatial node = (Spatial) obj; for (int i = 0; i < node.getNumControls(); i++) { if (node.getControl(i) instanceof PhysicsControl) { add(((PhysicsControl) node.getControl(i))); } } } else if (obj instanceof PhysicsCollisionObject) { addCollisionObject((PhysicsCollisionObject) obj); } else if (obj instanceof PhysicsJoint) { addJoint((PhysicsJoint) obj); } else { throw (new UnsupportedOperationException("Cannot add this kind of object to the physics space.")); } } public void addCollisionObject(PhysicsCollisionObject obj) { if (obj instanceof PhysicsGhostObject) { addGhostObject((PhysicsGhostObject) obj); } else if (obj instanceof PhysicsRigidBody) { addRigidBody((PhysicsRigidBody) obj); } else if (obj instanceof PhysicsVehicle) { addRigidBody((PhysicsVehicle) obj); } else if (obj instanceof PhysicsCharacter) { addCharacter((PhysicsCharacter) obj); } } /** * removes an object from the physics space * * @param obj the PhysicsControl or Spatial with PhysicsControl to remove */ public void remove(Object obj) { if (obj == null) return; if (obj instanceof PhysicsControl) { ((PhysicsControl) obj).setPhysicsSpace(null); } else if (obj instanceof Spatial) { Spatial node = (Spatial) obj; for (int i = 0; i < node.getNumControls(); i++) { if (node.getControl(i) instanceof PhysicsControl) { remove(((PhysicsControl) node.getControl(i))); } } } else if (obj instanceof PhysicsCollisionObject) { removeCollisionObject((PhysicsCollisionObject) obj); } else if (obj instanceof PhysicsJoint) { removeJoint((PhysicsJoint) obj); } else { throw (new UnsupportedOperationException("Cannot remove this kind of object from the physics space.")); } } public void removeCollisionObject(PhysicsCollisionObject obj) { if (obj instanceof PhysicsGhostObject) { removeGhostObject((PhysicsGhostObject) obj); } else if (obj instanceof PhysicsRigidBody) { removeRigidBody((PhysicsRigidBody) obj); } else if (obj instanceof PhysicsCharacter) { removeCharacter((PhysicsCharacter) obj); } } /** * adds all physics controls and joints in the given spatial node to the physics space * (e.g. after loading from disk) - recursive if node * @param spatial the rootnode containing the physics objects */ public void addAll(Spatial spatial) { if (spatial.getControl(RigidBodyControl.class) != null) { RigidBodyControl physicsNode = spatial.getControl(RigidBodyControl.class); add(physicsNode); //add joints with physicsNode as BodyA List<PhysicsJoint> joints = physicsNode.getJoints(); for (Iterator<PhysicsJoint> it1 = joints.iterator(); it1.hasNext();) { PhysicsJoint physicsJoint = it1.next(); if (physicsNode.equals(physicsJoint.getBodyA())) { //add(physicsJoint.getBodyB()); add(physicsJoint); } } } else { add(spatial); } //recursion if (spatial instanceof Node) { List<Spatial> children = ((Node) spatial).getChildren(); for (Iterator<Spatial> it = children.iterator(); it.hasNext();) { Spatial spat = it.next(); addAll(spat); } } } /** * Removes all physics controls and joints in the given spatial from the physics space * (e.g. before saving to disk) - recursive if node * @param spatial the rootnode containing the physics objects */ public void removeAll(Spatial spatial) { if (spatial.getControl(RigidBodyControl.class) != null) { RigidBodyControl physicsNode = spatial.getControl(RigidBodyControl.class); //remove joints with physicsNode as BodyA List<PhysicsJoint> joints = physicsNode.getJoints(); for (Iterator<PhysicsJoint> it1 = joints.iterator(); it1.hasNext();) { PhysicsJoint physicsJoint = it1.next(); if (physicsNode.equals(physicsJoint.getBodyA())) { removeJoint(physicsJoint); //remove(physicsJoint.getBodyB()); } } remove(physicsNode); } else if (spatial.getControl(PhysicsControl.class) != null) { remove(spatial); } //recursion if (spatial instanceof Node) { List<Spatial> children = ((Node) spatial).getChildren(); for (Iterator<Spatial> it = children.iterator(); it.hasNext();) { Spatial spat = it.next(); removeAll(spat); } } } private native void addCollisionObject(long space, long id); private native void removeCollisionObject(long space, long id); private native void addRigidBody(long space, long id); private native void removeRigidBody(long space, long id); private native void addCharacterObject(long space, long id); private native void removeCharacterObject(long space, long id); private native void addAction(long space, long id); private native void removeAction(long space, long id); private native void addVehicle(long space, long id); private native void removeVehicle(long space, long id); private native void addConstraint(long space, long id); private native void addConstraintC(long space, long id, boolean collision); private native void removeConstraint(long space, long id); private void addGhostObject(PhysicsGhostObject node) { if (physicsGhostObjects.containsKey(node.getObjectId())) { logger.log(Level.WARNING, "GhostObject {0} already exists in PhysicsSpace, cannot add.", node); return; } physicsGhostObjects.put(node.getObjectId(), node); logger.log(Level.FINE, "Adding ghost object {0} to physics space.", Long.toHexString(node.getObjectId())); addCollisionObject(physicsSpaceId, node.getObjectId()); } private void removeGhostObject(PhysicsGhostObject node) { if (!physicsGhostObjects.containsKey(node.getObjectId())) { logger.log(Level.WARNING, "GhostObject {0} does not exist in PhysicsSpace, cannot remove.", node); return; } physicsGhostObjects.remove(node.getObjectId()); logger.log(Level.FINE, "Removing ghost object {0} from physics space.", Long.toHexString(node.getObjectId())); removeCollisionObject(physicsSpaceId, node.getObjectId()); } private void addCharacter(PhysicsCharacter node) { if (physicsCharacters.containsKey(node.getObjectId())) { logger.log(Level.WARNING, "Character {0} already exists in PhysicsSpace, cannot add.", node); return; } physicsCharacters.put(node.getObjectId(), node); logger.log(Level.FINE, "Adding character {0} to physics space.", Long.toHexString(node.getObjectId())); addCharacterObject(physicsSpaceId, node.getObjectId()); addAction(physicsSpaceId, node.getControllerId()); // dynamicsWorld.addCollisionObject(node.getObjectId(), CollisionFilterGroups.CHARACTER_FILTER, (short) (CollisionFilterGroups.STATIC_FILTER | CollisionFilterGroups.DEFAULT_FILTER)); // dynamicsWorld.addAction(node.getControllerId()); } private void removeCharacter(PhysicsCharacter node) { if (!physicsCharacters.containsKey(node.getObjectId())) { logger.log(Level.WARNING, "Character {0} does not exist in PhysicsSpace, cannot remove.", node); return; } physicsCharacters.remove(node.getObjectId()); logger.log(Level.FINE, "Removing character {0} from physics space.", Long.toHexString(node.getObjectId())); removeAction(physicsSpaceId, node.getControllerId()); removeCharacterObject(physicsSpaceId, node.getObjectId()); // dynamicsWorld.removeAction(node.getControllerId()); // dynamicsWorld.removeCollisionObject(node.getObjectId()); } private void addRigidBody(PhysicsRigidBody node) { if (physicsBodies.containsKey(node.getObjectId())) { logger.log(Level.WARNING, "RigidBody {0} already exists in PhysicsSpace, cannot add.", node); return; } physicsBodies.put(node.getObjectId(), node); //Workaround //It seems that adding a Kinematic RigidBody to the dynamicWorld prevent it from being non kinematic again afterward. //so we add it non kinematic, then set it kinematic again. boolean kinematic = false; if (node.isKinematic()) { kinematic = true; node.setKinematic(false); } addRigidBody(physicsSpaceId, node.getObjectId()); if (kinematic) { node.setKinematic(true); } logger.log(Level.FINE, "Adding RigidBody {0} to physics space.", node.getObjectId()); if (node instanceof PhysicsVehicle) { logger.log(Level.FINE, "Adding vehicle constraint {0} to physics space.", Long.toHexString(((PhysicsVehicle) node).getVehicleId())); physicsVehicles.put(((PhysicsVehicle) node).getVehicleId(), (PhysicsVehicle) node); addVehicle(physicsSpaceId, ((PhysicsVehicle) node).getVehicleId()); } } private void removeRigidBody(PhysicsRigidBody node) { if (!physicsBodies.containsKey(node.getObjectId())) { logger.log(Level.WARNING, "RigidBody {0} does not exist in PhysicsSpace, cannot remove.", node); return; } if (node instanceof PhysicsVehicle) { logger.log(Level.FINE, "Removing vehicle constraint {0} from physics space.", Long.toHexString(((PhysicsVehicle) node).getVehicleId())); physicsVehicles.remove(((PhysicsVehicle) node).getVehicleId()); removeVehicle(physicsSpaceId, ((PhysicsVehicle) node).getVehicleId()); } logger.log(Level.FINE, "Removing RigidBody {0} from physics space.", Long.toHexString(node.getObjectId())); physicsBodies.remove(node.getObjectId()); removeRigidBody(physicsSpaceId, node.getObjectId()); } private void addJoint(PhysicsJoint joint) { if (physicsJoints.containsKey(joint.getObjectId())) { logger.log(Level.WARNING, "Joint {0} already exists in PhysicsSpace, cannot add.", joint); return; } logger.log(Level.FINE, "Adding Joint {0} to physics space.", Long.toHexString(joint.getObjectId())); physicsJoints.put(joint.getObjectId(), joint); addConstraintC(physicsSpaceId, joint.getObjectId(), !joint.isCollisionBetweenLinkedBodys()); // dynamicsWorld.addConstraint(joint.getObjectId(), !joint.isCollisionBetweenLinkedBodys()); } private void removeJoint(PhysicsJoint joint) { if (!physicsJoints.containsKey(joint.getObjectId())) { logger.log(Level.WARNING, "Joint {0} does not exist in PhysicsSpace, cannot remove.", joint); return; } logger.log(Level.FINE, "Removing Joint {0} from physics space.", Long.toHexString(joint.getObjectId())); physicsJoints.remove(joint.getObjectId()); removeConstraint(physicsSpaceId, joint.getObjectId()); // dynamicsWorld.removeConstraint(joint.getObjectId()); } public Collection<PhysicsRigidBody> getRigidBodyList() { return new LinkedList<PhysicsRigidBody>(physicsBodies.values()); } public Collection<PhysicsGhostObject> getGhostObjectList() { return new LinkedList<PhysicsGhostObject>(physicsGhostObjects.values()); } public Collection<PhysicsCharacter> getCharacterList() { return new LinkedList<PhysicsCharacter>(physicsCharacters.values()); } public Collection<PhysicsJoint> getJointList() { return new LinkedList<PhysicsJoint>(physicsJoints.values()); } public Collection<PhysicsVehicle> getVehicleList() { return new LinkedList<PhysicsVehicle>(physicsVehicles.values()); } /** * Sets the gravity of the PhysicsSpace, set before adding physics objects! * * @param gravity */ public void setGravity(Vector3f gravity) { this.gravity.set(gravity); setGravity(physicsSpaceId, gravity); } private native void setGravity(long spaceId, Vector3f gravity); //TODO: getGravity private final Vector3f gravity = new Vector3f(0,-9.81f,0); public Vector3f getGravity(Vector3f gravity) { return gravity.set(this.gravity); } // /** // * applies gravity value to all objects // */ // public void applyGravity() { //// dynamicsWorld.applyGravity(); // /** // * clears forces of all objects // */ // public void clearForces() { //// dynamicsWorld.clearForces(); /** * Adds the specified listener to the physics tick listeners. The listeners * are called on each physics step, which is not necessarily each frame but * is determined by the accuracy of the physics space. * * @param listener */ public void addTickListener(PhysicsTickListener listener) { tickListeners.add(listener); } public void removeTickListener(PhysicsTickListener listener) { tickListeners.remove(listener); } /** * Adds a CollisionListener that will be informed about collision events * * @param listener the CollisionListener to add */ public void addCollisionListener(PhysicsCollisionListener listener) { collisionListeners.add(listener); } /** * Removes a CollisionListener from the list * * @param listener the CollisionListener to remove */ public void removeCollisionListener(PhysicsCollisionListener listener) { collisionListeners.remove(listener); } /** * Adds a listener for a specific collision group, such a listener can * disable collisions when they happen.<br> There can be only one listener * per collision group. * * @param listener * @param collisionGroup */ public void addCollisionGroupListener(PhysicsCollisionGroupListener listener, int collisionGroup) { collisionGroupListeners.put(collisionGroup, listener); } public void removeCollisionGroupListener(int collisionGroup) { collisionGroupListeners.remove(collisionGroup); } /** * Performs a ray collision test and returns the results as a list of * PhysicsRayTestResults */ public List rayTest(Vector3f from, Vector3f to) { List results = new LinkedList(); rayTest(from, to, results); return (List<PhysicsRayTestResult>) results; } public void SetRayTestFlags(int flags) { rayTestFlags = flags; } public int GetRayTestFlags() { return rayTestFlags; } /** * Performs a ray collision test and returns the results as a list of * PhysicsRayTestResults */ public List<PhysicsRayTestResult> rayTest(Vector3f from, Vector3f to, List<PhysicsRayTestResult> results) { results.clear(); rayTest_native(from, to, physicsSpaceId, results, rayTestFlags); return results; } public native void rayTest_native(Vector3f from, Vector3f to, long physicsSpaceId, List<PhysicsRayTestResult> results, int flags); // private class InternalRayListener extends CollisionWorld.RayResultCallback { // private List<PhysicsRayTestResult> results; // public InternalRayListener(List<PhysicsRayTestResult> results) { // this.results = results; // @Override // public float addSingleResult(LocalRayResult lrr, boolean bln) { // PhysicsCollisionObject obj = (PhysicsCollisionObject) lrr.collisionObject.getUserPointer(); // results.add(new PhysicsRayTestResult(obj, Converter.convert(lrr.hitNormalLocal), lrr.hitFraction, bln)); // return lrr.hitFraction; /** * Performs a sweep collision test and returns the results as a list of * PhysicsSweepTestResults<br/> You have to use different Transforms for * start and end (at least distance > 0.4f). SweepTest will not see a * collision if it starts INSIDE an object and is moving AWAY from its * center. */ public List<PhysicsSweepTestResult> sweepTest(CollisionShape shape, Transform start, Transform end) { List results = new LinkedList(); sweepTest(shape, start, end , results); return (List<PhysicsSweepTestResult>) results; } public List<PhysicsSweepTestResult> sweepTest(CollisionShape shape, Transform start, Transform end, List<PhysicsSweepTestResult> results) { return sweepTest(shape, start, end, results, 0.0f); } public native void sweepTest_native(long shape, Transform from, Transform to, long physicsSpaceId, List<PhysicsSweepTestResult> results, float allowedCcdPenetration); /** * Performs a sweep collision test and returns the results as a list of * PhysicsSweepTestResults<br/> You have to use different Transforms for * start and end (at least distance > allowedCcdPenetration). SweepTest will not see a * collision if it starts INSIDE an object and is moving AWAY from its * center. */ public List<PhysicsSweepTestResult> sweepTest(CollisionShape shape, Transform start, Transform end, List<PhysicsSweepTestResult> results, float allowedCcdPenetration ) { results.clear(); sweepTest_native(shape.getObjectId(), start, end, physicsSpaceId, results, allowedCcdPenetration); return results; } /* private class InternalSweepListener extends CollisionWorld.ConvexResultCallback { private List<PhysicsSweepTestResult> results; public InternalSweepListener(List<PhysicsSweepTestResult> results) { this.results = results; } @Override public float addSingleResult(LocalConvexResult lcr, boolean bln) { PhysicsCollisionObject obj = (PhysicsCollisionObject) lcr.hitCollisionObject.getUserPointer(); results.add(new PhysicsSweepTestResult(obj, Converter.convert(lcr.hitNormalLocal), lcr.hitFraction, bln)); return lcr.hitFraction; } } */ /** * destroys the current PhysicsSpace so that a new one can be created */ public void destroy() { physicsBodies.clear(); physicsJoints.clear(); // dynamicsWorld.destroy(); // dynamicsWorld = null; } /** * // * used internally // * * @return the dynamicsWorld // */ public long getSpaceId() { return physicsSpaceId; } public BroadphaseType getBroadphaseType() { return broadphaseType; } public void setBroadphaseType(BroadphaseType broadphaseType) { this.broadphaseType = broadphaseType; } /** * Sets the maximum amount of extra steps that will be used to step the * physics when the fps is below the physics fps. Doing this maintains * determinism in physics. For example a maximum number of 2 can compensate * for framerates as low as 30fps when the physics has the default accuracy * of 60 fps. Note that setting this value too high can make the physics * drive down its own fps in case its overloaded. * * @param steps The maximum number of extra steps, default is 4. */ public void setMaxSubSteps(int steps) { maxSubSteps = steps; } /** * get the current accuracy of the physics computation * * @return the current accuracy */ public float getAccuracy() { return accuracy; } /** * sets the accuracy of the physics computation, default=1/60s<br> * * @param accuracy */ public void setAccuracy(float accuracy) { this.accuracy = accuracy; } public Vector3f getWorldMin() { return worldMin; } /** * only applies for AXIS_SWEEP broadphase * * @param worldMin */ public void setWorldMin(Vector3f worldMin) { this.worldMin.set(worldMin); } public Vector3f getWorldMax() { return worldMax; } /** * only applies for AXIS_SWEEP broadphase * * @param worldMax */ public void setWorldMax(Vector3f worldMax) { this.worldMax.set(worldMax); } /** * Set the number of iterations used by the contact solver. * * The default is 10. Use 4 for low quality, 20 for high quality. * * @param numIterations The number of iterations used by the contact & constraint solver. */ public void setSolverNumIterations(int numIterations) { this.solverNumIterations = numIterations; setSolverNumIterations(physicsSpaceId, numIterations); } /** * Get the number of iterations used by the contact solver. * * @return The number of iterations used by the contact & constraint solver. */ public int getSolverNumIterations() { return solverNumIterations; } private native void setSolverNumIterations(long physicsSpaceId, int numIterations); public static native void initNativePhysics(); /** * interface with Broadphase types */ public enum BroadphaseType { /** * basic Broadphase */ SIMPLE, /** * better Broadphase, needs worldBounds , max Object number = 16384 */ AXIS_SWEEP_3, /** * better Broadphase, needs worldBounds , max Object number = 65536 */ AXIS_SWEEP_3_32, /** * Broadphase allowing quicker adding/removing of physics objects */ DBVT; } @Override protected void finalize() throws Throwable { super.finalize(); Logger.getLogger(this.getClass().getName()).log(Level.FINE, "Finalizing PhysicsSpace {0}", Long.toHexString(physicsSpaceId)); finalizeNative(physicsSpaceId); } private native void finalizeNative(long objectId); }
package edu.isi.karma.util; import org.json.JSONArray; import org.json.JSONObject; import org.json.JSONException; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class KarmaStats { /* Instance Variables*/ private String inputFile; private String outputFile; boolean isPretty; public KarmaStats(CommandLine cl) { isPretty = false; } public static void main(String[] args) { Options options = createCommandLineOptions(); CommandLine cl = parseCommandLine(args, options); if(cl==null) { System.out.println("Error Parsing Command Line Arguments"); return; } try { KarmaStats stats = new KarmaStats(cl); if(!stats.parseCommandLineOptions(cl)) { System.out.println("Parse ERROR"); return; } karmaStats(stats.inputFile, stats.outputFile,stats.isPretty); } catch (Exception e) { e.printStackTrace(); } } public static void karmaStats(String inputFile, String outputFile,boolean isPretty) { try { FileReader filereader = new FileReader(inputFile); BufferedReader bufferedReader = new BufferedReader(filereader); String tmpString = null; StringBuffer buf = new StringBuffer(); String[] fileSplit = inputFile.split("/"); String[] fname = fileSplit[fileSplit.length - 1].split("\\."); StringBuffer nameBuf = new StringBuffer(); /* * If model name has "." in the name. * */ if(fname.length>2) { for(int j=0;j<fname.length-1;j++) { nameBuf.append(fname[j]); } } String modelName = nameBuf.toString(); final String matchDoublequote = "\\\""; final String newDoublequote = "\""; final String matchSlash = "\\\\"; final String newSlash = "\\"; final String pyTransformCommandName = "SubmitPythonTransformationCommand"; final String setSemanticCommandName = "SetSemanticTypeCommand"; final String setPropertyCommandName = "SetMetaPropertyCommand"; final String addLinkCommandName = "AddLinkCommand"; final String deleteLinkCommandName = "DeleteLinkCommand"; final String changeLinkCommandName = "ChangeInternalNodeLinksCommand"; final String unassignSemeticCommandName = "UnassignSemanticTypeCommand"; final String selectionCommandName = "OperateSelectionCommand"; boolean isJSON = false; int pyTransformCount = 0; int SemanticTypeCount = 0; int classCount = 0; int linkCount = 0; // Except sementic type links int filterCount = 0; while ((tmpString = bufferedReader.readLine()) != null) { if (isJSON) { if (tmpString.contains("]\"\"\"")) { buf.append(']'); break; } buf.append(tmpString); } else { if (tmpString.contains("hasWorksheetHistory")) { buf.append('['); isJSON = true; } } } if (isJSON) { classCount = countClass(bufferedReader); String bufString = buf.toString(); String removedQuote = bufString.replace(matchDoublequote, newDoublequote); String removedSlash = removedQuote .replace(matchSlash, newSlash); JSONArray commands = new JSONArray(removedSlash); /* * Compare all commands and classify according to names */ for (int i = 0; i < commands.length(); i++) { JSONObject command = (JSONObject) commands.get(i); String commandName = command.getString("commandName"); if (commandName.equals(pyTransformCommandName)) { pyTransformCount++; } else if (commandName.equals(setSemanticCommandName)) { SemanticTypeCount++; } else if (commandName.equals(setPropertyCommandName)) { SemanticTypeCount++; } else if (commandName.equals(addLinkCommandName)) { linkCount++; } else if (commandName.equals(deleteLinkCommandName)) { linkCount } else if (commandName.equals(selectionCommandName)) { filterCount++; } else if (commandName.equals(unassignSemeticCommandName)) { SemanticTypeCount } else if(commandName.equals(changeLinkCommandName)) { linkCount++; } } } FileWriter out = new FileWriter(outputFile); BufferedWriter bufferedWriter = new BufferedWriter(out); StringBuffer writeBuffer = new StringBuffer(); JSONObject output = new JSONObject(); JSONObject modelStat = new JSONObject(); modelStat.put("modelName", modelName); output.put("pyTransformations", pyTransformCount); output.put("semanticTypes", SemanticTypeCount); output.put("class", classCount); output.put("links", linkCount); output.put("filters", filterCount); modelStat.put("modelStatistics", output); if(isPretty) { writeBuffer.append(modelStat.toString(4)); } else { writeBuffer.append(modelStat.toString(0)); } bufferedWriter.write(writeBuffer.toString()); bufferedReader.close(); bufferedWriter.close(); } catch (JSONException e) { e.printStackTrace(); System.out.println("Failed to Parse JSON"); } catch (IOException e) { e.printStackTrace(); System.out.println("Error in reading/writing File"); } catch (Exception e) { e.printStackTrace(); } } /* * This method counts number of classes based on rr-class count in TTL file */ public static int countClass(BufferedReader reader) { int classCount = 0; try { String tmpString = null; while ((tmpString = reader.readLine()) != null) { if (tmpString.contains("rr:class")) { classCount++; } } } catch (IOException e) { e.printStackTrace(); } return classCount; } private static CommandLine parseCommandLine(String args[], Options options) { CommandLineParser parser = new BasicParser(); CommandLine cl = null; try { /** * PARSE THE COMMAND LINE ARGUMENTS * */ cl = parser.parse(options, args); if (cl == null || cl.getOptions().length == 0) { return null; } } catch (Exception e) { return cl; } return cl; } private static Options createCommandLineOptions() { Options options = new Options(); options.addOption(new Option("inputfile", "inputfile", true, "Input TTL File")); options.addOption(new Option("outputfile", "outputfile", true, "location of the output file with name")); options.addOption(new Option("pretty", "pretty", false, "JSON or JSONLines selection")); return options; } private boolean parseCommandLineOptions(CommandLine cl) { String isPretty; inputFile = (String) cl.getOptionValue("inputfile"); if(inputFile==null) { System.out.println("Please provide input File"); return false; } outputFile = (String) cl.getOptionValue("outputfile","KarmaStats.json"); isPretty = (String) cl.getOptionValue("pretty","false"); if(!isPretty.equals("false")) { isPretty = "true"; } this.isPretty = Boolean.parseBoolean(isPretty); return true; } }
package com.lucythemoocher.graphics; import com.lucythemoocher.Globals.Globals; import com.lucythemoocher.actors.PlayerCharacter; import com.lucythemoocher.controls.GlobalController; import com.lucythemoocher.physics.Box; import com.lucythemoocher.util.Direction; import com.lucythemoocher.util.Resources; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Align; import android.graphics.RectF; import android.graphics.Typeface; import android.util.SparseArray; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; /** * Render Drawables and Background * Handle scrolling * Camera's system is used in MasterLoop * Camera is not the physical screen, but a representation of the screen, so w() et h() are independent from the * hardware screen's size. * @see MasterLoop */ public class Camera extends SurfaceView implements SurfaceHolder.Callback { private static final float CAMERASPEED = 2f; static final float BACKGROUNDSPEED = 0.5f; private static float DT_ = 1; private Box screen_; // hardware screen's size private Canvas canvas_; private float currX_; private float currY_; private float scale_; // coefficient depending on hardware screen's size private boolean canDraw_ = false; private SparseArray<Paint> hudPaints_; private RectF hudOval_; /** * Constructor */ public Camera() { super(Resources.getActivity()); float h = Resources.getActivity().getWindowManager().getDefaultDisplay().getHeight(); float w = Resources.getActivity().getWindowManager().getDefaultDisplay().getWidth(); currX_ = 1; currY_ = 1; screen_ = new Box(currX_,currY_,h,w); getHolder().addCallback(this); setFocusable(true); scale_ = screen_.getW() / 1200f; hudPaints_ = new SparseArray<Paint>(); initHudColors(new int[] {Color.GRAY, Color.BLACK}, h); hudOval_ = new RectF(-w/10, -w/10, w+w/10, h+w/10); setSpeed(1.0f / 30.0f); this.requestFocus(); this.setFocusableInTouchMode(true); } /** * Target a position at the middle of the screen * @param x coor * @param y coor */ public void moveTo(float x, float y) { currX_ = x; currY_ = y; screen_.setX((currX_ - w() / 2)); screen_.setY((currY_ - h() / 2)); } /** * Initialize the HUD colors * @param colorArray colors to initialize */ private void initHudColors(int colorArray[], float h) { for (int color : colorArray) { Paint currPaint = new Paint(); currPaint.setStrokeWidth(h*0.40f); currPaint.setStyle(Paint.Style.STROKE); currPaint.setColor(color); currPaint.setAlpha(50); hudPaints_.put(color, currPaint); } } /** * Update position of the camera */ public void update() { PlayerCharacter pc = Globals.getInstance().getGame().getCharacter(); // follow player if exists if (pc != null) { followPoint( pc.getCinematic().getTargetX(), pc.getCinematic().getTargetY()); } } /** * Getter */ public Box getScreen() { Box scaledScreen = new Box(screen_); scaledScreen.setH(scaledScreen.getH() / scale_); scaledScreen.setW(scaledScreen.getW() / scale_); return scaledScreen; } /** * Follow the point (x, y) without exceeding camera's speed * @param x * @param y */ public void followPoint(float x, float y) { float coeff = camSpeed() * Globals.getInstance().getGame().getDt(); float diffX = x - currX_; float diffY = y - currY_; if (diffX == 0 && diffY == 0) { return; } float ratio = (float) Math.sqrt(Math.abs(diffX) + Math.abs(diffY)); if (coeff / ratio < 1) { currX_ += diffX / ratio * coeff; currY_ += diffY / ratio * coeff; } else { currX_ += diffX; currY_ += diffY; } screen_.setX((currX_ - w() / 2)); screen_.setY((currY_ - h() / 2)); } /** * Must be called before renderings * This locking is currently handled in the MasterLoop * @return true if managed to create the canvas * @see unlockScreen * @see MasterLoop */ public boolean lockScreen() { canvas_ = getHolder().lockCanvas(); return canvas_ != null; } /** * Graphical operation to perform before drawing things * Assume the canvas is not null */ public void prepare() { canvas_.scale(scale_, scale_); } /** * Must be called after renderings, to unlock canvas * Assumes the canvas is not null * @see lockScreen */ public void unlockScreen() { getHolder().unlockCanvasAndPost(canvas_); } /** * Getter * @return True when Camera is ready for rendering */ public boolean canDraw() { return canDraw_; } /** * Getter * @return Camera's speed * * This is just a coeff used, the speed also depends on the distance with * the target point */ private float camSpeed() { return CAMERASPEED*DT_; } /** * Getter * @return Camera's height in dp pixels * * Doesn't depend on the hardware screen's size * @see #physicalH() */ public float h() { return screen_.getH() / scale_; } /** * Getter * @return Camera's width in dp pixels * * Doesn't depend on the hardware screen's size * @see #physicalW() */ public float w() { return screen_.getW() / scale_; } /** * Getter * @return height of the physical screen (real resolution) */ public float physicalH() { return screen_.getH(); } /** * Getter * @return width of the physical screen (real resolution) */ public float physicalW() { return screen_.getW(); } /** * Draw the full screen with color * @param color */ public void drawFullColor(int color) { canvas_.drawColor(color); } /** * Draw text in the middle of the screen * @param text * @param color */ public void drawCenterText(String text, int color) { Paint textPaint = new Paint(); textPaint.setColor(color); textPaint.setTextAlign(Align.CENTER); textPaint.setTextSize(60); textPaint.setTypeface(Typeface.create("Arial",Typeface.BOLD)); canvas_.scale(1/scale_, 1/scale_); canvas_.drawText(text, 200, physicalH()/2, textPaint); canvas_.scale(scale_, scale_); } /** * Draw the image at the position x y * Screen must be locked * @param x x position in dp pixels * @param y y position in dp pixels * @param image * @see #lockScreen() */ public void drawImage(float x, float y, Image image) { float xx = x - offsetx() ; float yy = y - offsety() ; canvas_.drawBitmap(image.getBitmap().getBitmap(), xx, yy, image.getBitmap().getPaint()); } /** * Draw the image without using the scrolling * @param x position in dp pixels * @param y y position in dp pixels * @param image * @see #lockScreen() */ public void drawImageOnHud(float x, float y, Image image) { canvas_.drawBitmap(image.getBitmap().getBitmap(), x, y, image.getBitmap().getPaint()); } /** * Draw the HUD ellipsis, insensitive to scale * @param dir * @param c */ public void drawControlOnHud(int dir, int c) { int start_radix = 0; int radix_range = 90; int big_radix = 90; int small_radix = 180 - big_radix; if (dir == Direction.UP) { start_radix = -90 - big_radix / 2; radix_range = big_radix; } else if (dir == Direction.RIGHT) { start_radix = 0 - small_radix / 2; radix_range = small_radix; } else if (dir == Direction.DOWN) { start_radix = 90 - big_radix / 2; radix_range = big_radix; } else if (dir == Direction.LEFT) { start_radix = 180 - small_radix / 2; radix_range = small_radix; } // Insensitive to scale (quite dirty :s) canvas_.scale(1/scale_, 1/scale_); canvas_.drawArc(hudOval_, start_radix, radix_range, false, hudPaints_.get(c)); canvas_.scale(scale_, scale_); } /** * Draw the background according to the camera position * Screen must be locked * @param background * @see #lockScreen() */ public void drawBackground(Background background) { float x = -(currX_ - screen_.getW() / 2) * BACKGROUNDSPEED; float y = -(currY_ - screen_.getH() / 2) * BACKGROUNDSPEED; float offsetX = screen_.getW() / 2; float offsetY = screen_.getH() / 2; background.draw(Math.abs(offsetX-x), Math.abs(offsetY-y)); } /** * Draw the background according to the camera position * Screen must be locked * @param * @param * @param * @see #lockScreen() */ void drawBackground(Image im, float x, float y) { canvas_.drawBitmap(im.getBitmap().getBitmap(), x, y, null); } /** * Mutator * @param dt New dt speed */ public static void setSpeed(float dt) { DT_ = dt; } public boolean onTouchEvent(MotionEvent event) { GlobalController.getInstance().process(event); return true; } public boolean onKeyDown (int keyCode, KeyEvent event) { GlobalController.getInstance().processKey(keyCode, event); return true; } public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {} public void surfaceCreated(SurfaceHolder arg0) { canDraw_ = true; } public void surfaceDestroyed(SurfaceHolder arg0) { canDraw_ = false; } public float offsetx() { return screen_.getX(); } public float offsety() { return screen_.getY(); } /** * Getter * @return current scale */ public float getScale() { return scale_; } }
package edu.gatech.oad.antlab.person; /** * A simple class for person 3 * returns their name and a * reversed string * * @author Bob * @version 1.1 */ public class Person3 { /** * Holds the persons real name */ private String name; /** * The constructor, takes in the persons * name * * @param pname the person's real name */ public Person3(String pname) { name = pname; } /** * Return a string rep of this object * that varies with an input string * * @param input the varying string * @return the string representing the * object */ public String toString(String input) { return name + calc(input); } /** * This method should take the string * input and return its reverse. * given "gtg123b" it should return * b321gtg. * * @param input the string to be reversed * @return the reversed string */ private String calc(String input) { //Person 3 put your implementation here if (input != null) { char[] helper = input.toCharArray(); int start = 0; int end = helper.length - 1; char temp; while (end > start) { temp = helper[start]; helper[start] = helper[end]; helper[end] = temp; end start++; } return input; } else { throw new IllegalArumentExecption("String was null."); } } }
package moinoue.mentalmath; import java.util.ArrayList; import java.util.regex.Pattern; public class Lexer implements TokenType { private ArrayList<Token> tokens; private String input; private int position; public Lexer(String input){ this.input = input.toLowerCase() + " EOL" ; this.position = 0; this.tokens = new ArrayList<Token>(); constructToken(); check(); } private void constructToken(){ String[] strArray = input.split("\\s"); for (int i = 0; i<strArray.length; i++){ if (strArray[i].startsWith("(")) { Token tok = new Token(LPAR, 0); tokens.add(tok); continue; } if (strArray[i].equals("right") && (strArray[i+1].equals("parenthesis") || strArray[i+1].equals("parentheses") || strArray[i+1].equals("parent")|| strArray[i+1].equals("paren"))) { Token tok = new Token(RPAR, 0); tokens.add(tok); continue; } if (strArray[i].endsWith(")")) { Token tok = new Token(RPAR, 0); tokens.add(tok); continue; } if (strArray[i].equals("left") && (strArray[i+1].equals("parenthesis")|| strArray[i+1].equals("parentheses") || strArray[i+1].equals("parent")|| strArray[i+1].equals("paren"))) { Token tok = new Token(LPAR, 0); tokens.add(tok); continue; } if (strArray[i].equals("plus")|| strArray[i].equals("+") || strArray[i] .equals("added") ){ if(strArray[i+1].equals("by")) { i++; } Token tok = new Token(PLUS, 0); tokens.add(tok); continue; } if (strArray[i].equals("minus")|| strArray[i].equals("-") || strArray[i].equals("subtracted" )){ if(strArray[i+1].equals("by")) { i++; } Token tok = new Token(MINUS, 0); tokens.add(tok); continue; } if (strArray[i].equals("times")|| strArray[i].equals("*") || strArray[i].equals("x") || strArray[i].equals("product") || strArray[i].equals("into") || strArray[i].equals("by") || strArray[i].equals("multiplied")){ if((strArray[i].equals("multiplied") || strArray[i].equals("times")) && strArray[i+1].equals("by")){ i++; } Token tok = new Token(MULT, 0); tokens.add(tok); continue; } if (strArray[i].equals("divide")|| strArray[i].equals("/") || strArray[i].equals("over") || strArray[i].equals("divided" )) { if (strArray[i + 1].equals("by")){ i++; } Token tok = new Token(DIV, 0); tokens.add(tok); continue; } if (strArray[i].equals("mod")|| strArray[i].equals("modulus" ) || strArray[i].equals( "%" )){ Token tok = new Token(MOD, 0); tokens.add(tok); continue; } if (strArray[i].equals("log") || strArray[i].equals("logarithm") ){ Token tok = new Token(LOG, 0); tokens.add(tok); continue; } if (strArray[i].equals("exp" ) || strArray[i].equals( "exponent") ){ Token tok = new Token(EXP, 0); tokens.add(tok); continue; } if (strArray[i].equals("power") || strArray[i].equals("pow") || strArray[i].equals("^")){ Token tok = new Token(POW, 0); tokens.add(tok); continue; } if ( strArray[i].equals("square" )&& strArray[i+1].equals( "root") ){ Token tok = new Token(SQRT, 0); tokens.add(tok); i++; continue; } if ( strArray[i].equals("cube") && strArray[i+1].equals( "root") ){ Token tok = new Token(CBRT, 0); tokens.add(tok); i++; continue; } if ( strArray[i].equals("root" )){ Token tok = new Token(ROOT, 0); tokens.add(tok); continue; } if ((strArray[i].equals("ark") || strArray[i].equals("arc") )&& (strArray[i+1].equals( "sine") || strArray[i+1].equals("sign") || strArray[i+1].equals("sin"))){ Token tok = new Token(ASIN, 0); tokens.add(tok); i++; continue; } if ( strArray[i].equals( "sine") || strArray[i].equals("sign")){ Token tok = new Token(SIN, 0); tokens.add(tok); continue; } if ((strArray[i].equals("ark") || strArray[i].equals("arc") )&& (strArray[i+1].equals( "cosine") || strArray[i+1].equals("cosign") || strArray[i+1].equals("cos"))){ Token tok = new Token(ACOS, 0); tokens.add(tok); i++; continue; } if ( strArray[i].equals( "cosine") || strArray[i].equals("cosign")){ Token tok = new Token(COS, 0); tokens.add(tok); continue; } if ((strArray[i].equals("ark") || strArray[i].equals("arc") )&& (strArray[i+1].equals( "tan") || strArray[i+1].equals("tangent"))){ Token tok = new Token(ATAN, 0); tokens.add(tok); i++; continue; } if ( strArray[i].equals( "tan") || strArray[i].equals("tangent")){ Token tok = new Token(TAN, 0); tokens.add(tok); continue; } if ( strArray[i].equals("negative")){ Token tok = new Token(NEG, 0); tokens.add(tok); continue; } if ( strArray[i].equals("positive")){ Token tok = new Token(POS, 0); tokens.add(tok); continue; } //Numbers if (Pattern.matches("[+-]?[0-9]*.[0-9]+", strArray[i])){ Token tok = new Token(NUMBERS, Float.parseFloat(strArray[i])); tokens.add(tok); continue; } if (Pattern.matches("[+-]?[0-9]+", strArray[i])){ Token tok = new Token(NUMBERS, Float.parseFloat(strArray[i])); tokens.add(tok); continue; } //Special cases if (strArray[i].equals("to") || strArray[i].equals("too")){ Token tok = new Token(NUMBERS, 2); tokens.add(tok); continue; } if (strArray[i].equals("EOL")){ Token tok = new Token(EOL, 0); tokens.add(tok); break; } } } public String output(){ String output = ""; for (int i = 0; i<tokens.size(); i++) { output += tokens.get(i).output() + " "; } return output; } //Used for debugging private void check(){ for (Token t: tokens){ t.check(); } } public int getPosition(){ return position -1; } //Pulls the current token and moves the position marker by one public Token getNextToken(){ Token tok = tokens.get(position); position++; return tok; } }
package com.exedio.copernica; import java.io.PrintStream; import java.util.List; import javax.servlet.http.HttpServletRequest; import com.exedio.cope.Feature; import com.exedio.cope.Function; import com.exedio.cope.Query; import com.exedio.cope.QueryInfo; import com.exedio.cope.Transaction; import com.exedio.cope.Type; import com.exedio.cops.Pager; final class TypeCop extends CopernicaCop { private static final String ORDER_ASCENDING = "oa"; private static final String ORDER_DESCENDING = "od"; private static final Pager.Config PAGER_CONFIG = new Pager.Config(10, 20, 50, 100, 200, 500); final Type<?> type; final Function<?> orderBy; final boolean orderAscending; final Pager pager; private Query.Result<?> queryResult = null; private List<QueryInfo> queryInfos; TypeCop(final CopernicaProvider provider, final CopernicaLanguage language, final Type<?> type) { this(provider, language, type, null, true, PAGER_CONFIG.newPager()); } TypeCop(final CopernicaProvider provider, final CopernicaLanguage language, final Type<?> type, final Function<?> orderBy, final boolean orderAscending, final Pager pager) { super("type", provider, language); this.type = type; this.orderBy = orderBy; this.orderAscending = orderAscending; this.pager = pager; addParameter(TYPE, type.getID()); // orderBy must be a feature if(orderBy!=null) addParameter(orderAscending ? ORDER_ASCENDING : ORDER_DESCENDING, cast(orderBy).getName()); pager.addParameters(this); } @SuppressWarnings("unchecked") // workaround for bug in javac private static Feature cast(final Function<?> o) { return (Feature)o; } @Override final CopernicaCop switchLanguage(final CopernicaLanguage newLanguage) { return new TypeCop(provider, newLanguage, type, orderBy, orderAscending, pager); } @Override final boolean isType(final Type<?> type) { return this.type == type; } @Override final String getTitle() { return provider.getDisplayName(language, type); } @Override final CopernicaCop toPrev() { return pager.isFirst() ? null : toPage(pager.previous()); } @Override final CopernicaCop toNext() { return pager.isLast() ? null : toPage(pager.next()); } final CopernicaCop toPage(final Pager pager) { return pager!=null ? new TypeCop(provider, language, type, orderBy, orderAscending, pager) : null; } final TypeCop orderBy(final Function<?> newOrderBy, final boolean ascending) { return new TypeCop(provider, language, type, newOrderBy, ascending, pager); } final List<?> getItems() { return queryResult.getData(); } final List<QueryInfo> getQueryInfos() { return queryInfos; } @Override void init(final HttpServletRequest request) { super.init(request); assert queryResult==null; final Query<?> query = type.newQuery(null); if(orderBy!=null) query.setOrderByAndThis(orderBy, orderAscending); else query.setOrderByThis(true); query.setLimit(pager.getOffset(), pager.getLimit()); final Transaction transaction = type.getModel().currentTransaction(); transaction.setQueryInfoEnabled(true); queryResult = query.searchAndTotal(); queryInfos = transaction.getQueryInfos(); transaction.setQueryInfoEnabled(false); pager.init(queryResult.getData().size(), queryResult.getTotal()); } @Override void writeBody(final PrintStream out) { TypeCop_Jspm.writeBody(out, this); } static final TypeCop getCop( final CopernicaProvider provider, final CopernicaLanguage language, final String typeID, final HttpServletRequest request) { final Type<?> type = provider.getModel().getType(typeID); if(type==null) throw new RuntimeException("type "+typeID+" not available"); final String orderAscendingID = request.getParameter(ORDER_ASCENDING); final String orderDescendingID = request.getParameter(ORDER_DESCENDING); final boolean orderAscending = orderAscendingID!=null; final String orderID = orderAscending ? orderAscendingID : orderDescendingID; final Function<?> orderBy = (orderID==null) ? null : (Function<?>)type.getFeature(orderID); return new TypeCop( provider, language, type, orderBy, orderAscending, PAGER_CONFIG.newPager(request)); } }
package ru.job4j; /** *Class Calculate - " , !" *@author YuZuzia (mailto: zuziayv@ya.ru) *@version %i%, %G% *@since 15.03.2017 */ public class Calculate{ /** * main " " * @param args - */ public static void main(String[] args){ System.out.println("Hello snowboard!"); } }
package aQute.lib.json; import java.io.*; import java.lang.reflect.*; import java.util.*; import aQute.lib.hex.*; public class ByteArrayHandler extends Handler { @Override void encode(Encoder app, Object object, Map<Object,Type> visited) throws IOException, Exception { StringHandler.string(app, Hex.toHexString((byte[]) object)); } @Override Object decodeArray(Decoder r) throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); ArrayList<Object> list = new ArrayList<Object>(); r.codec.parseArray(list, Byte.class, r); for (Object b : list) { out.write(((Byte) b).byteValue()); } return out.toByteArray(); } @Override Object decode(Decoder dec, String s) throws Exception { return Hex.toByteArray(s); } }
package cocoonClient.Panels; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import javax.swing.JTree; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import JSONTransmitProtocol.newcreater.JSONCreater; import JSONTransmitProtocol.newcreater.query.CreaterQuery; import JSONTransmitProtocol.newcreater.query.QueryQuestion; import cocoonClient.Component.*; import cocoonClient.Data.GetProblemSet; import cocoonClient.Data.UserInfo; import cocoonClient.Frame.SubmitFrame; public class ProblemsPanel extends AbstractDisplayPanel{ private JTree tree; private Browser browser; private HashMap<String, Integer> problemSet; private SubmitFrame submitFrame; public ProblemsPanel(){ super(UserInfo.getMainFrame()); problemSet = new GetProblemSet().getProblemSet(); this.setLayout(new BorderLayout()); this.submitFrame = new SubmitFrame(); initBrowser(); initTree(); initButtonPanel(); } private void initButtonPanel() { AbstractRightPanel panel = new ProblemsRightPanel(submitFrame); this.setRightPanel(panel); } private void initBrowser(){ browser = new Browser(); browser.loadURL("https://dl.dropboxusercontent.com/u/113630504/OJ/welcome.htm"); this.add(browser, BorderLayout.CENTER); } private void initTree() { //create the root node DefaultMutableTreeNode root = new DefaultMutableTreeNode("root"); //create the child nodes DefaultMutableTreeNode basic = new DefaultMutableTreeNode("Basic"); Iterator iter = problemSet.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); String key = (String) entry.getKey(); basic.add(new DefaultMutableTreeNode(key)); } DefaultMutableTreeNode intermediate = new DefaultMutableTreeNode("Intermediate"); intermediate.add(new DefaultMutableTreeNode("empty")); DefaultMutableTreeNode hard = new DefaultMutableTreeNode("Hard"); hard.add(new DefaultMutableTreeNode("empty")); //create the tree by passing in the root node root.add(basic); root.add(intermediate); root.add(hard); tree = new JTree(root); tree.setRootVisible(false); tree.getSelectionModel().addTreeSelectionListener(new TreeSelectionListener() { @Override public void valueChanged(TreeSelectionEvent e) { String selection; selection = tree.getLastSelectedPathComponent().toString(); if(problemSet.containsKey(selection)){ UserInfo.setPID(problemSet.get(selection)); submitFrame.changeProblemName(selection); String url = "https://dl.dropboxusercontent.com/u/176423666/OJ/" + problemSet.get(selection)+ ".html"; browser.loadURL(url); } } }); tree.setOpaque(false); tree.setPreferredSize(new Dimension(160, 500)); this.add(tree, BorderLayout.WEST); } @Override public void switchToThisPanel(){ super.switchToThisPanel(); JSONCreater json = new JSONCreater("query") .setInfo(UserInfo.getUserInfo()) .setQuery(new CreaterQuery("question", new QueryQuestion("problemrate", UserInfo.getPID()))); UserInfo.getClient().sendMessage(json.toString()); } }
package com.m12y.ld28.core; import com.badlogic.gdx.Input; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.*; public class LD28 implements ApplicationListener { public static final int WIDTH = 1024; public static final int HEIGHT = 768; Texture texture; SpriteBatch batch; float elapsed; OrthographicCamera camera; World world; private Box2DDebugRenderer debugRenderer; private Body body; @Override public void create () { texture = new Texture(Gdx.files.internal("libgdx-logo.png")); batch = new SpriteBatch(); camera = new OrthographicCamera(); camera.setToOrtho(false, 16, 12); world = new World(new Vector2(0, 0), true); debugRenderer = new Box2DDebugRenderer(); BodyDef bodyDef = new BodyDef(); bodyDef.type = BodyDef.BodyType.DynamicBody; bodyDef.position.set(6, 6); bodyDef.linearDamping = 4f; bodyDef.fixedRotation = true; body = world.createBody(bodyDef); PolygonShape shape = new PolygonShape(); shape.setAsBox(1, 1); FixtureDef fixtureDef = new FixtureDef(); fixtureDef.shape = shape; fixtureDef.density = 1f; fixtureDef.restitution = 0.2f; Fixture fixture = body.createFixture(fixtureDef); shape.dispose(); ChainShape chain = new ChainShape(); float[] wall = new float[]{ 10, 0, 10, 10, 0, 10, 0, 20, -10, 20, -10, 10, -10, 0, 0, 0, 0, -10, 10, -10, 10, 0, }; chain.createChain(wall); BodyDef wallDef = new BodyDef(); wallDef.type = BodyDef.BodyType.StaticBody; Body wallBody = world.createBody(wallDef); wallBody.createFixture(chain, 0); chain.dispose(); } @Override public void resize (int width, int height) { } @Override public void render () { elapsed += Gdx.graphics.getDeltaTime(); Gdx.gl.glClearColor(0, 0, 0, 0); Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); camera.update(); debugRenderer.render(world, camera.combined); update(); camera.translate(body.getPosition().x - camera.position.x, body.getPosition().y - camera.position.y); } private void update() { world.step(1/60f, 6, 2); Vector2 vel = body.getLinearVelocity(); Vector2 pos = body.getPosition(); float maxVelocity = 10f; float impulse = 3f; if (Gdx.input.isKeyPressed(Input.Keys.RIGHT) && vel.x < maxVelocity) { body.applyLinearImpulse(impulse, 0, pos.x, pos.y, true); } if (Gdx.input.isKeyPressed(Input.Keys.LEFT) && vel.x > -maxVelocity) { body.applyLinearImpulse(-impulse, 0, pos.x, pos.y, true); } if (Gdx.input.isKeyPressed(Input.Keys.UP) && vel.y < maxVelocity) { body.applyLinearImpulse(0, impulse, pos.x, pos.y, true); } if (Gdx.input.isKeyPressed(Input.Keys.DOWN) && vel.y > -maxVelocity) { body.applyLinearImpulse(0, -impulse, pos.x, pos.y, true); } } @Override public void pause () { } @Override public void resume () { } @Override public void dispose () { } }
package hudson.model; import hudson.RelativePath; import hudson.XmlFile; import hudson.BulkChange; import hudson.Util; import static hudson.Util.singleQuote; import hudson.diagnosis.OldDataMonitor; import hudson.model.listeners.SaveableListener; import hudson.util.ReflectionUtils; import hudson.util.ReflectionUtils.Parameter; import hudson.views.ListViewColumn; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.kohsuke.stapler.*; import org.springframework.util.StringUtils; import org.jvnet.tiger_types.Types; import org.apache.commons.io.IOUtils; import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND; import javax.servlet.ServletException; import javax.servlet.RequestDispatcher; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.HashMap; import java.util.Locale; import java.util.Arrays; import java.util.Collections; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; import java.util.logging.Logger; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Type; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.beans.Introspector; /** * Metadata about a configurable instance. * * <p> * {@link Descriptor} is an object that has metadata about a {@link Describable} * object, and also serves as a factory (in a way this relationship is similar * to {@link Object}/{@link Class} relationship. * * A {@link Descriptor}/{@link Describable} * combination is used throughout in Hudson to implement a * configuration/extensibility mechanism. * * <p> * Take the list view support as an example, which is implemented * in {@link ListView} class. Whenever a new view is created, a new * {@link ListView} instance is created with the configuration * information. This instance gets serialized to XML, and this instance * will be called to render the view page. This is the job * of {@link Describable} &mdash; each instance represents a specific * configuration of a view (what projects are in it, regular expression, etc.) * * <p> * For Hudson to create such configured {@link ListView} instance, Hudson * needs another object that captures the metadata of {@link ListView}, * and that is what a {@link Descriptor} is for. {@link ListView} class * has a singleton descriptor, and this descriptor helps render * the configuration form, remember system-wide configuration, and works as a factory. * * <p> * {@link Descriptor} also usually have its associated views. * * * <h2>Persistence</h2> * <p> * {@link Descriptor} can persist data just by storing them in fields. * However, it is the responsibility of the derived type to properly * invoke {@link #save()} and {@link #load()}. * * <h2>Reflection Enhancement</h2> * {@link Descriptor} defines addition to the standard Java reflection * and provides reflective information about its corresponding {@link Describable}. * These are primarily used by tag libraries to * keep the Jelly scripts concise. * * @author Kohsuke Kawaguchi * @see Describable */ public abstract class Descriptor<T extends Describable<T>> implements Saveable { /** * Up to Hudson 1.61 this was used as the primary persistence mechanism. * Going forward Hudson simply persists all the non-transient fields * of {@link Descriptor}, just like others, so this is pointless. * * @deprecated since 2006-11-16 */ @Deprecated private transient Map<String,Object> properties; /** * The class being described by this descriptor. */ public transient final Class<? extends T> clazz; private transient final Map<String,String> checkMethods = new ConcurrentHashMap<String,String>(); /** * Lazily computed list of properties on {@link #clazz} and on the descriptor itself. */ private transient volatile Map<String, PropertyType> propertyTypes,globalPropertyTypes; /** * Represents a readable property on {@link Describable}. */ public static final class PropertyType { public final Class clazz; public final Type type; private volatile Class itemType; PropertyType(Class clazz, Type type) { this.clazz = clazz; this.type = type; } PropertyType(Field f) { this(f.getType(),f.getGenericType()); } PropertyType(Method getter) { this(getter.getReturnType(),getter.getGenericReturnType()); } public Enum[] getEnumConstants() { return (Enum[])clazz.getEnumConstants(); } /** * If the property is a collection/array type, what is an item type? */ public Class getItemType() { if(itemType==null) itemType = computeItemType(); return itemType; } private Class computeItemType() { if(clazz.isArray()) { return clazz.getComponentType(); } if(Collection.class.isAssignableFrom(clazz)) { Type col = Types.getBaseClass(type, Collection.class); if (col instanceof ParameterizedType) return Types.erasure(Types.getTypeArgument(col,0)); else return Object.class; } return null; } /** * Returns {@link Descriptor} whose 'clazz' is the same as {@link #getItemType() the item type}. */ public Descriptor getItemTypeDescriptor() { return Hudson.getInstance().getDescriptor(getItemType()); } public Descriptor getItemTypeDescriptorOrDie() { return Hudson.getInstance().getDescriptorOrDie(getItemType()); } /** * Returns all the descriptors that produce types assignable to the item type. */ public List<? extends Descriptor> getApplicableDescriptors() { return Hudson.getInstance().getDescriptorList(clazz); } } protected Descriptor(Class<? extends T> clazz) { this.clazz = clazz; // doing this turns out to be very error prone, // as field initializers in derived types will override values. // load(); } /** * Infers the type of the corresponding {@link Describable} from the outer class. * This version works when you follow the common convention, where a descriptor * is written as the static nested class of the describable class. * * @since 1.278 */ protected Descriptor() { this.clazz = (Class<T>)getClass().getEnclosingClass(); if(clazz==null) throw new AssertionError(getClass()+" doesn't have an outer class. Use the constructor that takes the Class object explicitly."); // detect an type error Type bt = Types.getBaseClass(getClass(), Descriptor.class); if (bt instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) bt; // this 't' is the closest approximation of T of Descriptor<T>. Class t = Types.erasure(pt.getActualTypeArguments()[0]); if(!t.isAssignableFrom(clazz)) throw new AssertionError("Outer class "+clazz+" of "+getClass()+" is not assignable to "+t+". Perhaps wrong outer class?"); } // detect a type error. this Descriptor is supposed to be returned from getDescriptor(), so make sure its type match up. try { Method getd = clazz.getMethod("getDescriptor"); if(!getd.getReturnType().isAssignableFrom(getClass())) { throw new AssertionError(getClass()+" must be assignable to "+getd.getReturnType()); } } catch (NoSuchMethodException e) { throw new AssertionError(getClass()+" is missing getDescriptor method."); } } /** * Human readable name of this kind of configurable object. */ public abstract String getDisplayName(); /** * Uniquely identifies this {@link Descriptor} among all the other {@link Descriptor}s. * * <p> * Historically {@link #clazz} is assumed to be unique, so this method uses that as the default, * but if you are adding {@link Descriptor}s programmatically for the same type, you can change * this to disambiguate them. * * @return * Stick to valid Java identifier character, plus '.', which had to be allowed for historical reasons. * * @since 1.391 */ public String getId() { return clazz.getName(); } /** * Gets the URL that this Descriptor is bound to, relative to the nearest {@link DescriptorByNameOwner}. * Since {@link Hudson} is a {@link DescriptorByNameOwner}, there's always one such ancestor to any request. */ public String getDescriptorUrl() { return "descriptorByName/"+getId(); } private String getCurrentDescriptorByNameUrl() { StaplerRequest req = Stapler.getCurrentRequest(); Ancestor a = req.findAncestor(DescriptorByNameOwner.class); return a.getUrl(); } /** * If the field "xyz" of a {@link Describable} has the corresponding "doCheckXyz" method, * return the form-field validation string. Otherwise null. * <p> * This method is used to hook up the form validation method to the corresponding HTML input element. */ public String getCheckUrl(String fieldName) { String method = checkMethods.get(fieldName); if(method==null) { method = calcCheckUrl(fieldName); checkMethods.put(fieldName,method); } if (method.equals(NONE)) // == would do, but it makes IDE flag a warning return null; // put this under the right contextual umbrella. // a is always non-null because we already have Hudson as the sentinel return singleQuote(getCurrentDescriptorByNameUrl()+'/')+'+'+method; } private String calcCheckUrl(String fieldName) { String capitalizedFieldName = StringUtils.capitalize(fieldName); Method method = ReflectionUtils.getPublicMethodNamed(getClass(),"doCheck"+ capitalizedFieldName); if(method==null) return NONE; return singleQuote(getDescriptorUrl() +"/check"+capitalizedFieldName) + buildParameterList(method, new StringBuilder()).append(".toString()"); } /** * Builds query parameter line by figuring out what should be submitted */ private StringBuilder buildParameterList(Method method, StringBuilder query) { for (Parameter p : ReflectionUtils.getParameters(method)) { QueryParameter qp = p.annotation(QueryParameter.class); if (qp!=null) { String name = qp.value(); if (name.length()==0) name = p.name(); if (name==null || name.length()==0) continue; // unknown parameter name. we'll report the error when the form is submitted. RelativePath rp = p.annotation(RelativePath.class); if (rp!=null) name = rp.value()+'/'+name; if (query.length()==0) query.append("+qs(this)"); if (name.equals("value")) { // The special 'value' parameter binds to the the current field query.append(".addThis()"); } else { query.append(".nearBy('"+name+"')"); } continue; } Method m = ReflectionUtils.getPublicMethodNamed(p.type(), "fromStapler"); if (m!=null) buildParameterList(m,query); } return query; } /** * Computes the list of other form fields that the given field depends on, via the doFillXyzItems method, * and sets that as the 'fillDependsOn' attribute. Also computes the URL of the doFillXyzItems and * sets that as the 'fillUrl' attribute. */ public void calcFillSettings(String field, Map<String,Object> attributes) { String capitalizedFieldName = StringUtils.capitalize(field); String methodName = "doFill" + capitalizedFieldName + "Items"; Method method = ReflectionUtils.getPublicMethodNamed(getClass(), methodName); if(method==null) throw new IllegalStateException(String.format("%s doesn't have the %s method for filling a drop-down list", getClass(), methodName)); // build query parameter line by figuring out what should be submitted List<String> depends = buildFillDependencies(method, new ArrayList<String>()); if (!depends.isEmpty()) attributes.put("fillDependsOn",Util.join(depends," ")); attributes.put("fillUrl", String.format("%s/%s/fill%sItems", getCurrentDescriptorByNameUrl(), getDescriptorUrl(), capitalizedFieldName)); } private List<String> buildFillDependencies(Method method, List<String> depends) { for (Parameter p : ReflectionUtils.getParameters(method)) { QueryParameter qp = p.annotation(QueryParameter.class); if (qp!=null) { String name = qp.value(); if (name.length()==0) name = p.name(); if (name==null || name.length()==0) continue; // unknown parameter name. we'll report the error when the form is submitted. RelativePath rp = p.annotation(RelativePath.class); if (rp!=null) name = rp.value()+'/'+name; depends.add(name); continue; } Method m = ReflectionUtils.getPublicMethodNamed(p.type(), "fromStapler"); if (m!=null) buildFillDependencies(m,depends); } return depends; } /** * Computes the auto-completion setting */ public void calcAutoCompleteSettings(String field, Map<String,Object> attributes) { String capitalizedFieldName = StringUtils.capitalize(field); String methodName = "doAutoComplete" + capitalizedFieldName; Method method = ReflectionUtils.getPublicMethodNamed(getClass(), methodName); if(method==null) return; // no auto-completion attributes.put("autoCompleteUrl", String.format("%s/%s/autoComplete%s", getCurrentDescriptorByNameUrl(), getDescriptorUrl(), capitalizedFieldName)); } /** * Used by Jelly to abstract away the handlign of global.jelly vs config.jelly databinding difference. */ public PropertyType getPropertyType(Object instance, String field) { // in global.jelly, instance==descriptor return instance==this ? getGlobalPropertyType(field) : getPropertyType(field); } /** * Obtains the property type of the given field of {@link #clazz} */ public PropertyType getPropertyType(String field) { if(propertyTypes==null) propertyTypes = buildPropertyTypes(clazz); return propertyTypes.get(field); } /** * Obtains the property type of the given field of this descriptor. */ public PropertyType getGlobalPropertyType(String field) { if(globalPropertyTypes==null) globalPropertyTypes = buildPropertyTypes(getClass()); return globalPropertyTypes.get(field); } /** * Given the class, list up its {@link PropertyType}s from its public fields/getters. */ private Map<String, PropertyType> buildPropertyTypes(Class<?> clazz) { Map<String, PropertyType> r = new HashMap<String, PropertyType>(); for (Field f : clazz.getFields()) r.put(f.getName(),new PropertyType(f)); for (Method m : clazz.getMethods()) if(m.getName().startsWith("get")) r.put(Introspector.decapitalize(m.getName().substring(3)),new PropertyType(m)); return r; } /** * Gets the class name nicely escaped to be usable as a key in the structured form submission. */ public final String getJsonSafeClassName() { return getId().replace('.','-'); } /** * @deprecated * Implement {@link #newInstance(StaplerRequest, JSONObject)} method instead. * Deprecated as of 1.145. */ public T newInstance(StaplerRequest req) throws FormException { throw new UnsupportedOperationException(getClass()+" should implement newInstance(StaplerRequest,JSONObject)"); } public T newInstance(StaplerRequest req, JSONObject formData) throws FormException { try { Method m = getClass().getMethod("newInstance", StaplerRequest.class); if(!Modifier.isAbstract(m.getDeclaringClass().getModifiers())) { // this class overrides newInstance(StaplerRequest). // maintain the backward compatible behavior return verifyNewInstance(newInstance(req)); } else { if (req==null) { // yes, req is supposed to be always non-null, but see the note above return verifyNewInstance(clazz.newInstance()); } // new behavior as of 1.206 return verifyNewInstance(req.bindJSON(clazz,formData)); } } catch (NoSuchMethodException e) { throw new AssertionError(e); // impossible } catch (InstantiationException e) { throw new Error("Failed to instantiate "+clazz+" from "+formData,e); } catch (IllegalAccessException e) { throw new Error("Failed to instantiate "+clazz+" from "+formData,e); } catch (RuntimeException e) { throw new RuntimeException("Failed to instantiate "+clazz+" from "+formData,e); } } private T verifyNewInstance(T t) { if (t!=null && t.getDescriptor()!=this) { // TODO: should this be a fatal error? LOGGER.warning("Father of "+ t+" and its getDescriptor() points to two different instances. Probably malplaced @Extension. See http://hudson.361315.n4.nabble.com/Help-Hint-needed-Post-build-action-doesn-t-stay-activated-td2308833.html"); } return t; } /** * Returns the resource path to the help screen HTML, if any. * * <p> * Starting 1.282, this method uses "convention over configuration" &mdash; you should * just put the "help.html" (and its localized versions, if any) in the same directory * you put your Jelly view files, and this method will automatically does the right thing. * * <p> * This value is relative to the context root of Hudson, so normally * the values are something like <tt>"/plugin/emma/help.html"</tt> to * refer to static resource files in a plugin, or <tt>"/publisher/EmmaPublisher/abc"</tt> * to refer to Jelly script <tt>abc.jelly</tt> or a method <tt>EmmaPublisher.doAbc()</tt>. * * @return * null to indicate that there's no help. */ public String getHelpFile() { return getHelpFile(null); } /** * Returns the path to the help screen HTML for the given field. * * <p> * The help files are assumed to be at "help/FIELDNAME.html" with possible * locale variations. */ public String getHelpFile(final String fieldName) { for(Class c=clazz; c!=null; c=c.getSuperclass()) { String page = "/descriptor/" + getId() + "/help"; String suffix; if(fieldName==null) { suffix=""; } else { page += '/'+fieldName; suffix='-'+fieldName; } try { if(Stapler.getCurrentRequest().getView(c,"help"+suffix)!=null) return page; } catch (IOException e) { throw new Error(e); } InputStream in = getHelpStream(c,suffix); IOUtils.closeQuietly(in); if(in!=null) return page; } return null; } /** * Checks if the given object is created from this {@link Descriptor}. */ public final boolean isInstance( T instance ) { return clazz.isInstance(instance); } /** * Checks if the type represented by this descriptor is a subtype of the given type. */ public final boolean isSubTypeOf(Class type) { return type.isAssignableFrom(clazz); } /** * @deprecated * As of 1.239, use {@link #configure(StaplerRequest, JSONObject)}. */ public boolean configure( StaplerRequest req ) throws FormException { return true; } public boolean configure( StaplerRequest req, JSONObject json ) throws FormException { // compatibility return configure(req); } public String getConfigPage() { return getViewPage(clazz, "config.jelly"); } public String getGlobalConfigPage() { return getViewPage(clazz, "global.jelly",null); } private String getViewPage(Class<?> clazz, String pageName, String defaultValue) { while(clazz!=Object.class) { String name = clazz.getName().replace('.', '/').replace('$', '/') + "/" + pageName; if(clazz.getClassLoader().getResource(name)!=null) return '/'+name; clazz = clazz.getSuperclass(); } return defaultValue; } protected final String getViewPage(Class<?> clazz, String pageName) { // We didn't find the configuration page. // Either this is non-fatal, in which case it doesn't matter what string we return so long as // it doesn't exist. // Or this error is fatal, in which case we want the developer to see what page he's missing. // so we put the page name. return getViewPage(clazz,pageName,pageName); } /** * Saves the configuration info to the disk. */ public synchronized void save() { if(BulkChange.contains(this)) return; try { getConfigFile().write(this); SaveableListener.fireOnChange(this, getConfigFile()); } catch (IOException e) { LOGGER.log(Level.WARNING, "Failed to save "+getConfigFile(),e); } } /** * Loads the data from the disk into this object. * * <p> * The constructor of the derived class must call this method. * (If we do that in the base class, the derived class won't * get a chance to set default values.) */ public synchronized void load() { XmlFile file = getConfigFile(); if(!file.exists()) return; try { file.unmarshal(this); } catch (IOException e) { LOGGER.log(Level.WARNING, "Failed to load "+file, e); } } private XmlFile getConfigFile() { return new XmlFile(new File(Hudson.getInstance().getRootDir(),getId()+".xml")); } /** * Serves <tt>help.html</tt> from the resource of {@link #clazz}. */ public void doHelp(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { String path = req.getRestOfPath(); if(path.contains("..")) throw new ServletException("Illegal path: "+path); path = path.replace('/','-'); for (Class c=clazz; c!=null; c=c.getSuperclass()) { RequestDispatcher rd = Stapler.getCurrentRequest().getView(c, "help"+path); if(rd!=null) {// Jelly-generated help page rd.forward(req,rsp); return; } InputStream in = getHelpStream(c,path); if(in!=null) { // TODO: generalize macro expansion and perhaps even support JEXL rsp.setContentType("text/html;charset=UTF-8"); String literal = IOUtils.toString(in,"UTF-8"); rsp.getWriter().println(Util.replaceMacro(literal, Collections.singletonMap("rootURL",req.getContextPath()))); in.close(); return; } } rsp.sendError(SC_NOT_FOUND); } private InputStream getHelpStream(Class c, String suffix) { Locale locale = Stapler.getCurrentRequest().getLocale(); String base = c.getName().replace('.', '/').replace('$','/') + "/help"+suffix; ClassLoader cl = c.getClassLoader(); if(cl==null) return null; InputStream in; in = cl.getResourceAsStream(base + '_' + locale.getLanguage() + '_' + locale.getCountry() + '_' + locale.getVariant() + ".html"); if(in!=null) return in; in = cl.getResourceAsStream(base + '_' + locale.getLanguage() + '_' + locale.getCountry() + ".html"); if(in!=null) return in; in = cl.getResourceAsStream(base + '_' + locale.getLanguage() + ".html"); if(in!=null) return in; // default return cl.getResourceAsStream(base+".html"); } // static methods // to work around warning when creating a generic array type public static <T> T[] toArray( T... values ) { return values; } public static <T> List<T> toList( T... values ) { return new ArrayList<T>(Arrays.asList(values)); } public static <T extends Describable<T>> Map<Descriptor<T>,T> toMap(Iterable<T> describables) { Map<Descriptor<T>,T> m = new LinkedHashMap<Descriptor<T>,T>(); for (T d : describables) { m.put(d.getDescriptor(),d); } return m; } /** * Used to build {@link Describable} instance list from &lt;f:hetero-list> tag. * * @param req * Request that represents the form submission. * @param formData * Structured form data that represents the contains data for the list of describables. * @param key * The JSON property name for 'formData' that represents the data for the list of describables. * @param descriptors * List of descriptors to create instances from. * @return * Can be empty but never null. */ public static <T extends Describable<T>> List<T> newInstancesFromHeteroList(StaplerRequest req, JSONObject formData, String key, Collection<? extends Descriptor<T>> descriptors) throws FormException { List<T> items = new ArrayList<T>(); if(!formData.has(key)) return items; return newInstancesFromHeteroList(req,formData.get(key),descriptors); } public static <T extends Describable<T>> List<T> newInstancesFromHeteroList(StaplerRequest req, Object formData, Collection<? extends Descriptor<T>> descriptors) throws FormException { List<T> items = new ArrayList<T>(); for (Object o : JSONArray.fromObject(formData)) { JSONObject jo = (JSONObject)o; String kind = jo.getString("kind"); items.add(find(descriptors,kind).newInstance(req,jo)); } return items; } /** * Finds a descriptor from a collection by its class name. */ public static <T extends Descriptor> T find(Collection<? extends T> list, String className) { for (T d : list) { if(d.getClass().getName().equals(className)) return d; } return null; } public static Descriptor find(String className) { return find(Hudson.getInstance().getExtensionList(Descriptor.class),className); } public static final class FormException extends Exception implements HttpResponse { private final String formField; public FormException(String message, String formField) { super(message); this.formField = formField; } public FormException(String message, Throwable cause, String formField) { super(message, cause); this.formField = formField; } public FormException(Throwable cause, String formField) { super(cause); this.formField = formField; } /** * Which form field contained an error? */ public String getFormField() { return formField; } public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node) throws IOException, ServletException { // for now, we can't really use the field name that caused the problem. new Failure(getMessage()).generateResponse(req,rsp,node); } } private static final Logger LOGGER = Logger.getLogger(Descriptor.class.getName()); /** * Used in {@link #checkMethods} to indicate that there's no check method. */ private static final String NONE = "\u0000"; private Object readResolve() { if (properties!=null) OldDataMonitor.report(this, "1.62"); return this; } }
package hudson.model; import hudson.DescriptorExtensionList; import hudson.PluginWrapper; import hudson.RelativePath; import hudson.XmlFile; import hudson.BulkChange; import hudson.Util; import hudson.model.listeners.SaveableListener; import hudson.util.FormApply; import hudson.util.ReflectionUtils; import hudson.util.ReflectionUtils.Parameter; import hudson.views.ListViewColumn; import jenkins.model.Jenkins; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.kohsuke.stapler.*; import org.kohsuke.stapler.jelly.JellyCompatibleFacet; import org.kohsuke.stapler.lang.Klass; import org.springframework.util.StringUtils; import org.jvnet.tiger_types.Types; import org.apache.commons.io.IOUtils; import static hudson.Functions.*; import static hudson.util.QuotedStringTokenizer.*; import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND; import javax.servlet.ServletException; import javax.servlet.RequestDispatcher; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.HashMap; import java.util.Locale; import java.util.Arrays; import java.util.Collections; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; import java.util.logging.Logger; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Type; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.beans.Introspector; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; /** * Metadata about a configurable instance. * * <p> * {@link Descriptor} is an object that has metadata about a {@link Describable} * object, and also serves as a factory (in a way this relationship is similar * to {@link Object}/{@link Class} relationship. * * A {@link Descriptor}/{@link Describable} * combination is used throughout in Hudson to implement a * configuration/extensibility mechanism. * * <p> * Take the list view support as an example, which is implemented * in {@link ListView} class. Whenever a new view is created, a new * {@link ListView} instance is created with the configuration * information. This instance gets serialized to XML, and this instance * will be called to render the view page. This is the job * of {@link Describable} &mdash; each instance represents a specific * configuration of a view (what projects are in it, regular expression, etc.) * * <p> * For Hudson to create such configured {@link ListView} instance, Hudson * needs another object that captures the metadata of {@link ListView}, * and that is what a {@link Descriptor} is for. {@link ListView} class * has a singleton descriptor, and this descriptor helps render * the configuration form, remember system-wide configuration, and works as a factory. * * <p> * {@link Descriptor} also usually have its associated views. * * * <h2>Persistence</h2> * <p> * {@link Descriptor} can persist data just by storing them in fields. * However, it is the responsibility of the derived type to properly * invoke {@link #save()} and {@link #load()}. * * <h2>Reflection Enhancement</h2> * {@link Descriptor} defines addition to the standard Java reflection * and provides reflective information about its corresponding {@link Describable}. * These are primarily used by tag libraries to * keep the Jelly scripts concise. * * @author Kohsuke Kawaguchi * @see Describable */ public abstract class Descriptor<T extends Describable<T>> implements Saveable { /** * The class being described by this descriptor. */ public transient final Class<? extends T> clazz; private transient final Map<String,String> checkMethods = new ConcurrentHashMap<String,String>(); /** * Lazily computed list of properties on {@link #clazz} and on the descriptor itself. */ private transient volatile Map<String, PropertyType> propertyTypes,globalPropertyTypes; /** * Represents a readable property on {@link Describable}. */ public static final class PropertyType { public final Class clazz; public final Type type; private volatile Class itemType; public final String displayName; PropertyType(Class clazz, Type type, String displayName) { this.clazz = clazz; this.type = type; this.displayName = displayName; } PropertyType(Field f) { this(f.getType(),f.getGenericType(),f.toString()); } PropertyType(Method getter) { this(getter.getReturnType(),getter.getGenericReturnType(),getter.toString()); } public Enum[] getEnumConstants() { return (Enum[])clazz.getEnumConstants(); } /** * If the property is a collection/array type, what is an item type? */ public Class getItemType() { if(itemType==null) itemType = computeItemType(); return itemType; } private Class computeItemType() { if(clazz.isArray()) { return clazz.getComponentType(); } if(Collection.class.isAssignableFrom(clazz)) { Type col = Types.getBaseClass(type, Collection.class); if (col instanceof ParameterizedType) return Types.erasure(Types.getTypeArgument(col,0)); else return Object.class; } return null; } /** * Returns {@link Descriptor} whose 'clazz' is the same as {@link #getItemType() the item type}. */ public Descriptor getItemTypeDescriptor() { return Jenkins.getInstance().getDescriptor(getItemType()); } public Descriptor getItemTypeDescriptorOrDie() { Class it = getItemType(); if (it == null) { throw new AssertionError(clazz + " is not an array/collection type in " + displayName + ". See https://wiki.jenkins-ci.org/display/JENKINS/My+class+is+missing+descriptor"); } Descriptor d = Jenkins.getInstance().getDescriptor(it); if (d==null) throw new AssertionError(it +" is missing its descriptor in "+displayName+". See https://wiki.jenkins-ci.org/display/JENKINS/My+class+is+missing+descriptor"); return d; } /** * Returns all the descriptors that produce types assignable to the property type. */ public List<? extends Descriptor> getApplicableDescriptors() { return Jenkins.getInstance().getDescriptorList(clazz); } /** * Returns all the descriptors that produce types assignable to the item type for a collection property. */ public List<? extends Descriptor> getApplicableItemDescriptors() { return Jenkins.getInstance().getDescriptorList(getItemType()); } } /** * Help file redirect, keyed by the field name to the path. * * @see #getHelpFile(String) */ private transient final Map<String,String> helpRedirect = new HashMap<String, String>(); /** * * @param clazz * Pass in {@link #self()} to have the descriptor describe itself, * (this hack is needed since derived types can't call "getClass()" to refer to itself. */ protected Descriptor(Class<? extends T> clazz) { if (clazz==self()) clazz = (Class)getClass(); this.clazz = clazz; // doing this turns out to be very error prone, // as field initializers in derived types will override values. // load(); } /** * Infers the type of the corresponding {@link Describable} from the outer class. * This version works when you follow the common convention, where a descriptor * is written as the static nested class of the describable class. * * @since 1.278 */ protected Descriptor() { this.clazz = (Class<T>)getClass().getEnclosingClass(); if(clazz==null) throw new AssertionError(getClass()+" doesn't have an outer class. Use the constructor that takes the Class object explicitly."); // detect an type error Type bt = Types.getBaseClass(getClass(), Descriptor.class); if (bt instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) bt; // this 't' is the closest approximation of T of Descriptor<T>. Class t = Types.erasure(pt.getActualTypeArguments()[0]); if(!t.isAssignableFrom(clazz)) throw new AssertionError("Outer class "+clazz+" of "+getClass()+" is not assignable to "+t+". Perhaps wrong outer class?"); } // detect a type error. this Descriptor is supposed to be returned from getDescriptor(), so make sure its type match up. try { Method getd = clazz.getMethod("getDescriptor"); if(!getd.getReturnType().isAssignableFrom(getClass())) { throw new AssertionError(getClass()+" must be assignable to "+getd.getReturnType()); } } catch (NoSuchMethodException e) { throw new AssertionError(getClass()+" is missing getDescriptor method."); } } /** * Human readable name of this kind of configurable object. */ public abstract String getDisplayName(); /** * Uniquely identifies this {@link Descriptor} among all the other {@link Descriptor}s. * * <p> * Historically {@link #clazz} is assumed to be unique, so this method uses that as the default, * but if you are adding {@link Descriptor}s programmatically for the same type, you can change * this to disambiguate them. * * <p> * To look up {@link Descriptor} from ID, use {@link Jenkins#getDescriptor(String)}. * * @return * Stick to valid Java identifier character, plus '.', which had to be allowed for historical reasons. * * @since 1.391 */ public String getId() { return clazz.getName(); } /** * Unlike {@link #clazz}, return the parameter type 'T', which determines * the {@link DescriptorExtensionList} that this goes to. * * <p> * In those situations where subtypes cannot provide the type parameter, * this method can be overridden to provide it. */ public Class<T> getT() { Type subTyping = Types.getBaseClass(getClass(), Descriptor.class); if (!(subTyping instanceof ParameterizedType)) { throw new IllegalStateException(getClass()+" doesn't extend Descriptor with a type parameter."); } return Types.erasure(Types.getTypeArgument(subTyping, 0)); } /** * Gets the URL that this Descriptor is bound to, relative to the nearest {@link DescriptorByNameOwner}. * Since {@link Jenkins} is a {@link DescriptorByNameOwner}, there's always one such ancestor to any request. */ public String getDescriptorUrl() { return "descriptorByName/"+getId(); } /** * Gets the URL that this Descriptor is bound to, relative to the context path. * @since 1.406 */ public final String getDescriptorFullUrl() { return getCurrentDescriptorByNameUrl()+'/'+getDescriptorUrl(); } /** * @since 1.402 */ public static String getCurrentDescriptorByNameUrl() { StaplerRequest req = Stapler.getCurrentRequest(); // this override allows RenderOnDemandClosure to preserve the proper value Object url = req.getAttribute("currentDescriptorByNameUrl"); if (url!=null) return url.toString(); Ancestor a = req.findAncestor(DescriptorByNameOwner.class); return a.getUrl(); } /** * If the field "xyz" of a {@link Describable} has the corresponding "doCheckXyz" method, * return the form-field validation string. Otherwise null. * <p> * This method is used to hook up the form validation method to the corresponding HTML input element. */ public String getCheckUrl(String fieldName) { String method = checkMethods.get(fieldName); if(method==null) { method = calcCheckUrl(fieldName); checkMethods.put(fieldName,method); } if (method.equals(NONE)) // == would do, but it makes IDE flag a warning return null; // put this under the right contextual umbrella. // a is always non-null because we already have Hudson as the sentinel return '\'' + jsStringEscape(getCurrentDescriptorByNameUrl()) + "/'+" + method; } private String calcCheckUrl(String fieldName) { String capitalizedFieldName = StringUtils.capitalize(fieldName); Method method = ReflectionUtils.getPublicMethodNamed(getClass(),"doCheck"+ capitalizedFieldName); if(method==null) return NONE; return '\'' + getDescriptorUrl() + "/check" + capitalizedFieldName + '\'' + buildParameterList(method, new StringBuilder()).append(".toString()"); } /** * Builds query parameter line by figuring out what should be submitted */ private StringBuilder buildParameterList(Method method, StringBuilder query) { for (Parameter p : ReflectionUtils.getParameters(method)) { QueryParameter qp = p.annotation(QueryParameter.class); if (qp!=null) { String name = qp.value(); if (name.length()==0) name = p.name(); if (name==null || name.length()==0) continue; // unknown parameter name. we'll report the error when the form is submitted. RelativePath rp = p.annotation(RelativePath.class); if (rp!=null) name = rp.value()+'/'+name; if (query.length()==0) query.append("+qs(this)"); if (name.equals("value")) { // The special 'value' parameter binds to the the current field query.append(".addThis()"); } else { query.append(".nearBy('"+name+"')"); } continue; } Method m = ReflectionUtils.getPublicMethodNamed(p.type(), "fromStapler"); if (m!=null) buildParameterList(m,query); } return query; } /** * Computes the list of other form fields that the given field depends on, via the doFillXyzItems method, * and sets that as the 'fillDependsOn' attribute. Also computes the URL of the doFillXyzItems and * sets that as the 'fillUrl' attribute. */ public void calcFillSettings(String field, Map<String,Object> attributes) { String capitalizedFieldName = StringUtils.capitalize(field); String methodName = "doFill" + capitalizedFieldName + "Items"; Method method = ReflectionUtils.getPublicMethodNamed(getClass(), methodName); if(method==null) throw new IllegalStateException(String.format("%s doesn't have the %s method for filling a drop-down list", getClass(), methodName)); // build query parameter line by figuring out what should be submitted List<String> depends = buildFillDependencies(method, new ArrayList<String>()); if (!depends.isEmpty()) attributes.put("fillDependsOn",Util.join(depends," ")); attributes.put("fillUrl", String.format("%s/%s/fill%sItems", getCurrentDescriptorByNameUrl(), getDescriptorUrl(), capitalizedFieldName)); } private List<String> buildFillDependencies(Method method, List<String> depends) { for (Parameter p : ReflectionUtils.getParameters(method)) { QueryParameter qp = p.annotation(QueryParameter.class); if (qp!=null) { String name = qp.value(); if (name.length()==0) name = p.name(); if (name==null || name.length()==0) continue; // unknown parameter name. we'll report the error when the form is submitted. RelativePath rp = p.annotation(RelativePath.class); if (rp!=null) name = rp.value()+'/'+name; depends.add(name); continue; } Method m = ReflectionUtils.getPublicMethodNamed(p.type(), "fromStapler"); if (m!=null) buildFillDependencies(m,depends); } return depends; } /** * Computes the auto-completion setting */ public void calcAutoCompleteSettings(String field, Map<String,Object> attributes) { String capitalizedFieldName = StringUtils.capitalize(field); String methodName = "doAutoComplete" + capitalizedFieldName; Method method = ReflectionUtils.getPublicMethodNamed(getClass(), methodName); if(method==null) return; // no auto-completion attributes.put("autoCompleteUrl", String.format("%s/%s/autoComplete%s", getCurrentDescriptorByNameUrl(), getDescriptorUrl(), capitalizedFieldName)); } /** * Used by Jelly to abstract away the handlign of global.jelly vs config.jelly databinding difference. */ public @CheckForNull PropertyType getPropertyType(@Nonnull Object instance, @Nonnull String field) { // in global.jelly, instance==descriptor return instance==this ? getGlobalPropertyType(field) : getPropertyType(field); } /** * Akin to {@link #getPropertyType(Object,String) but never returns null. * @throws AssertionError in case the field cannot be found * @since 1.492 */ public @Nonnull PropertyType getPropertyTypeOrDie(@Nonnull Object instance, @Nonnull String field) { PropertyType propertyType = getPropertyType(instance, field); if (propertyType != null) { return propertyType; } else if (instance == this) { throw new AssertionError(getClass().getName() + " has no property " + field); } else { throw new AssertionError(clazz.getName() + " has no property " + field); } } /** * Obtains the property type of the given field of {@link #clazz} */ public PropertyType getPropertyType(String field) { if(propertyTypes==null) propertyTypes = buildPropertyTypes(clazz); return propertyTypes.get(field); } /** * Obtains the property type of the given field of this descriptor. */ public PropertyType getGlobalPropertyType(String field) { if(globalPropertyTypes==null) globalPropertyTypes = buildPropertyTypes(getClass()); return globalPropertyTypes.get(field); } /** * Given the class, list up its {@link PropertyType}s from its public fields/getters. */ private Map<String, PropertyType> buildPropertyTypes(Class<?> clazz) { Map<String, PropertyType> r = new HashMap<String, PropertyType>(); for (Field f : clazz.getFields()) r.put(f.getName(),new PropertyType(f)); for (Method m : clazz.getMethods()) if(m.getName().startsWith("get")) r.put(Introspector.decapitalize(m.getName().substring(3)),new PropertyType(m)); return r; } /** * Gets the class name nicely escaped to be usable as a key in the structured form submission. */ public final String getJsonSafeClassName() { return getId().replace('.','-'); } /** * @deprecated * Implement {@link #newInstance(StaplerRequest, JSONObject)} method instead. * Deprecated as of 1.145. */ public T newInstance(StaplerRequest req) throws FormException { throw new UnsupportedOperationException(getClass()+" should implement newInstance(StaplerRequest,JSONObject)"); } public T newInstance(StaplerRequest req, JSONObject formData) throws FormException { try { Method m = getClass().getMethod("newInstance", StaplerRequest.class); if(!Modifier.isAbstract(m.getDeclaringClass().getModifiers())) { // this class overrides newInstance(StaplerRequest). // maintain the backward compatible behavior return verifyNewInstance(newInstance(req)); } else { if (req==null) { // yes, req is supposed to be always non-null, but see the note above return verifyNewInstance(clazz.newInstance()); } // new behavior as of 1.206 return verifyNewInstance(req.bindJSON(clazz,formData)); } } catch (NoSuchMethodException e) { throw new AssertionError(e); // impossible } catch (InstantiationException e) { throw new Error("Failed to instantiate "+clazz+" from "+formData,e); } catch (IllegalAccessException e) { throw new Error("Failed to instantiate "+clazz+" from "+formData,e); } catch (RuntimeException e) { throw new RuntimeException("Failed to instantiate "+clazz+" from "+formData,e); } } private T verifyNewInstance(T t) { if (t!=null && t.getDescriptor()!=this) { // TODO: should this be a fatal error? LOGGER.warning("Father of "+ t+" and its getDescriptor() points to two different instances. Probably malplaced @Extension. See http://hudson.361315.n4.nabble.com/Help-Hint-needed-Post-build-action-doesn-t-stay-activated-td2308833.html"); } return t; } /** * Returns the {@link Klass} object used for the purpose of loading resources from this descriptor. * * This hook enables other JVM languages to provide more integrated lookup. */ public Klass<?> getKlass() { return Klass.java(clazz); } /** * Returns the resource path to the help screen HTML, if any. * * <p> * Starting 1.282, this method uses "convention over configuration" &mdash; you should * just put the "help.html" (and its localized versions, if any) in the same directory * you put your Jelly view files, and this method will automatically does the right thing. * * <p> * This value is relative to the context root of Hudson, so normally * the values are something like <tt>"/plugin/emma/help.html"</tt> to * refer to static resource files in a plugin, or <tt>"/publisher/EmmaPublisher/abc"</tt> * to refer to Jelly script <tt>abc.jelly</tt> or a method <tt>EmmaPublisher.doAbc()</tt>. * * @return * null to indicate that there's no help. */ public String getHelpFile() { return getHelpFile(null); } /** * Returns the path to the help screen HTML for the given field. * * <p> * The help files are assumed to be at "help/FIELDNAME.html" with possible * locale variations. */ public String getHelpFile(final String fieldName) { return getHelpFile(getKlass(),fieldName); } public String getHelpFile(Klass<?> clazz, String fieldName) { String v = helpRedirect.get(fieldName); if (v!=null) return v; for (Klass<?> c : clazz.getAncestors()) { String page = "/descriptor/" + getId() + "/help"; String suffix; if(fieldName==null) { suffix=""; } else { page += '/'+fieldName; suffix='-'+fieldName; } try { if(Stapler.getCurrentRequest().getView(c,"help"+suffix)!=null) return page; } catch (IOException e) { throw new Error(e); } if(getStaticHelpUrl(c, suffix) !=null) return page; } return null; } /** * Tells Jenkins that the help file for the field 'fieldName' is defined in the help file for * the 'fieldNameToRedirectTo' in the 'owner' class. * @since 1.425 */ protected void addHelpFileRedirect(String fieldName, Class<? extends Describable> owner, String fieldNameToRedirectTo) { helpRedirect.put(fieldName, Jenkins.getInstance().getDescriptor(owner).getHelpFile(fieldNameToRedirectTo)); } /** * Checks if the given object is created from this {@link Descriptor}. */ public final boolean isInstance( T instance ) { return clazz.isInstance(instance); } /** * Checks if the type represented by this descriptor is a subtype of the given type. */ public final boolean isSubTypeOf(Class type) { return type.isAssignableFrom(clazz); } /** * @deprecated * As of 1.239, use {@link #configure(StaplerRequest, JSONObject)}. */ public boolean configure( StaplerRequest req ) throws FormException { return true; } public boolean configure( StaplerRequest req, JSONObject json ) throws FormException { // compatibility return configure(req); } public String getConfigPage() { return getViewPage(clazz, getPossibleViewNames("config"), "config.jelly"); } public String getGlobalConfigPage() { return getViewPage(clazz, getPossibleViewNames("global"), null); } private String getViewPage(Class<?> clazz, String pageName, String defaultValue) { return getViewPage(clazz,Collections.singleton(pageName),defaultValue); } private String getViewPage(Class<?> clazz, Collection<String> pageNames, String defaultValue) { while(clazz!=Object.class && clazz!=null) { for (String pageName : pageNames) { String name = clazz.getName().replace('.', '/').replace('$', '/') + "/" + pageName; if(clazz.getClassLoader().getResource(name)!=null) return '/'+name; } clazz = clazz.getSuperclass(); } return defaultValue; } protected final String getViewPage(Class<?> clazz, String pageName) { // We didn't find the configuration page. // Either this is non-fatal, in which case it doesn't matter what string we return so long as // it doesn't exist. // Or this error is fatal, in which case we want the developer to see what page he's missing. // so we put the page name. return getViewPage(clazz,pageName,pageName); } protected List<String> getPossibleViewNames(String baseName) { List<String> names = new ArrayList<String>(); for (Facet f : WebApp.get(Jenkins.getInstance().servletContext).facets) { if (f instanceof JellyCompatibleFacet) { JellyCompatibleFacet jcf = (JellyCompatibleFacet) f; for (String ext : jcf.getScriptExtensions()) names.add(baseName +ext); } } return names; } /** * Saves the configuration info to the disk. */ public synchronized void save() { if(BulkChange.contains(this)) return; try { getConfigFile().write(this); SaveableListener.fireOnChange(this, getConfigFile()); } catch (IOException e) { LOGGER.log(Level.WARNING, "Failed to save "+getConfigFile(),e); } } /** * Loads the data from the disk into this object. * * <p> * The constructor of the derived class must call this method. * (If we do that in the base class, the derived class won't * get a chance to set default values.) */ public synchronized void load() { XmlFile file = getConfigFile(); if(!file.exists()) return; try { file.unmarshal(this); } catch (IOException e) { LOGGER.log(Level.WARNING, "Failed to load "+file, e); } } protected final XmlFile getConfigFile() { return new XmlFile(new File(Jenkins.getInstance().getRootDir(),getId()+".xml")); } /** * Returns the plugin in which this descriptor is defined. * * @return * null to indicate that this descriptor came from the core. */ protected PluginWrapper getPlugin() { return Jenkins.getInstance().getPluginManager().whichPlugin(clazz); } /** * Serves <tt>help.html</tt> from the resource of {@link #clazz}. */ public void doHelp(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { String path = req.getRestOfPath(); if(path.contains("..")) throw new ServletException("Illegal path: "+path); path = path.replace('/','-'); PluginWrapper pw = getPlugin(); if (pw!=null) { rsp.setHeader("X-Plugin-Short-Name",pw.getShortName()); rsp.setHeader("X-Plugin-Long-Name",pw.getLongName()); rsp.setHeader("X-Plugin-From", Messages.Descriptor_From( pw.getLongName().replace("Hudson","Jenkins").replace("hudson","jenkins"), pw.getUrl())); } for (Klass<?> c= getKlass(); c!=null; c=c.getSuperClass()) { RequestDispatcher rd = Stapler.getCurrentRequest().getView(c, "help"+path); if(rd!=null) {// template based help page rd.forward(req,rsp); return; } URL url = getStaticHelpUrl(c, path); if(url!=null) { // TODO: generalize macro expansion and perhaps even support JEXL rsp.setContentType("text/html;charset=UTF-8"); InputStream in = url.openStream(); try { String literal = IOUtils.toString(in,"UTF-8"); rsp.getWriter().println(Util.replaceMacro(literal, Collections.singletonMap("rootURL",req.getContextPath()))); } finally { IOUtils.closeQuietly(in); } return; } } rsp.sendError(SC_NOT_FOUND); } private URL getStaticHelpUrl(Klass<?> c, String suffix) { Locale locale = Stapler.getCurrentRequest().getLocale(); String base = "help"+suffix; URL url; url = c.getResource(base + '_' + locale.getLanguage() + '_' + locale.getCountry() + '_' + locale.getVariant() + ".html"); if(url!=null) return url; url = c.getResource(base + '_' + locale.getLanguage() + '_' + locale.getCountry() + ".html"); if(url!=null) return url; url = c.getResource(base + '_' + locale.getLanguage() + ".html"); if(url!=null) return url; // default return c.getResource(base + ".html"); } // static methods // to work around warning when creating a generic array type public static <T> T[] toArray( T... values ) { return values; } public static <T> List<T> toList( T... values ) { return new ArrayList<T>(Arrays.asList(values)); } public static <T extends Describable<T>> Map<Descriptor<T>,T> toMap(Iterable<T> describables) { Map<Descriptor<T>,T> m = new LinkedHashMap<Descriptor<T>,T>(); for (T d : describables) { m.put(d.getDescriptor(),d); } return m; } /** * Used to build {@link Describable} instance list from &lt;f:hetero-list> tag. * * @param req * Request that represents the form submission. * @param formData * Structured form data that represents the contains data for the list of describables. * @param key * The JSON property name for 'formData' that represents the data for the list of describables. * @param descriptors * List of descriptors to create instances from. * @return * Can be empty but never null. */ public static <T extends Describable<T>> List<T> newInstancesFromHeteroList(StaplerRequest req, JSONObject formData, String key, Collection<? extends Descriptor<T>> descriptors) throws FormException { return newInstancesFromHeteroList(req,formData.get(key),descriptors); } public static <T extends Describable<T>> List<T> newInstancesFromHeteroList(StaplerRequest req, Object formData, Collection<? extends Descriptor<T>> descriptors) throws FormException { List<T> items = new ArrayList<T>(); if (formData!=null) { for (Object o : JSONArray.fromObject(formData)) { JSONObject jo = (JSONObject)o; String kind = jo.getString("kind"); items.add(find(descriptors,kind).newInstance(req,jo)); } } return items; } /** * Finds a descriptor from a collection by its class name. */ public static <T extends Descriptor> T find(Collection<? extends T> list, String className) { for (T d : list) { if(d.getClass().getName().equals(className)) return d; } // Since we introduced Descriptor.getId(), it is a preferred method of identifying descriptor by a string. // To make that migration easier without breaking compatibility, let's also match up with the id. for (T d : list) { if(d.getId().equals(className)) return d; } return null; } public static Descriptor find(String className) { return find(Jenkins.getInstance().getExtensionList(Descriptor.class),className); } public static final class FormException extends Exception implements HttpResponse { private final String formField; public FormException(String message, String formField) { super(message); this.formField = formField; } public FormException(String message, Throwable cause, String formField) { super(message, cause); this.formField = formField; } public FormException(Throwable cause, String formField) { super(cause); this.formField = formField; } /** * Which form field contained an error? */ public String getFormField() { return formField; } public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node) throws IOException, ServletException { if (FormApply.isApply(req)) { FormApply.applyResponse("notificationBar.show(" + quote(getMessage())+ ",notificationBar.defaultOptions.ERROR)") .generateResponse(req, rsp, node); } else { // for now, we can't really use the field name that caused the problem. new Failure(getMessage()).generateResponse(req,rsp,node); } } } private static final Logger LOGGER = Logger.getLogger(Descriptor.class.getName()); /** * Used in {@link #checkMethods} to indicate that there's no check method. */ private static final String NONE = "\u0000"; /** * Special type indicating that {@link Descriptor} describes itself. * @see Descriptor#Descriptor(Class) */ public static final class Self {} protected static Class self() { return Self.class; } }
import org.json.JSONObject; import java.util.HashMap; public class Pages { private ApiConnection apiConnection; private ApiQuery apiQuery; /** * Used to create a new page * @param queryMap * @return */ public JSONObject createPage(HashMap<String, Object> queryMap) { this.apiConnection = new ApiConnection(Definitions.PAYSTACK_PAGES_CREATE_PAGE); return this.apiConnection.connectAndQuery(queryMap); } /** * Used to create a new page * @param query * @return */ public JSONObject createPage(ApiQuery query) { this.apiConnection = new ApiConnection(Definitions.PAYSTACK_PAGES_CREATE_PAGE); return this.apiConnection.connectAndQuery(query); } /** * Used to create a new page * @param name * @param description * @param amount * @return */ public JSONObject createPage(String name, String description, String amount) { this.apiConnection = new ApiConnection(Definitions.PAYSTACK_PAGES_CREATE_PAGE); this.apiQuery = new ApiQuery(); this.apiQuery.putParams("name", name); this.apiQuery.putParams("description", description); this.apiQuery.putParams("amount", amount); return this.apiConnection.connectAndQuery(this.apiQuery); } /** * Used to list created pages * @param queryMap * @return */ public JSONObject listPages(HashMap<String, Object> queryMap) { this.apiConnection = new ApiConnection(Definitions.PAYSTACK_PAGES_LIST_PAGES); return this.apiConnection.connectAndQueryWithGet(queryMap); } /** * Used to list created pages * @param query * @return */ public JSONObject listPages(ApiQuery query) { this.apiConnection = new ApiConnection(Definitions.PAYSTACK_PAGES_LIST_PAGES); return this.apiConnection.connectAndQueryWithGet(query); } /** * Used to list created pages * @param perPage * @param page * @return */ public JSONObject listPages(int perPage, int page) { this.apiConnection = new ApiConnection(Definitions.PAYSTACK_PAGES_LIST_PAGES); this.apiQuery = new ApiQuery(); this.apiQuery.putParams("perPage", perPage); this.apiQuery.putParams("page", page); return this.apiConnection.connectAndQueryWithGet(this.apiQuery); } /** * Used to fetch a page * @param idOrSlug * @return */ public JSONObject fetchPage(String idOrSlug) { this.apiConnection = new ApiConnection(Definitions.PAYSTACK_PAGES_FETCH_PAGE + idOrSlug); return this.apiConnection.connectAndQueryWithGet(); } /** * Used to update a page * @param idOrSlug * @param queryMap * @return */ public JSONObject updatePage(String idOrSlug, HashMap<String, Object> queryMap) { this.apiConnection = new ApiConnection(Definitions.PAYSTACK_PAGES_UPDATE_PAGE + idOrSlug); return this.apiConnection.connectAndQueryWithPut(queryMap); } /** * Used to update a page * @param idOrSlug * @param query * @return */ public JSONObject updatePage(String idOrSlug, ApiQuery query) { this.apiConnection = new ApiConnection(Definitions.PAYSTACK_PAGES_UPDATE_PAGE + idOrSlug); return this.apiConnection.connectAndQueryWithPut(query); } /** * Used to update a page * @param idOrSlug * @param name * @param description * @param amount * @param active * @return */ public JSONObject updatePage(String idOrSlug, String name, String description, String amount, boolean active) { this.apiConnection = new ApiConnection(Definitions.PAYSTACK_PAGES_UPDATE_PAGE + idOrSlug); this.apiQuery = new ApiQuery(); this.apiQuery.putParams("name", name); this.apiQuery.putParams("description", description); this.apiQuery.putParams("amount", amount); this.apiQuery.putParams("active", active); return this.apiConnection.connectAndQueryWithPut(this.apiQuery); } }
package sx.lambda.voxel.world.chunk; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.Mesh; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.attributes.BlendingAttribute; import com.badlogic.gdx.graphics.g3d.attributes.TextureAttribute; import com.badlogic.gdx.graphics.g3d.utils.MeshBuilder; import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder; import sx.lambda.voxel.VoxelGameClient; import sx.lambda.voxel.api.VoxelGameAPI; import sx.lambda.voxel.api.events.render.EventChunkRender; import sx.lambda.voxel.block.Block; import sx.lambda.voxel.block.NormalBlockRenderer; import sx.lambda.voxel.client.render.meshing.GreedyMesher; import sx.lambda.voxel.util.Vec3i; import sx.lambda.voxel.world.IWorld; import java.util.List; public class Chunk implements IChunk { private final transient GreedyMesher mesher; private final int size; private final int height; /** * Map of light levels (ints 0-16) to brightness multipliers */ private final float[] lightLevelMap = new float[17]; private int[][][] blockList; private transient IWorld parentWorld; private transient MeshBuilder meshBuilder; private transient ModelBuilder modelBuilder; private transient Model opaqueModel, translucentModel; private transient ModelInstance opaqueModelInstance, translucentModelInstance; private final Vec3i startPosition; private int highestPoint; private final transient float[][][] lightLevels; private transient int[][][] sunlightLevels; private transient boolean sunlightChanging; private transient boolean sunlightChanged; private boolean setup; private boolean cleanedUp; private List<GreedyMesher.Face> translucentFaces; private List<GreedyMesher.Face> opaqueFaces; private boolean meshing, meshed, meshWhenDone; public Chunk(IWorld world, Vec3i startPosition, int[][][] ids) { this.parentWorld = world; this.startPosition = startPosition; this.size = world.getChunkSize(); this.height = world.getHeight(); for (int i = 0; i < 17; i++) { int reduction = 16 - i; lightLevelMap[i] = (float) Math.pow(0.8, reduction); } sunlightLevels = new int[size][height][size]; if (VoxelGameClient.getInstance() != null) {// We're a client mesher = new GreedyMesher(this); } else { mesher = null; } this.loadIdInts(ids); lightLevels = new float[size][height][size]; setupSunlighting(); } public Chunk(IWorld world, Vec3i startPosition) { this.parentWorld = world; this.startPosition = startPosition; this.size = world.getChunkSize(); this.height = world.getHeight(); for (int i = 0; i < 17; i++) { int reduction = 16 - i; lightLevelMap[i] = (float) Math.pow(0.8, reduction); } sunlightLevels = new int[size][height][size]; if (VoxelGameClient.getInstance() != null) {// We're a client mesher = new GreedyMesher(this); } else { mesher = null; } this.blockList = new int[size][height][size]; highestPoint = world.getChunkGen().generate(startPosition, blockList); lightLevels = new float[size][height][size]; setupSunlighting(); } @Override public void rerender() { if (cleanedUp) return; if(sunlightChanging)return; if (this.parentWorld == null) { if (VoxelGameClient.getInstance() != null) {// We're a client this.parentWorld = VoxelGameClient.getInstance().getWorld(); } } if (!setup) { meshBuilder = new MeshBuilder(); modelBuilder = new ModelBuilder(); setup = true; } sunlightChanged = false; if(meshing || parentWorld.getNumChunksMeshing() >= 2) { meshWhenDone = true; } else { meshing = true; new Thread("Chunk Meshing") { @Override public void run() { updateFaces(); } }.start(); } } @Override public void render(ModelBatch batch) { if (cleanedUp) return; if(!meshing && meshed) { updateModelInstances(); meshed = false; } if (sunlightChanged && !sunlightChanging || (!meshing && !meshed && meshWhenDone)) { meshWhenDone = false; rerender(); } if(opaqueModelInstance != null) { batch.render(opaqueModelInstance); batch.render(translucentModelInstance); } } @Override public void renderTranslucent(ModelBatch batch) { } @Override public void eachBlock(EachBlockCallee callee) { for (int x = 0; x < size; x++) { for (int y = 0; y < height; y++) { for (int z = 0; z < size; z++) { Block blk = VoxelGameAPI.instance.getBlockByID(blockList[x][y][z]); callee.call(blk, x, y, z); } } } } public Block getBlockAtPosition(Vec3i position) { int x = position.x % size; int y = position.y; int z = position.z % size; if (x < 0) { x += size; } if (z < 0) { z += size; } if (y > height - 1) return null; if (y < 0) return null; return VoxelGameAPI.instance.getBlockByID(blockList[x][y][z]); } @Override public void removeBlock(int x, int y, int z) { x = x % size; z = z % size; if (x < 0) { x += size; } if (z < 0) { z += size; } if (y > height - 1) return; blockList[x][y][z] = -1; getWorld().rerenderChunk(this); this.addNeighborsToSunlightQueue(x, y, z); } private void addNeighborsToSunlightQueue(int x, int y, int z) {// X Y and Z are relative coords, not world coords x += startPosition.x; z += startPosition.z; int negX = x-1; int posX = x+1; int negZ = z-1; int posZ = z+1; int posY = y+1; IChunk negXNeighborChunk = parentWorld.getChunkAtPosition(negX, z); IChunk posXNeighborChunk = parentWorld.getChunkAtPosition(posX, z); IChunk negZNeighborChunk = parentWorld.getChunkAtPosition(x, negZ); IChunk posZNeighborChunk = parentWorld.getChunkAtPosition(x, posZ); if (negXNeighborChunk != null) { int negXSunlight = negXNeighborChunk.getSunlight(negX, y, z); if (negXSunlight > 1) { Block bl = negXNeighborChunk.getBlockAtPosition(negX, y, z); if (bl == null) { parentWorld.addToSunlightQueue(new int[]{negX, y, z}); } else if (bl.isTranslucent()) { parentWorld.addToSunlightQueue(new int[]{negX, y, z}); } } } if (posXNeighborChunk != null) { int posXSunlight = posXNeighborChunk.getSunlight(posX, y, z); if (posXSunlight > 1) { Block bl = posXNeighborChunk.getBlockAtPosition(posX, y, z); if (bl == null) { parentWorld.addToSunlightQueue(new int[]{posX, y, z}); } else if (bl.isTranslucent()) { parentWorld.addToSunlightQueue(new int[]{posX, y, z}); } } } if (negZNeighborChunk != null) { int negZSunlight = negZNeighborChunk.getSunlight(x, y, negZ); if (negZSunlight > 1) { Block bl = negZNeighborChunk.getBlockAtPosition(x, y, negZ); if (bl == null) { parentWorld.addToSunlightQueue(new int[]{x, y, negZ}); } else if (bl.isTranslucent()) { parentWorld.addToSunlightQueue(new int[]{x, y, negZ}); } } } if (posZNeighborChunk != null) { int posZSunlight = posZNeighborChunk.getSunlight(x, y, posZ); if (posZSunlight > 1) { Block bl = posZNeighborChunk.getBlockAtPosition(x, y, posZ); if (bl == null) { parentWorld.addToSunlightQueue(new int[]{x, y, posZ}); } else if (bl.isTranslucent()) { parentWorld.addToSunlightQueue(new int[]{x, y, posZ}); } } } if (y < height - 1) { Block posYBlock = VoxelGameAPI.instance.getBlockByID(blockList[x - startPosition.x][posY][z - startPosition.z]); if (getSunlight(x, y + 1, z) > 1) { if (posYBlock == null) { parentWorld.addToSunlightQueue(new int[]{x, posY, z}); } else if (posYBlock.isTranslucent()) { parentWorld.addToSunlightQueue(new int[]{x, posY, z}); } } } } @Override public void addBlock(int block, int x, int y, int z) { addBlock(block, x, y, z, true); } @Override public void addBlock(int block, int x, int y, int z, boolean updateSunlight) { x = x % size; z = z % size; if (x < 0) { x += size; } if (z < 0) { z += size; } if (y > height - 1) return; blockList[x][y][z] = block; if (block > 0) { highestPoint = Math.max(highestPoint, y); } if(updateSunlight) getWorld().addToSunlightRemovalQueue(new int[]{x + startPosition.x, y + startPosition.y, z + startPosition.z}); } @Override public Vec3i getStartPosition() { return this.startPosition; } @Override public float getHighestPoint() { return highestPoint; } @Override public float getLightLevel(int x, int y, int z) { x %= size; z %= size; if (x < 0) { x += size; } if (z < 0) { z += size; } if (y > height - 1 || y < 0) { return 1; } return lightLevels[x][y][z]; } @Override public int[][][] blocksToIdInt() { return blockList; } private void loadIdInts(int[][][] ints) { blockList = ints; highestPoint = 0; for (int x = 0; x < ints.length; x++) { for (int z = 0; z < ints[0][0].length; z++) { for (int y = 0; y < ints[0].length; y++) { if(ints[x][y][z] > 0) highestPoint = Math.max(y, highestPoint); } } } } private void setupSunlighting() { sunlightLevels = new int[size][height][size]; for (int x = 0; x < size; x++) { for (int z = 0; z < size; z++) { sunlightLevels[x][height - 1][z] = 16; parentWorld.addToSunlightQueue(new int[]{startPosition.x + x, height - 1, startPosition.z + z}); } } } @Override public void setSunlight(int x, int y, int z, int level) { setSunlight(x, y, z, level, true); } @Override public void setSunlight(int x, int y, int z, int level, boolean updateNeighbors) { x %= size; z %= size; if (x < 0) { x += size; } if (z < 0) { z += size; } sunlightLevels[x][y][z] = level; lightLevels[x][y][z] = lightLevelMap[level]; sunlightChanging = true; sunlightChanged = true; if(updateNeighbors) { if (x == 0) { IChunk xMinNeighbor = getWorld().getChunkAtPosition(startPosition.x - 1, startPosition.z); if (xMinNeighbor != null) { getWorld().rerenderChunk(xMinNeighbor); } } if (x == size - 1) { IChunk xPlNeighbor = getWorld().getChunkAtPosition(startPosition.x + 1, startPosition.z); if (xPlNeighbor != null) { getWorld().rerenderChunk(xPlNeighbor); } } if (z == 0) { IChunk zMinNeighbor = getWorld().getChunkAtPosition(startPosition.x, startPosition.z - 1); if (zMinNeighbor != null) { getWorld().rerenderChunk(zMinNeighbor); } } if (z == size - 1) { IChunk zPlNeighbor = getWorld().getChunkAtPosition(startPosition.x, startPosition.z + 1); if (zPlNeighbor != null) { getWorld().rerenderChunk(zPlNeighbor); } } } } @Override public int getSunlight(int x, int y, int z) { x %= size; z %= size; if (x < 0) { x += size; } if (z < 0) { z += size; } if (y > height - 1 || y < 0) { return -1; } return (sunlightLevels[x][y][z]); } @Override public void finishChangingSunlight() { sunlightChanging = false; } @Override public IWorld getWorld() { return this.parentWorld; } @Override public void cleanup() { if(opaqueModel != null) opaqueModel.dispose(); if(translucentModel != null) translucentModel.dispose(); cleanedUp = true; } public int getBlockIdAtPosition(int x, int y, int z) { x = x % size; z = z % size; if (x < 0) { x += size; } if (z < 0) { z += size; } if (y > height - 1) return 0; if (y < 0) return 0; return blockList[x][y][z]; } @Override public Block getBlockAtPosition(int x, int y, int z) { x = x % size; z = z % size; if (x < 0) { x += size; } if (z < 0) { z += size; } if (y > height - 1) return null; if (y < 0) return null; return VoxelGameAPI.instance.getBlockByID(blockList[x][y][z]); } private void updateModelInstances() { if(opaqueModel != null) opaqueModel.dispose(); if(translucentModel != null) translucentModel.dispose(); Mesh opaqueMesh = mesher.meshFaces(opaqueFaces, meshBuilder); Mesh translucentMesh = mesher.meshFaces(translucentFaces, meshBuilder); modelBuilder.begin(); modelBuilder.part(String.format("c-%d,%d", startPosition.x, startPosition.z), opaqueMesh, GL20.GL_TRIANGLES, new Material(TextureAttribute.createDiffuse(NormalBlockRenderer.getBlockMap()))); opaqueModel = modelBuilder.end(); modelBuilder.begin(); modelBuilder.part(String.format("c-%d,%d-t", startPosition.x, startPosition.z), translucentMesh, GL20.GL_TRIANGLES, new Material(TextureAttribute.createDiffuse(NormalBlockRenderer.getBlockMap()), new BlendingAttribute())); translucentModel = modelBuilder.end(); opaqueModelInstance = new ModelInstance(opaqueModel); translucentModelInstance = new ModelInstance(translucentModel); } private void updateFaces() { parentWorld.incrChunksMeshing(); final Block[][][] translucent = new Block[size][height][size]; final Block[][][] opaque = new Block[size][height][size]; eachBlock(new EachBlockCallee() { @Override public void call(Block block, int x, int y, int z) { if (block != null) { if (block.isTranslucent()) translucent[x][y][z] = block; else opaque[x][y][z] = block; } } }); opaqueFaces = mesher.getFaces(opaque, lightLevels); translucentFaces = mesher.getFaces(translucent, lightLevels); meshing = false; meshed = true; parentWorld.decrChunksMeshing(); VoxelGameAPI.instance.getEventManager().push(new EventChunkRender(Chunk.this)); } }
package com.DroneSimulator; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Toolkit; import java.awt.event.KeyEvent; import java.awt.event.WindowEvent; import javax.swing.*; public class Screen extends JPanel{ private JFrame frame; private Dimension dim = null; private SimulationRun simRun = null; private Simulation simulation = null; private JProgressBar progressBar = null; private int cursorX, cursorY; public Screen(Simulation sim) { this.simulation = sim; this.simRun = this.simulation.generateNext(); frame = new JFrame(); frame.setTitle("UAV BCI Software"); frame.setExtendedState(JFrame.MAXIMIZED_BOTH); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setBackground(Color.WHITE); frame.add(this); frame.setVisible(true); dim = Toolkit.getDefaultToolkit().getScreenSize(); this.progressBar = new JProgressBar(); cursorX = (int) simRun.getStartX(); cursorY = (int) simRun.getStartY(); //Initialise Maps for Keybindings. InputMap im = this.getInputMap(JPanel.WHEN_IN_FOCUSED_WINDOW); ActionMap am = this.getActionMap(); //Keybindings im.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "Enter"); im.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE,0), "Escape"); im.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP,0), "Up"); im.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN,0), "Down"); im.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT,0), "Right"); im.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT,0), "Left"); am.put("Escape", new KeyAction("Escape", this)); am.put("Enter", new KeyAction("Enter", this)); am.put("Up", new KeyAction("Up", this)); am.put("Down", new KeyAction("Down", this)); am.put("Right", new KeyAction("Right", this)); am.put("Left", new KeyAction("Left", this)); } @Override public void paint(Graphics g) { super.paint(g); if(isHit()){ simRun = this.simulation.generateNext(); //Reset simulation cursorX = (int) simRun.getStartX(); // Adjust Coordinates cursorY = (int) simRun.getStartY(); } int height = (int) simRun.getTargetHeight(); int width = (int) simRun.getTargetWidth(); g.setColor(Color.RED); g.fillRect(dim.width/2 - width/2, dim.height/2 - height/2, width, height); g.setColor(Color.BLACK); g.fillOval(cursorX, cursorY, 10, 10); } /** * Handles enter key presses */ public void enterKey(){ this.simRun = this.simulation.generateNext(); //Reset simulation cursorX = (int) simRun.getStartX(); // Adjust Coordinates cursorY = (int) simRun.getStartY(); this.repaint(); } /** * Handles escape key presses */ public void escapeKey(){ this.frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING)); } /** * Handles up key presses */ public void upKey(){ cursorY -= 10; cursorY = (cursorY < 0) ? 0 : cursorY; this.repaint(); } /** * Handles down key presses */ public void downKey(){ cursorY += 10; cursorY = (int) ((cursorY > (dim.getHeight()-70)) ? (dim.getHeight()-70) : cursorY); this.repaint(); } /** * Handles right key presses */ public void rightKey(){ cursorX += 10; cursorX = (int) ((cursorX > (dim.getWidth()-10)) ? (dim.getWidth()-10) : cursorX); this.repaint(); } /** * Handles left key presses */ public void leftKey(){ cursorX -= 10; cursorX = (cursorX < 0) ? 0 : cursorX; this.repaint(); } /** * Checks if the cursor hit the target * @return true if hit, otherwise false. */ public boolean isHit(){ return (cursorY) <= (dim.getHeight()/2 + simRun.getTargetHeight()/2) && (cursorY) >= (dim.getHeight()/2 - simRun.getTargetHeight()/2) && (cursorX) <= (dim.getWidth()/2 + simRun.getTargetWidth()/2) && (cursorX) >= (dim.getWidth()/2 - simRun.getTargetWidth()/2); } }
package eu.theunitry.fabula.levels; import eu.theunitry.fabula.UNGameEngine.graphics.UNGameScreen; import eu.theunitry.fabula.UNGameEngine.graphics.UNColor; import eu.theunitry.fabula.UNGameEngine.graphics.UNGraphicsObject; import eu.theunitry.fabula.UNGameEngine.graphics.UNLevel; import eu.theunitry.fabula.UNGameEngine.launcher.UNLauncher; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Random; /** * Level 4 * Ruben Smit */ public class Level4 extends UNLevel { private Timer timer; private ArrayList<UNGraphicsObject> rockets, machines, supportsL, supportsR, cables, gems; private JButton button; private boolean winning, cableRelease, supportRelease, rocketRelease; private UNColor color; private String lastHelp; private ArrayList<JLabel> ufosText, answers; private double rocketIndex, machineIndex, supportLIndex, supportRIndex, cableIndex; private int machineState, g1, g2, answer, fakeAnswer1, fakeAnswer2, touch; /** * Level 3 * @param gameScreen * @param hudEnabled */ public Level4(UNGameScreen gameScreen, boolean hudEnabled) { super(gameScreen, hudEnabled); machines = new ArrayList<>(); supportsL = new ArrayList<>(); supportsR = new ArrayList<>(); rockets = new ArrayList<>(); cables = new ArrayList<>(); gems = new ArrayList<>(); gameScreen.getMusic().get("song2").play(true); gameScreen.getMusic().get("song2").setVolume(0.1); this.setBackgroundImage(gameScreen.getBackgrounds().get("silo")); setPlayerHasWon(false); winning = false; this.lastHelp = getHelp(); this.rocketIndex = 0; this.machineIndex = 0; this.supportLIndex = 1; this.supportRIndex = 1; this.cableIndex = 1; this.g1 = new Random().nextInt(5) + 5; this.g2 = new Random().nextInt(4) + 1; this.answer = g1 - g2; this.setQuestion("Wat is " + g1 +" min " + g2 + "?"); this.addHelp("Jammer! Probeer het nog eens."); this.addHelp("Helaas! Probeer het nog een keer!"); this.setHelp("Sleep het aantal diamanten naar de machine."); this.color = new UNColor(); machines.add(new UNGraphicsObject(gameScreen.getWindow().getFrame(), 415, 265, gameScreen.getSprites().get("2:4:0:0"), false, 170 , 200)); cables.add(new UNGraphicsObject(gameScreen.getWindow().getFrame(), 208, 358, gameScreen.getSprites().get("2:4:4:1"), false, 205, 105)); supportsR.add(new UNGraphicsObject(gameScreen.getWindow().getFrame(), 295, 315, gameScreen.getSprites().get("2:4:5:1"), false, 95, 150)); supportsL.add(new UNGraphicsObject(gameScreen.getWindow().getFrame(), 145, 315, gameScreen.getSprites().get("2:4:6:1"), false, 95, 150)); rockets.add(new UNGraphicsObject(gameScreen.getWindow().getFrame(), 190, 220, gameScreen.getSprites().get("2:4:7:0"), false, 160,250)); gems.add(new UNGraphicsObject(gameScreen.getWindow().getFrame(), 570, 120, gameScreen.getSprites().get("2:9:1"), true, 40, 40)); gems.add(new UNGraphicsObject(gameScreen.getWindow().getFrame(), 620, 120, gameScreen.getSprites().get("2:9:1"), true, 40, 40)); gems.add(new UNGraphicsObject(gameScreen.getWindow().getFrame(), 670, 120, gameScreen.getSprites().get("2:9:1"), true, 40, 40)); gems.add(new UNGraphicsObject(gameScreen.getWindow().getFrame(), 570, 175, gameScreen.getSprites().get("2:9:1"), true, 40, 40)); gems.add(new UNGraphicsObject(gameScreen.getWindow().getFrame(), 620, 175, gameScreen.getSprites().get("2:9:1"), true, 40, 40)); gems.add(new UNGraphicsObject(gameScreen.getWindow().getFrame(), 670, 175, gameScreen.getSprites().get("2:9:1"), true, 40, 40)); gems.add(new UNGraphicsObject(gameScreen.getWindow().getFrame(), 590, 235, gameScreen.getSprites().get("2:9:1"), true, 40, 40)); gems.add(new UNGraphicsObject(gameScreen.getWindow().getFrame(), 645, 235, gameScreen.getSprites().get("2:9:1"), true, 40, 40)); for (UNGraphicsObject rocket : rockets) { addObject(rocket); } for (UNGraphicsObject supportL : supportsL) { addObject(supportL); } for (UNGraphicsObject supportR : supportsR) { addObject(supportR); } for (UNGraphicsObject machine : machines) { addObject(machine); } for (UNGraphicsObject cable : cables) { addObject(cable); } for (UNGraphicsObject gem : gems) { addObject(gem); } this.button = new JButton("Nakijken"); this.setLayout(null); this.button.setBounds(618, 64, 150, 50); this.button.setBackground(new Color(51, 51, 51)); this.button.setFont(new Font("Minecraftia", Font.PLAIN, 15)); this.button.setForeground(Color.white); this.button.setOpaque(true); /** * Reset Default Styling */ this.button.setFocusPainted(false); this.button.setBorderPainted(false); add(button); button.setText("Nakijken"); for (int i = 0; i < 4; i++){ gameScreen.addSubLevel4(); } machineState = gameScreen.getSubLevel4(); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (button.getText() == "Doorgaan") { if (gameScreen.getSubLevel4() <= 5) { if (winning) { gameScreen.addSubLevel4(); } gameScreen.switchPanel(new Level4(gameScreen, true)); gameScreen.setSubLevel4(gameScreen.getSubLevel4()); } } else if (button.getText() == "Nakijken"){ for (UNGraphicsObject gem : gems) { for (UNGraphicsObject machine : machines){ if (machine.getHitbox().intersects(gem.getHitbox())) { touch++; } } if (touch == answer){ if (gameScreen.getSubLevel4() == 5) { button.setText("Lanceren!"); setHelp("Hoera! Nu kunnen we naar de maan."); } else{ setHelp("Jij kan goed rekenen!"); winning = true; } for (UNGraphicsObject ge : gems) { removeObject(ge); } } else{ addMistake(); if (getMistakes() > 3) { button.setText("Doorgaan"); getHelper().setState(4); if (touch < answer) { setHelp("Jammer, er moest" + ((answer - touch == 1) ? "" : "en") + " nog " + (answer - touch) + " diamant" + ((answer - touch == 1) ? "" : "en") + " bij. Want " + g1 + " min " + g2 + " is " + answer + ". Jij had er " + touch + "." ); } else { setHelp("Jammer, er moest" + ((touch - answer == 1) ? "" : "en") + " " + (touch - answer) + " diamant" + ((touch - answer == 1) ? "" : "en") + " af. Want " + g1 + " min " + g2 + " is " + answer + ". Jij had er " + touch + "." ); } for (UNGraphicsObject ge : gems) { ge.setClickable(false); } winning = false; } } } } else{ winning = true; button.remove(button); new java.util.Timer().schedule( new java.util.TimerTask() { @Override public void run() { levelDone(4); gameScreen.addSubLevel4(); } }, 4500 ); } } }); timer = new Timer(10, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (rocketRelease) { if (rocketIndex < 3) { rocketIndex += 0.07; } else { rocketIndex = 1; } for (UNGraphicsObject rocket : rockets) { rocket.setImage(gameScreen.getSprites().get("2:4:7:" + (int) Math.round(rocketIndex))); } new java.util.Timer().schedule( new java.util.TimerTask() { @Override public void run() { supportRelease = true; } }, 500 ); } if (machineIndex < 3) { machineIndex += 0.1; } else { machineIndex = 0; } if (machineState == 5 && winning){ machineState = 6; } for (UNGraphicsObject machine : machines) { switch (machineState) { case 1: machine.setImage(gameScreen.getSprites().get("2:4:" + (int) Math.round(machineIndex) + ":0")); break; case 2: machine.setImage(gameScreen.getSprites().get("2:4:" + (int) Math.round(machineIndex) + ":1")); break; case 3: machine.setImage(gameScreen.getSprites().get("2:4:" + (int) Math.round(machineIndex) + ":2")); break; case 4: machine.setImage(gameScreen.getSprites().get("2:4:" + (int) Math.round(machineIndex) + ":3")); break; case 5: machine.setImage(gameScreen.getSprites().get("2:4:" + (int) Math.round(machineIndex) + ":4")); break; case 6: machine.setImage(gameScreen.getSprites().get("2:4:" + (int) Math.round(machineIndex) + ":5")); cableRelease = true; break; } } if (cableRelease) { if (cableIndex < 6) { cableIndex += 0.07; } for (UNGraphicsObject cable : cables) { cable.setImage(gameScreen.getSprites().get("2:4:4:" + (int) Math.round(cableIndex))); } new java.util.Timer().schedule( new java.util.TimerTask() { @Override public void run() { rocketRelease = true; } }, 1000 ); } if (supportRelease) { new java.util.Timer().schedule( new java.util.TimerTask() { @Override public void run() { for (UNGraphicsObject rocket : rockets){ if (rocket.getX() < 200) { rocket.setY(rocket.getY() - 2); } else{ removeObject(rocket); } } } }, 200 ); if (supportRIndex < 7) { supportRIndex += 0.05; } for (UNGraphicsObject supportR : supportsR) { supportR.setImage(gameScreen.getSprites().get("2:4:5:" + (int) Math.round(supportRIndex))); } if (supportLIndex < 7) { supportLIndex += 0.05; } for (UNGraphicsObject supportL : supportsL) { supportL.setImage(gameScreen.getSprites().get("2:4:6:" + (int) Math.round(supportLIndex))); } gameScreen.resetSubLevel4(); } } }); timer.start(); } }
package de.htwg.gobang.entities; public class GameField{ private static final int TokenToWin = 5; private static final int FieldSize = 19; private static GameToken[][] matrix; public GameField(){ matrix = new GameToken[FieldSize][FieldSize]; } public int getFieldSize(){ return FieldSize; } @SuppressWarnings("static-access") public char putStone(int x, int y, GameToken token){ int tx = x-1; int ty = y-1; if(isValid(tx, ty)) { if(matrix[tx][ty] != null) { return 'b'; } this.matrix[tx][ty] = token; return getWin(tx, ty, token); } return 'f'; } private static boolean isValid(int x, int y) { if(x >= FieldSize || x < 0 || y >= FieldSize || y < 0) { return false; } return true; } public char removeToken(int x, int y) { int tx = x-1; int ty = y-1; if(isValid(x, y)) { if (matrix[tx][ty] == null) { return 'f'; } matrix[tx][ty] = null; return 'r'; } return 'f'; } @SuppressWarnings("static-access") private char getWin(int x, int y, GameToken token) { Checker myCheck = createChain(); myCheck.getWin(x, y, token); if (myCheck.win == 1) { return 'g'; } return 'e'; } private static Checker createChain(){ Checker myChecker = new LeftChecker(); Checker myRCheck = new RightChecker(); Checker myTCheck = new TopChecker(); Checker myDCheck = new DownChecker(); Checker myTLCheck = new TopLeftChecker(); Checker myTRCheck = new TopRightChecker(); Checker myDLCheck = new DownRightChecker(); Checker myDRCheck = new DownLeftChecker(); myChecker.setNext(myRCheck); myRCheck.setNext(myTCheck); myTCheck.setNext(myDCheck); myDCheck.setNext(myTLCheck); myTLCheck.setNext(myDRCheck); myDRCheck.setNext(myTRCheck); myTRCheck.setNext(myDLCheck); return myChecker; } abstract static class Checker { protected static int counter = 1; protected static int tend = 0; protected static int win = 0; private Checker next; public void resetCounter() { counter = 1; } public void setNext(Checker nChecker) { next = nChecker; } public void getWin(int x, int y, GameToken token) { tend = 0; checkWin(x, y, token); if (tend == 1 && counter >= TokenToWin) { win = 1; return; } else if (tend == 1) { resetCounter(); } if (next != null){ next.getWin(x, y, token); } } public int checkStep(int x, int y, GameToken token) { if (isValid(x, y) && matrix[x][y] == token) { return 1; } return 0; } abstract protected void checkWin(int x, int y, GameToken token); } static class LeftChecker extends Checker { @SuppressWarnings("static-access") @Override protected void checkWin(int x, int y, GameToken token) { int ty = y - 1; if (checkStep(x, ty, token) == 1) { super.counter += 1; checkWin(x, ty, token); } } } static class RightChecker extends Checker { @SuppressWarnings("static-access") @Override protected void checkWin(int x, int y, GameToken token) { int ty = y + 1; if (checkStep(x, ty, token) == 1) { super.counter += 1; checkWin(x, ty, token); } super.tend = 1; } } static class TopChecker extends Checker { @SuppressWarnings("static-access") @Override protected void checkWin(int x, int y, GameToken token) { int tx = x - 1; if (checkStep(tx, y, token) == 1) { super.counter += 1; checkWin(tx, y, token); } } } static class DownChecker extends Checker { @SuppressWarnings("static-access") @Override protected void checkWin(int x, int y, GameToken token) { int tx = x + 1; if (checkStep(tx, y, token) == 1) { super.counter += 1; checkWin(tx, y, token); } super.tend = 1; } } static class TopLeftChecker extends Checker { @SuppressWarnings("static-access") @Override protected void checkWin(int x, int y, GameToken token) { int tx = x - 1; int ty = y + 1; if (checkStep(tx, ty, token) == 1) { super.counter += 1; checkWin(tx, ty, token); } } } static class DownRightChecker extends Checker { @SuppressWarnings("static-access") @Override protected void checkWin(int x, int y, GameToken token) { int tx = x + 1; int ty = y - 1; if (checkStep(tx, ty, token) == 1) { super.counter += 1; checkWin(tx, ty, token); } super.tend = 1; } } static class TopRightChecker extends Checker { @SuppressWarnings("static-access") @Override protected void checkWin(int x, int y, GameToken token) { int tx = x + 1; int ty = y + 1; if (checkStep(tx, ty, token) == 1) { super.counter += 1; checkWin(tx, y, token); } } } static class DownLeftChecker extends Checker { @SuppressWarnings("static-access") @Override protected void checkWin(int x, int y, GameToken token) { int tx = x - 1; int ty = y - 1; if (checkStep(tx, ty, token) == 1) { super.counter += 1; checkWin(tx, ty, token); } super.tend = 1; } } }
package imj3.draft.processing; import static imj3.tools.AwtImage2D.awtRead; import static imj3.tools.CommonSwingTools.limitHeight; import static imj3.tools.CommonSwingTools.setModel; import static java.lang.Math.max; import static java.lang.Math.min; import static net.sourceforge.aprog.swing.SwingTools.horizontalBox; import static net.sourceforge.aprog.swing.SwingTools.horizontalSplit; import static net.sourceforge.aprog.swing.SwingTools.scrollable; import static net.sourceforge.aprog.swing.SwingTools.verticalBox; import static net.sourceforge.aprog.tools.Tools.append; import static net.sourceforge.aprog.tools.Tools.array; import static net.sourceforge.aprog.tools.Tools.baseName; import static net.sourceforge.aprog.tools.Tools.cast; import static net.sourceforge.aprog.tools.Tools.join; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.xml.StaxDriver; import imj2.pixel3d.MouseHandler; import imj2.tools.Canvas; import imj3.draft.processing.VisualAnalysis.Context.Refresh; import imj3.draft.processing.VisualAnalysis.Experiment.ClassDescription; import imj3.draft.segmentation.ImageComponent; import imj3.draft.segmentation.ImageComponent.Layer; import imj3.draft.segmentation.ImageComponent.Painter; import imj3.tools.CommonSwingTools.NestedList; import imj3.tools.CommonSwingTools.PropertyGetter; import imj3.tools.CommonSwingTools.PropertySetter; import imj3.tools.CommonSwingTools.StringGetter; import imj3.tools.CommonSwingTools.UserObject; import java.awt.BasicStroke; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Rectangle; import java.awt.dnd.DropTarget; import java.awt.dnd.DropTargetDropEvent; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseWheelEvent; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.Serializable; import java.io.UncheckedIOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.prefs.Preferences; import javax.imageio.ImageIO; import javax.swing.AbstractAction; import javax.swing.Box; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JSplitPane; import javax.swing.JTextField; import javax.swing.JTree; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreePath; import net.sourceforge.aprog.swing.SwingTools; import net.sourceforge.aprog.tools.IllegalInstantiationException; import net.sourceforge.aprog.tools.Tools; /** * @author codistmonk (creation 2015-02-13) */ public final class VisualAnalysis { private VisualAnalysis() { throw new IllegalInstantiationException(); } static final Preferences preferences = Preferences.userNodeForPackage(VisualAnalysis.class); static final XStream xstream = new XStream(new StaxDriver()); public static final String IMAGE_PATH = "image.path"; public static final String GROUND_TRUTH = "groundtruth"; public static final String EXPERIMENT = "experiment"; /** * @param commandLineArguments * <br>Unused */ public static final void main(final String[] commandLineArguments) { SwingTools.useSystemLookAndFeel(); final Context context = new Context(); SwingUtilities.invokeLater(new Runnable() { @Override public final void run() { SwingTools.show(new MainPanel(context), VisualAnalysis.class.getSimpleName(), false); context.setImage(new File(preferences.get(IMAGE_PATH, ""))); context.setGroundTruth(preferences.get(GROUND_TRUTH, "gt")); context.setExperiment(new File(preferences.get(EXPERIMENT, "experiment.xml"))); } }); } public static final Component label(final String text, final Component... components) { return limitHeight(horizontalBox(append(array((Component) new JLabel(text)), components))); } public static final <C extends JComponent> C centerX(final C component) { component.setAlignmentX(Component.CENTER_ALIGNMENT); return component; } public static final JTextField textView(final String text) { final JTextField result = new JTextField(text); result.setEditable(false); return result; } public static final JButton button(final String type) { final JButton result = new JButton(new ImageIcon(Tools.getResourceURL("lib/tango/" + type + ".png"))); final int size = max(result.getIcon().getIconWidth(), result.getIcon().getIconHeight()); result.setPreferredSize(new Dimension(size + 2, size + 2)); return result; } /** * @author codistmonk (creation 2015-02-19) */ public static final class FileSelector extends JButton { private final List<File> files = new ArrayList<>(); private File selectedFile; private ActionListener fileListener; { this.addActionListener(new ActionListener() { @Override public final void actionPerformed(final ActionEvent event) { FileSelector.this.showPopup(); } }); this.setMaximumSize(new Dimension(Integer.MAX_VALUE, 26)); this.setHorizontalAlignment(SwingConstants.LEFT); } public final ActionListener getFileListener() { return this.fileListener; } public final void setFileListener(final ActionListener fileListener) { this.fileListener = fileListener; } public final File getSelectedFile() { return this.selectedFile; } public final FileSelector setFile(final File file) { this.files.remove(file); this.files.add(0, file); final boolean changed = !file.equals(this.getSelectedFile()); if (changed) { this.selectedFile = file; this.setText(file.getName()); if (this.fileListener != null) { this.fileListener.actionPerformed(new ActionEvent(this, -1, null)); } } return this; } final void showPopup() { final JPopupMenu popup = new JPopupMenu(); for (final File file : this.files) { popup.add(new JMenuItem(new AbstractAction(file.getPath()) { @Override public final void actionPerformed(final ActionEvent event) { FileSelector.this.setFile(file); } private static final long serialVersionUID = 8311454620470586686L; })); } popup.show(this, 0, 0); } private static final long serialVersionUID = 7227165282556980768L; } public static final File save(final String preferenceKey, final String title, final Component parent) { final JFileChooser fileChooser = new JFileChooser(new File(preferences.get(preferenceKey, "")).getParentFile()); if (JFileChooser.APPROVE_OPTION == fileChooser.showSaveDialog(parent)) { return fileChooser.getSelectedFile(); } return null; } public static final File open(final String preferenceKey, final String title, final Component parent) { final JFileChooser fileChooser = new JFileChooser(new File(preferences.get(preferenceKey, "")).getParentFile()); if (JFileChooser.APPROVE_OPTION == fileChooser.showOpenDialog(parent)) { return fileChooser.getSelectedFile(); } return null; } /** * @author codistmonk (creation 2015-02-13) */ public static final class MainPanel extends JPanel { private final Context context; private final FileSelector imageSelector; private final JCheckBox imageVisibilitySelector; private final FileSelector groundTruthSelector; private final JCheckBox groundTruthVisibilitySelector; private final FileSelector experimentSelector; private final JTextField trainingTimeView; private final JTextField classificationTimeView; private final JCheckBox classificationVisibilitySelector; private final JTextField scoreView; private final JTree tree; private final JSplitPane mainSplitPane; private ImageComponent imageComponent; private Experiment experiment; private final Point mouse; private int brushSize; public MainPanel(final Context context) { super(new BorderLayout()); this.context = context; this.imageSelector = new FileSelector(); this.imageVisibilitySelector = new JCheckBox("", true); this.groundTruthSelector = new FileSelector(); this.groundTruthVisibilitySelector = new JCheckBox(); this.experimentSelector = new FileSelector(); this.trainingTimeView = textView("-"); this.classificationTimeView = textView("-"); this.classificationVisibilitySelector = new JCheckBox(); this.scoreView = textView("-"); this.tree = new JTree(new DefaultTreeModel(new DefaultMutableTreeNode("No experiment"))); this.mouse = new Point(); this.brushSize = 1; final int padding = this.imageVisibilitySelector.getPreferredSize().width; final JButton openImageButton = button("open"); final JButton newGroundTruthButton = button("new"); final JButton saveGroundTruthButton = button("save"); final JButton refreshGroundTruthButton = button("refresh"); final JButton newExperimentButton = button("new"); final JButton openExperimentButton = button("open"); final JButton runExperimentButton = button("process"); final JButton saveExperimentButton = button("save"); final JButton refreshExperimentButton = button("refresh"); this.mainSplitPane = horizontalSplit(verticalBox( label(" Image: ", this.imageSelector, openImageButton, this.imageVisibilitySelector), label(" Ground truth: ", this.groundTruthSelector, newGroundTruthButton, saveGroundTruthButton, refreshGroundTruthButton, this.groundTruthVisibilitySelector), label(" Experiment: ", this.experimentSelector, newExperimentButton, openExperimentButton, runExperimentButton, saveExperimentButton, refreshExperimentButton, Box.createHorizontalStrut(padding)), label(" Training (s): ", this.trainingTimeView, button("process"), Box.createHorizontalStrut(padding)), label(" Classification (s): ", this.classificationTimeView, button("process"), button("save"), button("refresh"), this.classificationVisibilitySelector), label(" F1: ", this.scoreView, Box.createHorizontalStrut(padding)), centerX(new JButton("Confusion matrix...")), scrollable(this.tree)), scrollable(new JLabel("Drop file here"))); this.mainSplitPane.getLeftComponent().setMaximumSize(new Dimension(128, Integer.MAX_VALUE)); this.add(this.mainSplitPane, BorderLayout.CENTER); openImageButton.addActionListener(new ActionListener() { @Override public final void actionPerformed(final ActionEvent event) { final File file = open(IMAGE_PATH, "Open image", MainPanel.this); if (file != null) { context.setImage(file); } } }); this.imageSelector.setFileListener(new ActionListener() { @Override public final void actionPerformed(final ActionEvent event) { context.setImage(MainPanel.this.getImageSelector().getSelectedFile()); } }); this.groundTruthSelector.setFileListener(new ActionListener() { @Override public final void actionPerformed(final ActionEvent event) { context.refreshGroundTruthAndClassification(Refresh.FROM_FILE); } }); newGroundTruthButton.addActionListener(e -> { final String name = JOptionPane.showInputDialog("Ground truth name:"); if (name != null && context.getImage() != null) { try { ImageIO.write(context.formatGroundTruth().getGroundTruth().getImage(), "png", new File(context.getGroundTruthPath(name))); } catch (final IOException exception) { throw new UncheckedIOException(exception); } context.setGroundTruth(name); } }); saveGroundTruthButton.addActionListener(e -> Tools.debugPrint("TODO")); this.experimentSelector.setFileListener(new ActionListener() { @Override public final void actionPerformed(final ActionEvent event) { context.setExperiment(MainPanel.this.getExperimentSelector().getSelectedFile()); } }); newExperimentButton.addActionListener(e -> { final File file = save(EXPERIMENT, "New experiment", MainPanel.this); if (file != null) { try (final OutputStream output = new FileOutputStream(file)) { xstream.toXML(new Experiment(), output); } catch (final IOException exception) { throw new UncheckedIOException(exception); } context.setExperiment(file); } }); openExperimentButton.addActionListener(e -> Tools.debugPrint("TODO")); saveExperimentButton.addActionListener(e -> Tools.debugPrint("TODO")); this.imageVisibilitySelector.addActionListener(new ActionListener() { @Override public final void actionPerformed(final ActionEvent event) { final Layer imageLayer = MainPanel.this.getImageComponent().getLayers().get(0); final Painter imagePainter = imageLayer.getPainters().get(0); final boolean imageVisible = MainPanel.this.getImageVisibilitySelector().isSelected(); if (!imageVisible) { imageLayer.getCanvas().clear(Color.GRAY); } imagePainter.getActive().set(imageVisible); imagePainter.getUpdateNeeded().set(true); MainPanel.this.getImageComponent().repaint(); } }); this.groundTruthVisibilitySelector.addActionListener(new ActionListener() { @Override public final void actionPerformed(final ActionEvent event) { final Layer groundTruthLayer = MainPanel.this.getImageComponent().getLayers().get(1); final Painter groundTruthPainter = groundTruthLayer.getPainters().get(0); final boolean groundTruthVisible = MainPanel.this.getGroundTruthVisibilitySelector().isSelected(); groundTruthPainter.getActive().set(groundTruthVisible); groundTruthPainter.getUpdateNeeded().set(true); MainPanel.this.getImageComponent().repaint(); } }); this.classificationVisibilitySelector.addActionListener(new ActionListener() { @Override public final void actionPerformed(final ActionEvent event) { final Layer classificationLayer = MainPanel.this.getImageComponent().getLayers().get(2); final Painter classificationPainter = classificationLayer.getPainters().get(0); final boolean classificationVisible = MainPanel.this.getClassificationVisibilitySelector().isSelected(); classificationPainter.getActive().set(classificationVisible); classificationPainter.getUpdateNeeded().set(true); MainPanel.this.getImageComponent().repaint(); } }); this.setDropTarget(new DropTarget() { @Override public final synchronized void drop(final DropTargetDropEvent event) { final File file = SwingTools.getFiles(event).get(0); if (file.getName().toLowerCase(Locale.ENGLISH).endsWith(".xml")) { context.setExperiment(file); } else { context.setImage(file); } } /** * {@value}. */ private static final long serialVersionUID = 5442000733451223725L; }); this.setPreferredSize(new Dimension(800, 600)); context.setMainPanel(this); } public final int getBrushSize() { return this.brushSize; } public final void setBrushSize(final int brushSize) { this.brushSize = max(1, min(brushSize, 128)); } public final Point getMouse() { return this.mouse; } public final Context getContext() { return this.context; } public final Experiment getExperiment() { return this.experiment; } public final void setExperiment(final Experiment experiment) { this.experiment = experiment; setModel(this.tree, experiment, "Experiment"); } public final ImageComponent getImageComponent() { return this.imageComponent; } final void setImage(final String path) { this.imageComponent = new ImageComponent(awtRead(path)); this.getImageComponent().addLayer().getPainters().add(new Painter.Abstract() { @Override public final void paint(final Canvas canvas) { canvas.getGraphics().drawImage(MainPanel.this.getContext().getGroundTruth().getImage(), 0, 0, null); } private static final long serialVersionUID = 4700895082820237288L; }); this.getImageComponent().addLayer().getPainters().add(new Painter.Abstract() { @Override public final void paint(final Canvas canvas) { canvas.getGraphics().drawImage(MainPanel.this.getContext().getClassification().getImage(), 0, 0, null); } private static final long serialVersionUID = 7941391067177261093L; }); this.getImageComponent().addLayer().getPainters().add(new Painter.Abstract() { @Override public final void paint(final Canvas canvas) { final Point m = MainPanel.this.getMouse(); if (0 < m.x) { final int s = MainPanel.this.getBrushSize(); canvas.getGraphics().setColor(Color.WHITE); canvas.getGraphics().drawOval(m.x - s / 2, m.y - s / 2, s, s); } } private static final long serialVersionUID = -476876650788388190L; }); new MouseHandler(null) { private boolean dragging; @Override public final void mousePressed(final MouseEvent event) { this.mouseMoved(event); } @Override public final void mouseReleased(final MouseEvent event) { this.dragging = false; } @Override public final void mouseMoved(final MouseEvent event) { MainPanel.this.getMouse().setLocation(event.getX(), event.getY()); MainPanel.this.getImageComponent().getLayers().get(3).getPainters().get(0).getUpdateNeeded().set(true); MainPanel.this.getImageComponent().repaint(); } @Override public final void mouseExited(final MouseEvent event) { if (!this.dragging) { MainPanel.this.getMouse().x = -1; MainPanel.this.getImageComponent().getLayers().get(3).getPainters().get(0).getUpdateNeeded().set(true); MainPanel.this.getImageComponent().repaint(); } } @Override public final void mouseWheelMoved(final MouseWheelEvent event) { if (event.getWheelRotation() < 0) { MainPanel.this.setBrushSize(MainPanel.this.getBrushSize() + 1); } else { MainPanel.this.setBrushSize(MainPanel.this.getBrushSize() - 1); } MainPanel.this.getImageComponent().getLayers().get(3).getPainters().get(0).getUpdateNeeded().set(true); MainPanel.this.getImageComponent().repaint(); } @Override public final void mouseDragged(final MouseEvent event) { if (MainPanel.this.getGroundTruthVisibilitySelector().isSelected()) { final TreePath selectionPath = MainPanel.this.getTree().getSelectionPath(); final DefaultMutableTreeNode node = selectionPath == null ? null : cast(DefaultMutableTreeNode.class, selectionPath.getLastPathComponent()); final UserObject userObject = node == null ? null : cast(UserObject.class, node.getUserObject()); final ClassDescription classDescription = userObject == null ? null : cast(ClassDescription.class, userObject.getUIScaffold().getObject()); if (classDescription != null) { this.dragging = true; final Graphics2D g = MainPanel.this.getContext().getGroundTruth().getGraphics(); final Point m = MainPanel.this.getMouse(); final int x = event.getX(); final int y = event.getY(); g.setColor(new Color(classDescription.getLabel(), true)); g.setStroke(new BasicStroke(MainPanel.this.getBrushSize(), BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND)); g.drawLine(m.x, m.y, x, y); MainPanel.this.getImageComponent().getLayers().get(1).getPainters().get(0).getUpdateNeeded().set(true); } } this.mouseMoved(event); } private static final long serialVersionUID = 1137846082170903999L; }.addTo(this.getImageComponent()); this.setContents(this.getImageComponent()); } public final FileSelector getImageSelector() { return this.imageSelector; } public final JTree getTree() { return this.tree; } public final JCheckBox getImageVisibilitySelector() { return this.imageVisibilitySelector; } public final FileSelector getGroundTruthSelector() { return this.groundTruthSelector; } public final JCheckBox getGroundTruthVisibilitySelector() { return this.groundTruthVisibilitySelector; } public final FileSelector getExperimentSelector() { return this.experimentSelector; } public final JTextField getTrainingTimeView() { return this.trainingTimeView; } public final JTextField getClassificationTimeView() { return this.classificationTimeView; } public final JCheckBox getClassificationVisibilitySelector() { return this.classificationVisibilitySelector; } public final JTextField getScoreView() { return this.scoreView; } public final void setContents(final Component component) { this.mainSplitPane.setRightComponent(scrollable(component)); } private static final long serialVersionUID = 2173077945563031333L; public static final int IMAGE_SELECTOR_RESERVED_SLOTS = 2; } /** * @author codistmonk (creation 2015-02-13) */ public static final class Context implements Serializable { private MainPanel mainPanel; private final Canvas groundTruth = new Canvas(); private final Canvas classification = new Canvas(); public final MainPanel getMainPanel() { return this.mainPanel; } public final void setMainPanel(final MainPanel mainPanel) { this.mainPanel = mainPanel; } public final File getExperimentFile() { return this.getMainPanel().getExperimentSelector().getSelectedFile(); } public final String getGroundTruthName() { return this.getMainPanel().getGroundTruthSelector().getText(); } public final Context setGroundTruthName(final String groundTruthName) { this.getMainPanel().getGroundTruthSelector().setFile(new File(groundTruthName)); return this; } public final BufferedImage getImage() { final MainPanel mainPanel = this.getMainPanel(); final ImageComponent imageComponent = mainPanel == null ? null : mainPanel.getImageComponent(); return imageComponent == null ? null : imageComponent.getImage(); } public final Canvas getGroundTruth() { return this.groundTruth; } public final Context formatGroundTruth() { return format(this.getGroundTruth()); } public final Canvas getClassification() { return this.classification; } public final String getExperimentName() { final File experimentFile = this.getExperimentFile(); return experimentFile == null ? null : baseName(experimentFile.getName()); } public final File getImageFile() { return new File(this.getMainPanel().getImageSelector().getText()); } public final String getGroundTruthPath() { return this.getGroundTruthPath(this.getGroundTruthName()); } public final String getGroundTruthPath(final String name) { return baseName(this.getImageFile().getPath()) + "_groundtruth_" + name + ".png"; } public final String getClassificationPath() { return baseName(this.getImageFile().getPath()) + "_classification_" + this.getGroundTruthName() + "_" + this.getExperimentName() + ".png"; } public final void refreshGroundTruthAndClassification(final Refresh refresh) { final BufferedImage image = this.getImage(); if (image == null) { return; } System.out.println(Tools.debug(Tools.DEBUG_STACK_OFFSET + 1)); Tools.debugPrint(this.getGroundTruthName()); final int imageWidth = image.getWidth(); final int imageHeight = image.getHeight(); this.getGroundTruth().setFormat(imageWidth, imageHeight, BufferedImage.TYPE_INT_ARGB); this.getClassification().setFormat(imageWidth, imageHeight, BufferedImage.TYPE_INT_ARGB); switch (refresh) { case CLEAR: this.getGroundTruth().clear(CLEAR); this.getClassification().clear(CLEAR); break; case FROM_FILE: { { final String groundTruthPath = this.getGroundTruthPath(); if (new File(groundTruthPath).isFile()) { this.getGroundTruth().getGraphics().drawImage(awtRead(groundTruthPath), 0, 0, null); } else { this.getGroundTruth().clear(CLEAR); } } { final String classificationPath = this.getClassificationPath(); if (new File(classificationPath).isFile()) { this.getClassification().getGraphics().drawImage(awtRead(classificationPath), 0, 0, null); } else { this.getClassification().clear(CLEAR); } } break; } case NOP: break; } } public final Context setImage(final File imageFile) { System.out.println(Tools.debug(Tools.DEBUG_STACK_OFFSET + 1, imageFile)); final File oldImageFile = this.getImageFile(); if (imageFile.isFile() && !imageFile.equals(oldImageFile)) { this.getMainPanel().setImage(imageFile.getPath()); this.getMainPanel().getImageSelector().setFile(imageFile); this.refreshGroundTruthAndClassification(Refresh.FROM_FILE); preferences.put(IMAGE_PATH, imageFile.getPath()); } return this; } public final Context setGroundTruth(final String name) { if (new File(this.getGroundTruthPath(name)).isFile()) { this.getMainPanel().getGroundTruthSelector().setFile(new File(name)); preferences.put(GROUND_TRUTH, name); } return this; } public final Context setExperiment(final File experimentFile) { if (experimentFile.isFile()) { this.getMainPanel().setExperiment((Experiment) xstream.fromXML(experimentFile)); this.getMainPanel().getExperimentSelector().setFile(experimentFile); preferences.put(EXPERIMENT, experimentFile.getPath()); } return this; } private final Context format(final Canvas canvas) { final BufferedImage image = this.getImage(); if (image != null) { canvas.setFormat(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB); } else { canvas.setFormat(1, 1, BufferedImage.TYPE_INT_ARGB); } canvas.clear(CLEAR); return this; } private static final long serialVersionUID = -2487965125442868238L; public static final Color CLEAR = new Color(0, true); /** * @author codistmonk (creation 2015-02-17) */ public static enum Refresh { NOP, CLEAR, FROM_FILE; } } /** * @author codistmonk (creation 2015-02-16) */ public static final class Experiment implements Serializable { private final List<ClassDescription> classDescriptions = new ArrayList<>(); private final List<TrainingField> trainingFields = new ArrayList<>(); @Override public final String toString() { return "Experiment"; } @NestedList(name="classes", element="class", elementClass=ClassDescription.class) public final List<ClassDescription> getClassDescriptions() { return this.classDescriptions; } @NestedList(name="training", element="training field", elementClass=TrainingField.class) public final List<TrainingField> getTrainingFields() { return this.trainingFields; } private static final long serialVersionUID = -4539259556658072410L; /** * @author codistmonk (creation 2015-02-16) */ public static final class ClassDescription implements Serializable { private String name = "class"; private int label = 0xFF000000; @StringGetter @PropertyGetter("name") public final String getName() { return this.name; } @PropertySetter("name") public final ClassDescription setName(final String name) { this.name = name; return this; } public final int getLabel() { return this.label; } public final ClassDescription setLabel(final int label) { this.label = label; return this; } @PropertyGetter("label") public final String getLabelAsString() { return "#" + Integer.toHexString(this.getLabel()).toUpperCase(Locale.ENGLISH); } @PropertySetter("label") public final ClassDescription setLabel(final String labelAsString) { return this.setLabel((int) Long.parseLong(labelAsString.substring(1), 16)); } private static final long serialVersionUID = 4974707407567297906L; } /** * @author codistmonk (creation 2015-02-17) */ public static final class TrainingField implements Serializable { private String imagePath = ""; private final Rectangle bounds = new Rectangle(); @PropertyGetter("image") public final String getImagePath() { return this.imagePath; } @PropertySetter("image") public final TrainingField setImagePath(final String imagePath) { this.imagePath = imagePath; return this; } public final Rectangle getBounds() { return this.bounds; } @PropertyGetter("bounds") public final String getBoundsAsString() { return join(",", this.getBounds().x, this.getBounds().y, this.getBounds().width, this.getBounds().height); } @PropertySetter("bounds") public final TrainingField setBounds(final String boundsAsString) { final int[] bounds = Arrays.stream(boundsAsString.split(",")).mapToInt(Integer::parseInt).toArray(); this.getBounds().setBounds(bounds[0], bounds[1], bounds[2], bounds[3]); return this; } @Override public final String toString() { return new File(this.getImagePath()).getName() + "[" + this.getBoundsAsString() + "]"; } private static final long serialVersionUID = 847822079141878928L; } } }
package javafe.reader; import java.io.*; import java.util.*; //import decsrc.util.*; import javafe.decsrc.ClassFileParser; import javafe.ast.*; import javafe.util.*; import javafe.genericfile.GenericFile; /** * Parses the contents of a class file into an AST for the purpose of * type checking. Ignores components of the class file that have no * relevance to type checking (e.g. method bodies). * * @deprecated Use BCELReader for Java 1.5 and later versions */ class ASTClassFileParser extends ClassFileParser { /** * The package name of the class being parsed. * Initialized by constructor (by way of set_this_class) */ // access only readonly by BinReader Name classPackage; /** * The AST of the class parsed by this parser. * Initialized by constructor (by way of parse_file). */ // access only readonly by BinReader //@ invariant typeDecl.specOnly; /*@ spec_protected non_null*/ TypeDecl typeDecl; /** * A dummy location representing the class being parsed. * Initialized by constructor. */ // access only readonly by BinReader //@ invariant classLocation != Location.NULL; int classLocation; /** * Vector of methods and fields with Synthetic attributes. * Use this to weed out synthetic while constructing TypeDecl. */ private/*@ non_null */Vector synthetics = new Vector(); /** * Flag indicating whether the class being parsed has the synthetic * attribute. */ private boolean syntheticClass = false; /** * Flag indicates that class bodies are currently being parsed, otherwise * only the type interface is parsed. */ private boolean includeBodies = false; /** * A flag indicating that parsed type declaration should ignore/omit * private class fields. */ private boolean omitPrivateFields = true; /** * Parse a class into a new class parser. Resulting class file is * stored in <code>typeDecl</code>; this will be a "spec only" * declaration. Its package is stored in <code>classPackage</code> * and a location for it is stored in <code>classLocation</code>. * @param inputFile the file to parse the class from * @param includeBodies if true, bodies are included, if not, only a spec is produced */ ASTClassFileParser(/*@ non_null */GenericFile inputFile, boolean includeBodies) throws IOException, ClassFormatError { super(); this.includeBodies = includeBodies; DataInputStream stream = null; try { this.inputFile = inputFile; this.classLocation = Location.createWholeFileLoc(inputFile); stream = new DataInputStream(inputFile.getInputStream()); parse_file(stream); //@ nowarn Invariant; // "parse_file" is a helper } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { } } } removeExtraArg(); } /** Binary inner class constructors have an extra initial argument to their constructors (the enclosing class). This is not present in the source file. To make the AST generated by reading the binary correspond to that obtained from a source file, we remove that extra argument for each inner (non-static) class. Since we do this at the end of parse_file, each nested class does this for its own direct inner classes. - DRCok */ public void removeExtraArg() { TypeDeclElemVec vv = typeDecl.elems; for (int k = 0; k < vv.size(); ++k) { if (!(vv.elementAt(k) instanceof ClassDecl)) continue; ClassDecl cd = (ClassDecl) vv.elementAt(k); if (Modifiers.isStatic(cd.modifiers)) continue; TypeDeclElemVec v = cd.elems; for (int j = 0; j < v.size(); ++j) { if (!(v.elementAt(j) instanceof ConstructorDecl)) continue; ConstructorDecl cdl = (ConstructorDecl) v.elementAt(j); cdl.args.removeElementAt(0); } } } /** * Add only AST nodes that are not synthetic decls to <code>v</code>. * <code>elems</code> should be an array of {@link TypeDeclElems}. * A synthetic decl is one that had the synthetic attribute, * or is a static method decl for an interface. */ protected void addNonSyntheticDecls(/*@ non_null */TypeDeclElemVec v, /*@ non_null */TypeDeclElem[] elems) { for (int i = 0; i < elems.length; i++) { if (synthetics.contains(elems[i])) { //@ nowarn; continue; } if ((modifiers & ACC_INTERFACE) != 0 && elems[i] instanceof RoutineDecl) { RoutineDecl rd = (RoutineDecl) elems[i]; if (Modifiers.isStatic(rd.modifiers)) { continue; } } if (omitPrivateFields && elems[i] instanceof FieldDecl) { if (Modifiers.isPrivate(((FieldDecl) elems[i]).modifiers)) { continue; } } v.addElement(elems[i]); //@ nowarn Pre; } } /** * Parse the file and set <code>typeDecl</code>. */ //@ also ensures typeDecl != null; protected void parse_file(DataInput stream) throws ClassFormatError, IOException { super.parse_file(stream); TypeNameVec interfaceVec = TypeNameVec.make(interfaces); //@ nowarn Pre; int predict = classMembers.size() + routines.length + fields.length; TypeDeclElemVec elementVec = TypeDeclElemVec.make(predict); elementVec.append(classMembers); // only add routines and fields that are not synthetic. this.addNonSyntheticDecls(elementVec, routines); this.addNonSyntheticDecls(elementVec, fields); //@ assume classIdentifier != null; if ((modifiers & ACC_INTERFACE) != 0) { typeDecl = (TypeDecl) InterfaceDecl.make(modifiers & ~ACC_INTERFACE, null, classIdentifier, interfaceVec, null, elementVec, classLocation, classLocation, classLocation, classLocation); } else { typeDecl = (TypeDecl) ClassDecl.make(modifiers, null, classIdentifier, interfaceVec, null, elementVec, classLocation, classLocation, classLocation, classLocation, super_class); } typeDecl.specOnly = true; } /** * Call back from ClassFileParser. */ protected void set_version(int major, int minor) throws ClassFormatError { // don't need class file version } /** * Call back from ClassFileParser. */ protected void set_num_constants(int cnum) throws ClassFormatError { constants = new Object[cnum]; rawConstants = new Object[cnum]; } /** * Call back from ClassFileParser. */ protected void set_const(int i, int ctype, Object value) throws ClassFormatError { constants[i] = ctype == CONSTANT_Class ? //@ nowarn IndexTooBig; DescriptorParser.parseClass((String) value) : value; rawConstants[i] = value; } /** * Call back from ClassFileParser. */ protected void set_const_ref(int i, int ctype, int class_index, String field_name, String type) throws ClassFormatError { // don't need ref constants } /** * Call back from ClassFileParser. */ protected void set_class_attribute(/*@non_null*/ String aname, /*@non_null*/ DataInput stream, int n) throws IOException, ClassFormatError { if (aname.equals("Synthetic")) { syntheticClass = true; } else if (!aname.equals("InnerClasses")) { super.set_class_attribute(aname, stream, n); } else { int num_classes = stream.readUnsignedShort(); for (int j = 0; j < num_classes; j++) { int inner = stream.readUnsignedShort(); //@ assume inner < constants.length; // property of class files int outer = stream.readUnsignedShort(); int name = stream.readUnsignedShort(); //@ assume name < constants.length; // property of class files int flags = stream.readUnsignedShort(); //System.out.println("PPP" + Modifiers.toString(flags)); if (outer == this_class_index && name != 0) { // We've found a member that needs to be parsed... if (!(rawConstants[name] instanceof String)) { throw new ClassFormatError("bad constant reference"); } //@ assume rawConstants[inner] instanceof String; // property of class files String nm = (String) rawConstants[inner]; int i = nm.lastIndexOf("/"); String icfn = (i < 0 ? nm : nm.substring(i + 1)) + ".class"; GenericFile icf = inputFile.getSibling(icfn); if (icf == null) { throw new IOException(icfn + ": inner class not found"); } ASTClassFileParser parser = new ASTClassFileParser(icf, true); parser.typeDecl.modifiers |= (flags & ~ACC_SYNCHRONIZED & ~ACC_INTERFACE); if (Modifiers.isPublic(parser.typeDecl.modifiers)) { parser.typeDecl.modifiers &= ~ACC_PROTECTED; } // Only add classes that are not synthetic and are not anonymous inner classes, // which are identified by names that start with a number. if (!parser.syntheticClass && !Character.isDigit(parser.typeDecl.id.toString().charAt(0))) { classMembers.addElement(parser.typeDecl); } } } } } /** * Call back from ClassFileParser. */ protected void set_modifiers(int modifiers) throws ClassFormatError { // The synchronized bit for classes is used for other purposes: this.modifiers = modifiers & ~ACC_SYNCHRONIZED; } /** * Call back from ClassFileParser. */ protected void set_this_class(int cindex) throws ClassFormatError { // record the class type and synthesize a location for the class binary TypeName typeName = (TypeName) constants[cindex]; //@ nowarn Cast, IndexTooBig; //@ assume typeName != null; Name qualifier = getNameQualifier(typeName.name); Identifier terminal = getNameTerminal(typeName.name); this_class_index = cindex; //this_class = typeName; classPackage = qualifier; classIdentifier = terminal; // This is not the correct location; it may be useful later, though. // int location = Location.createWholeFileLoc(terminal+".java"); // classLocation = location; DescriptorParser.classLocation = classLocation; } /** * Call back from ClassFileParser. */ protected void set_super_class(int cindex) throws ClassFormatError { super_class = (TypeName) constants[cindex]; //@ nowarn Cast, IndexTooBig; } /** * Call back from ClassFileParser. */ protected void set_num_interfaces(int n) throws ClassFormatError { interfaces = new TypeName[n]; } /** * Call back from ClassFileParser. */ protected void set_interface(int index, int cindex) throws ClassFormatError { interfaces[index] = (TypeName) constants[cindex]; //@ nowarn Cast,IndexTooBig; } /** * Call back from ClassFileParser. */ protected void set_num_fields(int n) throws ClassFormatError { fields = new FieldDecl[n]; } /** * Call back from ClassFileParser. */ protected void set_field(int i, String fname, String type, int mod) throws ClassFormatError { fields[i] = //@ nowarn IndexTooBig; FieldDecl.make(mod, null, Identifier.intern(fname), DescriptorParser .parseField(type), classLocation, null, classLocation); } /** * Call back from ClassFileParser. */ protected void set_field_initializer(int i, Object value) throws ClassFormatError { // construct a literal expression for the initializer FieldDecl field = fields[i]; //@ nowarn IndexTooBig; //@ assume field != null ; int tag; Object literal; switch (field.type.getTag()) { case ASTTagConstants.BOOLEANTYPE: tag = ASTTagConstants.BOOLEANLIT; literal = Boolean.valueOf(((Integer) value).intValue() != 0); //@ nowarn Cast,Null; break; case ASTTagConstants.INTTYPE: case ASTTagConstants.BYTETYPE: case ASTTagConstants.SHORTTYPE: tag = ASTTagConstants.INTLIT; literal = (Integer) value; //@ nowarn Cast; break; case ASTTagConstants.LONGTYPE: tag = ASTTagConstants.LONGLIT; literal = (Long) value; //@ nowarn Cast; break; case ASTTagConstants.CHARTYPE: tag = ASTTagConstants.CHARLIT; literal = (Integer) value; //@ nowarn Cast; break; case ASTTagConstants.FLOATTYPE: tag = ASTTagConstants.FLOATLIT; literal = (Float) value; //@ nowarn Cast; break; case ASTTagConstants.DOUBLETYPE: tag = ASTTagConstants.DOUBLELIT; literal = (Double) value; //@ nowarn Cast; break; default: tag = ASTTagConstants.STRINGLIT; literal = (String) value; //@ nowarn Cast; break; } field.init = LiteralExpr.make(tag, literal, classLocation); } /** * Call back from ClassFileParser. */ protected void set_num_methods(int n) throws ClassFormatError { routines = new RoutineDecl[n]; } /** * Call back from ClassFileParser. */ protected void set_method(int i, String mname, String sig, int mod) throws ClassFormatError { MethodSignature signature = DescriptorParser.parseMethod(sig); FormalParaDeclVec formalVec = FormalParaDeclVec .make(makeFormals(signature)); BlockStmt body = null; routines[i] = //@ nowarn IndexTooBig; mname.equals("<init>") ? (RoutineDecl) ConstructorDecl .make(mod, null, null, formalVec, emptyTypeNameVec, body, Location.NULL, classLocation, classLocation, classLocation) : (RoutineDecl) MethodDecl.make(mod, null, null, formalVec, emptyTypeNameVec, body, Location.NULL, classLocation, classLocation, classLocation, Identifier.intern(mname), signature .getReturn(), classLocation); } /** * Call back from ClassFileParser. */ protected void set_method_body(int i, int max_stack, int max_local, byte[] code, int num_handlers) throws ClassFormatError { // put in a dummy body if (!includeBodies) return; routines[i].body = //@ nowarn Null, IndexTooBig; BlockStmt.make(StmtVec.make(), classLocation, classLocation); routines[i].locOpenBrace = classLocation; } /** * Call back from ClassFileParser. */ protected void set_method_handler(int i, int j, int start_pc, int end_pc, int handler_pc, int catch_index) throws ClassFormatError { // don't need method handlers } /** * Call back from ClassFileParser. */ protected void set_method_attribute(int i, String aname, DataInput stream, int n) throws IOException, ClassFormatError { // look for the Exceptions attribute and modify the appropriate method, if // necessary if (aname.equals("Exceptions")) { routines[i].raises = TypeNameVec .make(parseTypeNames((DataInputStream) stream)); //@ nowarn Null, Cast, IndexTooBig; } else if (aname.equals("Synthetic")) { synthetics.addElement(routines[i]); //@ nowarn ; } else { stream.skipBytes(n); } } /** * The input file being parsed. */ /*@ non_null */GenericFile inputFile; /** * The constant pool of the class being parsed. * Initialized by set_num_constants. * Elements initialized by set_const and set_const_ref. * * Dynamic element types according to constant tag: * UTF8 String * String String * Class TypeName * Integer Integer * Float Float * Long Long * Double Double * FieldRef null * MethodRef null * InterfaceMethodRef null */ //@ private invariant \typeof(constants) == \type(Object[]); private /*@non_null*/Object[] constants; /** * The constant pool of the class being parsed. * This array contains the constants as they came out of the * parser (versus translated by DescriptorParser). Initialized * by set_const and set_num_constants. */ //@ private invariant \typeof(rawConstants) == \type(Object[]); //@ private invariant constants.length == rawConstants.length; private /*@non_null*/Object[] rawConstants; /** * The modifiers of the class being parsed. * Initialized by set_modifiers. */ private int modifiers; /** * The contant pool index of this class. * Initialized by set_this_class. */ private int this_class_index; /** * The type name of the class being parsed. * Initialized by set_this_class. */ //private TypeName this_class; /** * The type name of the superclass of the class being parsed. * Initialized by set_super_class. */ private TypeName super_class; /** * The type names of the interfaces implemented by the class being parsed. * Initialized by set_num_interfaces. * Elements initialized by set_interface. */ //@ private invariant \typeof(interfaces) == \type(TypeName[]); private /*@non_null*/ TypeName[] interfaces; /** * The class members of the class being parsed. * Intialized by set_field, set_method, and set_class_attributes. */ private /*@non_null*/ TypeDeclElemVec classMembers = TypeDeclElemVec.make(0); /** * The fields of the class being parsed. * Initialized by set_num_fields. * Elements initialized by set_field. */ //@ invariant \typeof(fields) == \type(FieldDecl[]); //@ spec_public private /*@non_null*/ FieldDecl[] fields; /** * The methods and constructors of the class being parsed. * Initialized by set_num_methods. * Elements initialized by set_method. */ //@ invariant \typeof(routines) == \type(RoutineDecl[]); //@ spec_public private /*@non_null*/ RoutineDecl[] routines; /** * The identifier of the class being parsed. * Initialized by set_this_class. */ //@ spec_public private Identifier classIdentifier; /** * Parse a sequence of type names from a given stream. * @param stream the stream to parse the type names from * @return an array of type names * @exception ClassFormatError if the type names are not class constants */ //@ ensures \nonnullelements(\result); //@ ensures \typeof(\result)==\type(TypeName[]); private /*@non_null*/TypeName[] parseTypeNames(/*@non_null*/DataInputStream stream) throws IOException, ClassFormatError { int count = stream.readUnsignedShort(); TypeName[] names = new TypeName[count]; for (int i = 0; i < count; i++) { int index = stream.readUnsignedShort(); if (index >= constants.length) throw new ClassFormatError("unknown constant"); Object constant = constants[index]; if (!(constant instanceof TypeName)) throw new ClassFormatError("not a class constant"); names[i] = (TypeName) constant; } return names; } /** * Construct a vector of formal parameters from a method signature. * @param signature the method signature to make the formal parameters from * @return the formal parameters */ //@ requires signature != null; //@ ensures \nonnullelements(\result); //@ ensures \typeof(\result) == \type(FormalParaDecl[]); private FormalParaDecl[] makeFormals(MethodSignature signature) { int length = signature.countParameters(); FormalParaDecl[] formals = new FormalParaDecl[length]; for (int i = 0; i < length; i++) { Identifier id = Identifier.intern("arg" + i); formals[i] = FormalParaDecl.make(0, null, id, signature.parameterAt(i), classLocation); } return formals; } /** * Return the package qualifier of a given name. * @param name the name to return the package qualifier of * @return the package qualifier of name */ //@ requires name != null; private static Name getNameQualifier(Name name) { int size = name.size(); return size > 1 ? name.prefix(size - 1) : null; // using null for the unnamed package ??? } /** * Return the terminal identifier of a given name. * @param name the name to return the terminal identifier of * @return the terminal identifier of name */ //@ requires name != null; private static Identifier getNameTerminal(Name name) { return name.identifierAt(name.size() - 1); } /** * An empty type name vector. */ //@ invariant emptyTypeNameVec != null; //@ spec_public private static final TypeNameVec emptyTypeNameVec = TypeNameVec.make(); /** * A null identifier. */ /* UNUSED //@ invariant nullIdentifier != null; private static final Identifier nullIdentifier = Identifier.intern(""); */ }
// simulate occasional problematic (long blocking) requests for disk IO import java.net.*; import java.io.*; import java.util.*; class ReadResponse { public int rc; public int bytes_read; public long elapsed_time_ms; public String file_path; public ReadResponse(int rc, int bytes_read, long elapsed_time_ms, String file_path) { this.rc = rc; this.bytes_read = bytes_read; this.elapsed_time_ms = elapsed_time_ms; this.file_path = file_path; } public void addQueueTime(long queue_time_ms) { this.elapsed_time_ms += queue_time_ms; } public String toString() { return "" + rc + "," + bytes_read + "," + elapsed_time_ms + "," + file_path; } } public class SimulatedDiskIOServer { public static int NUM_WORKER_THREADS = 5; public static int READ_TIMEOUT_SECS = 4; public static int STATUS_READ_SUCCESS = 0; public static int STATUS_READ_TIMEOUT = 1; public static int STATUS_READ_IO_FAIL = 2; public static int STATUS_QUEUE_TIMEOUT = 3; // percentage of requests that result in very long response times (many seconds) public static double PCT_LONG_IO_RESPONSE_TIMES = 0.10; // percentage of requests that result in IO failure public static double PCT_IO_FAIL = 0.001; // max size that would be read public static double MAX_READ_BYTES = 100000; // min/max values for io failure public static double MIN_TIME_FOR_IO_FAIL = 0.3; public static double MAX_TIME_FOR_IO_FAIL = 3.0; // min/max values for slow read (dying disk) public static double MIN_TIME_FOR_SLOW_IO = 6.0; public static double MAX_TIME_FOR_SLOW_IO = 20.0; // min/max values for normal io public static double MIN_TIME_FOR_NORMAL_IO = 0.075; public static double MAX_TIME_FOR_NORMAL_IO = 0.4; // maximum ADDITIONAL time above timeout experienced by requests that time out public static double MAX_TIME_ABOVE_TIMEOUT = MAX_TIME_FOR_SLOW_IO * 0.8; private static Random randomGenerator = new Random(); public static double random_value_between(double min_value, double max_value) { double rand_value = randomGenerator.nextDouble() * max_value; if (rand_value < min_value) { rand_value = min_value; } return rand_value; } public static ReadResponse simulated_file_read(String file_path, long elapsed_time_ms, int read_timeout_secs) { final long read_timeout_ms = read_timeout_secs * 1000; int num_bytes_read = 0; double rand_number = randomGenerator.nextDouble(); boolean request_with_slow_read = false; int rc; double min_response_time; double max_response_time; if (rand_number <= PCT_IO_FAIL) { // simulate read io failure rc = STATUS_READ_IO_FAIL; min_response_time = MIN_TIME_FOR_IO_FAIL; max_response_time = MAX_TIME_FOR_IO_FAIL; } else { rc = STATUS_READ_SUCCESS; if (rand_number <= PCT_LONG_IO_RESPONSE_TIMES) { // simulate very slow request request_with_slow_read = true; min_response_time = MIN_TIME_FOR_SLOW_IO; max_response_time = MAX_TIME_FOR_SLOW_IO; } else { // simulate typical read response time min_response_time = MIN_TIME_FOR_NORMAL_IO; max_response_time = MAX_TIME_FOR_NORMAL_IO; } num_bytes_read = (int) (randomGenerator.nextDouble() * MAX_READ_BYTES); } // do we need to generate the response time? (i.e., not predetermined) if (-1 == elapsed_time_ms) { elapsed_time_ms = (long) (1000.0 * random_value_between(min_response_time, max_response_time)); if (elapsed_time_ms > read_timeout_ms && !request_with_slow_read) { rc = STATUS_READ_TIMEOUT; elapsed_time_ms = (long) (1000.0 * random_value_between(0, MAX_TIME_ABOVE_TIMEOUT)); num_bytes_read = 0; } } try { Thread.sleep(elapsed_time_ms); } catch (InterruptedException ignored) { } if (rc == STATUS_READ_TIMEOUT) { System.out.println("timeout (assigned)"); } else if (rc == STATUS_READ_IO_FAIL) { System.out.println("io fail"); } else if (rc == STATUS_READ_SUCCESS) { // what would otherwise have been a successful read turns into a // timeout error if simulated execution time exceeds timeout value if (elapsed_time_ms > read_timeout_ms) { //TODO: it would be nice to increment a counter here and show // the counter value as part of print System.out.println("timeout (service)"); rc = STATUS_READ_TIMEOUT; num_bytes_read = 0; } } return new ReadResponse(rc, num_bytes_read, elapsed_time_ms, file_path); } public static void handle_socket_request(Socket sock, long receipt_timestamp) { BufferedReader reader = null; BufferedWriter writer = null; try { reader = new BufferedReader(new InputStreamReader(sock.getInputStream())); writer = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream())); // read request from client String request_text = reader.readLine(); // did we get anything from client? if ((request_text != null) && (request_text.length() > 0)) { // determine how long the request has waited in queue final long start_processing_timestamp = System.currentTimeMillis(); final long queue_time_ms = start_processing_timestamp - receipt_timestamp; final int queue_time_secs = (int) (queue_time_ms / 1000); // unless otherwise specified, let server generate // the response time long predetermined_response_time_ms = -1; String file_path; // look for field delimiter in request int pos_field_delimiter = request_text.indexOf(","); if (pos_field_delimiter > -1) { file_path = request_text.substring(pos_field_delimiter + 1); final int num_digits = pos_field_delimiter; if ((num_digits > 0) && (num_digits < 10)) { String req_time_digits = request_text.substring(0, pos_field_delimiter); final long req_response_time_ms = Long.parseLong(req_time_digits); if (req_response_time_ms > 0) { predetermined_response_time_ms = req_response_time_ms; } } } else { file_path = request_text; } ReadResponse read_resp; // has this request already timed out? if (queue_time_secs >= READ_TIMEOUT_SECS) { System.out.println("timeout (queue)"); read_resp = new ReadResponse(STATUS_QUEUE_TIMEOUT, 0, // bytes read 0, // elapsed time ms file_path); } else { read_resp = simulated_file_read(file_path, predetermined_response_time_ms, READ_TIMEOUT_SECS); } // total request time is sum of time spent in queue and the // simulated disk read time read_resp.addQueueTime(queue_time_ms); // return response text to client writer.write(read_resp.toString() + "\n"); writer.flush(); } } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException ignored) { } } if (writer != null) { try { writer.close(); } catch (IOException ignored) { } } // close client socket connection try { sock.close(); } catch (IOException ignored) { } } } public static void main(String[] args) { int server_port = 6000; try { ServerSocket server_socket = new ServerSocket(server_port); System.out.println("server listening on port " + server_port); while (true) { try { final Socket sock = server_socket.accept(); if (sock != null) { final long receipt_timestamp = System.currentTimeMillis(); new Thread(new Runnable() { @Override public void run() { handle_socket_request(sock, receipt_timestamp); } }).start(); } } catch (IOException ignored) { } } } catch (IOException e) { System.out.println("error: unable to create server socket on port " + server_port); } } }
package com.artifex.mupdf; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.RectF; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.text.method.PasswordTransformationMethod; import android.view.MotionEvent; import android.view.ScaleGestureDetector; import android.view.View; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.RelativeLayout; import android.widget.SeekBar; import android.widget.TextView; import android.widget.ViewSwitcher; class SearchTaskResult { public final int pageNumber; public final RectF searchBoxes[]; SearchTaskResult(int _pageNumber, RectF _searchBoxes[]) { pageNumber = _pageNumber; searchBoxes = _searchBoxes; } } public class MuPDFActivity extends Activity { /* The core rendering instance */ private final int TAP_PAGE_MARGIN = 5; private MuPDFCore core; private String mFileName; private ReaderView mDocView; private View mButtonsView; private boolean mButtonsVisible; private EditText mPasswordView; private TextView mFilenameView; private SeekBar mPageSlider; private TextView mPageNumberView; private ImageButton mSearchButton; private Button mCancelButton; private ImageButton mOutlineButton; private ViewSwitcher mTopBarSwitcher; private boolean mTopBarIsSearch; private ImageButton mSearchBack; private ImageButton mSearchFwd; private EditText mSearchText; private AsyncTask<Integer,Void,SearchTaskResult> mSearchTask; private SearchTaskResult mSearchTaskResult; private AlertDialog.Builder mAlertBuilder; private MuPDFCore openFile(String path) { int lastSlashPos = path.lastIndexOf('/'); mFileName = new String(lastSlashPos == -1 ? path : path.substring(lastSlashPos+1)); System.out.println("Trying to open "+path); try { core = new MuPDFCore(path); // New file: drop the old outline data OutlineActivityData.set(null); } catch (Exception e) { System.out.println(e); return null; } return core; } /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mAlertBuilder = new AlertDialog.Builder(this); if (core == null) { core = (MuPDFCore)getLastNonConfigurationInstance(); if (savedInstanceState != null && savedInstanceState.containsKey("FileName")) { mFileName = savedInstanceState.getString("FileName"); } } if (core == null) { Intent intent = getIntent(); if (Intent.ACTION_VIEW.equals(intent.getAction())) core = openFile(Uri.decode(intent.getData().getEncodedPath())); if (core != null && core.needsPassword()) { requestPassword(savedInstanceState); return; } } if (core == null) { AlertDialog alert = mAlertBuilder.create(); alert.setTitle(R.string.open_failed); alert.setButton(AlertDialog.BUTTON_POSITIVE, "Dismiss", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }); alert.show(); return; } createUI(savedInstanceState); } public void requestPassword(final Bundle savedInstanceState) { mPasswordView = new EditText(this); mPasswordView.setInputType(EditorInfo.TYPE_TEXT_VARIATION_PASSWORD); mPasswordView.setTransformationMethod(new PasswordTransformationMethod()); AlertDialog alert = mAlertBuilder.create(); alert.setTitle(R.string.enter_password); alert.setView(mPasswordView); alert.setButton(AlertDialog.BUTTON_POSITIVE, "Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (core.authenticatePassword(mPasswordView.getText().toString())) { createUI(savedInstanceState); } else { requestPassword(savedInstanceState); } } }); alert.setButton(AlertDialog.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }); alert.show(); } public void createUI(Bundle savedInstanceState) { // Now create the UI. // First create the document view making use of the ReaderView's internal // gesture recognition mDocView = new ReaderView(this) { private boolean showButtonsDisabled; public boolean onSingleTapUp(MotionEvent e) { if (e.getX() < super.getWidth()/TAP_PAGE_MARGIN) { super.moveToPrevious(); } else if (e.getX() > super.getWidth()*(TAP_PAGE_MARGIN-1)/TAP_PAGE_MARGIN) { super.moveToNext(); } else if (!showButtonsDisabled) { int linkPage = -1; MuPDFPageView pageView = (MuPDFPageView) mDocView.getDisplayedView(); if (pageView != null) { linkPage = pageView.hitLinkPage(e.getX(), e.getY()); } if (linkPage != -1) { mDocView.setDisplayedViewIndex(linkPage); } else { if (!mButtonsVisible) { showButtons(); } else { hideButtons(); } } } return super.onSingleTapUp(e); } public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { if (!showButtonsDisabled) hideButtons(); return super.onScroll(e1, e2, distanceX, distanceY); } public boolean onScaleBegin(ScaleGestureDetector d) { // Disabled showing the buttons until next touch. // Not sure why this is needed, but without it // pinch zoom can make the buttons appear showButtonsDisabled = true; return super.onScaleBegin(d); } public boolean onTouchEvent(MotionEvent event) { if (event.getActionMasked() == MotionEvent.ACTION_DOWN) showButtonsDisabled = false; return super.onTouchEvent(event); } protected void onChildSetup(int i, View v) { if (mSearchTaskResult != null && mSearchTaskResult.pageNumber == i) ((PageView)v).setSearchBoxes(mSearchTaskResult.searchBoxes); else ((PageView)v).setSearchBoxes(null); } protected void onMoveToChild(int i) { mPageNumberView.setText(String.format("%d/%d", i+1, core.countPages())); mPageSlider.setMax(core.countPages()-1); mPageSlider.setProgress(i); if (mSearchTaskResult != null && mSearchTaskResult.pageNumber != i) { mSearchTaskResult = null; mDocView.resetupChildren(); } } protected void onSettle(View v) { // When the layout has settled ask the page to render // in HQ ((PageView)v).addHq(); } protected void onUnsettle(View v) { // When something changes making the previous settled view // no longer appropriate, tell the page to remove HQ ((PageView)v).removeHq(); } }; mDocView.setAdapter(new MuPDFPageAdapter(this, core)); mDocView.setBackgroundResource(R.drawable.tiled_background); // Make the buttons overlay, and store all its // controls in variables makeButtonsView(); // Set the file-name text mFilenameView.setText(mFileName); // Activate the seekbar mPageSlider.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { public void onStopTrackingTouch(SeekBar seekBar) { mDocView.setDisplayedViewIndex(seekBar.getProgress()); } public void onStartTrackingTouch(SeekBar seekBar) {} public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { updatePageNumView(progress); } }); // Activate the search-preparing button mSearchButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { searchModeOn(); } }); mCancelButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { searchModeOff(); } }); // Search invoking buttons are disabled while there is no text specified mSearchBack.setEnabled(false); mSearchFwd.setEnabled(false); // React to interaction with the text widget mSearchText.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable s) { boolean haveText = s.toString().length() > 0; mSearchBack.setEnabled(haveText); mSearchFwd.setEnabled(haveText); } public void beforeTextChanged(CharSequence s, int start, int count, int after) {} public void onTextChanged(CharSequence s, int start, int before, int count) {} }); // Activate search invoking buttons mSearchBack.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { hideKeyboard(); search(-1); } }); mSearchFwd.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { hideKeyboard(); search(1); } }); if (core.hasOutline()) { mOutlineButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { OutlineItem outline[] = core.getOutline(); if (outline != null) { OutlineActivityData.get().items = outline; Intent intent = new Intent(MuPDFActivity.this, OutlineActivity.class); startActivityForResult(intent, 0); } } }); } else { mOutlineButton.setVisibility(View.GONE); } // Reenstate last state if it was recorded SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE); mDocView.setDisplayedViewIndex(prefs.getInt("page"+mFileName, 0)); if (savedInstanceState == null || !savedInstanceState.getBoolean("ButtonsHidden", false)) showButtons(); if(savedInstanceState != null && savedInstanceState.getBoolean("SearchMode", false)) searchModeOn(); // Stick the document view and the buttons overlay into a parent view RelativeLayout layout = new RelativeLayout(this); layout.addView(mDocView); layout.addView(mButtonsView); setContentView(layout); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode >= 0) mDocView.setDisplayedViewIndex(resultCode); super.onActivityResult(requestCode, resultCode, data); } public Object onRetainNonConfigurationInstance() { MuPDFCore mycore = core; core = null; return mycore; } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mFileName != null && mDocView != null) { outState.putString("FileName", mFileName); // Store current page in the prefs against the file name, // so that we can pick it up each time the file is loaded // Other info is needed only for screen-orientation change, // so it can go in the bundle SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE); SharedPreferences.Editor edit = prefs.edit(); edit.putInt("page"+mFileName, mDocView.getDisplayedViewIndex()); edit.commit(); } if (!mButtonsVisible) outState.putBoolean("ButtonsHidden", true); if (mTopBarIsSearch) outState.putBoolean("SearchMode", true); } @Override protected void onPause() { super.onPause(); if (mFileName != null && mDocView != null) { SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE); SharedPreferences.Editor edit = prefs.edit(); edit.putInt("page"+mFileName, mDocView.getDisplayedViewIndex()); edit.commit(); } } public void onDestroy() { if (core != null) core.onDestroy(); core = null; super.onDestroy(); } void showButtons() { if (!mButtonsVisible) { mButtonsVisible = true; // Update page number text and slider int index = mDocView.getDisplayedViewIndex(); updatePageNumView(index); mPageSlider.setMax(core.countPages()-1); mPageSlider.setProgress(index); if (mTopBarIsSearch) { mSearchText.requestFocus(); showKeyboard(); } Animation anim = AnimationUtils.loadAnimation(this, R.anim.fade_in); anim.setAnimationListener(new Animation.AnimationListener() { public void onAnimationStart(Animation animation) { mButtonsView.setVisibility(View.VISIBLE); } public void onAnimationRepeat(Animation animation) {} public void onAnimationEnd(Animation animation) {} }); mButtonsView.startAnimation(anim); } } void hideButtons() { if (mButtonsVisible) { mButtonsVisible = false; hideKeyboard(); Animation anim = AnimationUtils.loadAnimation(this, R.anim.fade_out); anim.setAnimationListener(new Animation.AnimationListener() { public void onAnimationStart(Animation animation) {} public void onAnimationRepeat(Animation animation) {} public void onAnimationEnd(Animation animation) { mButtonsView.setVisibility(View.INVISIBLE); } }); mButtonsView.startAnimation(anim); } } void searchModeOn() { mTopBarIsSearch = true; //Focus on EditTextWidget mSearchText.requestFocus(); showKeyboard(); mTopBarSwitcher.showNext(); } void searchModeOff() { mTopBarIsSearch = false; hideKeyboard(); mTopBarSwitcher.showPrevious(); mSearchTaskResult = null; // Make the ReaderView act on the change to mSearchTaskResult // via overridden onChildSetup method. mDocView.resetupChildren(); } void updatePageNumView(int index) { mPageNumberView.setText(String.format("%d/%d", index+1, core.countPages())); } void makeButtonsView() { mButtonsView = getLayoutInflater().inflate(R.layout.buttons,null); mButtonsView.setVisibility(View.INVISIBLE); mFilenameView = (TextView)mButtonsView.findViewById(R.id.docNameText); mPageSlider = (SeekBar)mButtonsView.findViewById(R.id.pageSlider); mPageNumberView = (TextView)mButtonsView.findViewById(R.id.pageNumber); mSearchButton = (ImageButton)mButtonsView.findViewById(R.id.searchButton); mCancelButton = (Button)mButtonsView.findViewById(R.id.cancel); mOutlineButton = (ImageButton)mButtonsView.findViewById(R.id.outlineButton); mTopBarSwitcher = (ViewSwitcher)mButtonsView.findViewById(R.id.switcher); mSearchBack = (ImageButton)mButtonsView.findViewById(R.id.searchBack); mSearchFwd = (ImageButton)mButtonsView.findViewById(R.id.searchForward); mSearchText = (EditText)mButtonsView.findViewById(R.id.searchText); } void showKeyboard() { InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); if (imm != null) imm.showSoftInput(mSearchText, 0); } void hideKeyboard() { InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); if (imm != null) imm.hideSoftInputFromWindow(mSearchText.getWindowToken(), 0); } void search(int direction) { if (mSearchTask != null) { mSearchTask.cancel(true); mSearchTask = null; } mSearchTask = new AsyncTask<Integer,Void,SearchTaskResult>() { @Override protected SearchTaskResult doInBackground(Integer... params) { int index; if (mSearchTaskResult == null) index = mDocView.getDisplayedViewIndex(); else index = mSearchTaskResult.pageNumber + params[0].intValue(); while (0 <= index && index < core.countPages()) { RectF searchHits[] = core.searchPage(index, mSearchText.getText().toString()); if (searchHits != null && searchHits.length > 0) return new SearchTaskResult(index, searchHits); index += params[0].intValue(); } return null; } @Override protected void onPostExecute(SearchTaskResult result) { if (result != null) { // Ask the ReaderView to move to the resulting page mDocView.setDisplayedViewIndex(result.pageNumber); mSearchTaskResult = result; // Make the ReaderView act on the change to mSearchTaskResult // via overridden onChildSetup method. mDocView.resetupChildren(); } else { mAlertBuilder.setTitle("Text not found"); AlertDialog alert = mAlertBuilder.create(); alert.setButton(AlertDialog.BUTTON_POSITIVE, "Dismiss", (DialogInterface.OnClickListener)null); alert.show(); } } }; mSearchTask.execute(new Integer(direction)); } }
package com.mapswithme.maps; import android.annotation.SuppressLint; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Configuration; import android.graphics.Rect; import android.location.Location; import android.os.Build; import android.os.Bundle; import android.support.annotation.CallSuper; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.StyleRes; import android.support.v4.app.DialogFragment; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v7.app.AlertDialog; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.ImageButton; import android.widget.Toast; import com.mapswithme.maps.Framework.MapObjectListener; import com.mapswithme.maps.activity.CustomNavigateUpListener; import com.mapswithme.maps.ads.LikesManager; import com.mapswithme.maps.api.ParsedMwmRequest; import com.mapswithme.maps.api.ParsedRoutingData; import com.mapswithme.maps.api.ParsedSearchRequest; import com.mapswithme.maps.api.ParsedUrlMwmRequest; import com.mapswithme.maps.api.RoutePoint; import com.mapswithme.maps.base.BaseMwmFragmentActivity; import com.mapswithme.maps.base.OnBackPressListener; import com.mapswithme.maps.bookmarks.BookmarkCategoriesActivity; import com.mapswithme.maps.bookmarks.data.BookmarkManager; import com.mapswithme.maps.bookmarks.data.MapObject; import com.mapswithme.maps.downloader.DownloaderActivity; import com.mapswithme.maps.downloader.DownloaderFragment; import com.mapswithme.maps.downloader.MapManager; import com.mapswithme.maps.downloader.MigrationFragment; import com.mapswithme.maps.downloader.OnmapDownloader; import com.mapswithme.maps.editor.AuthDialogFragment; import com.mapswithme.maps.editor.Editor; import com.mapswithme.maps.editor.EditorActivity; import com.mapswithme.maps.editor.EditorHostFragment; import com.mapswithme.maps.editor.FeatureCategoryActivity; import com.mapswithme.maps.editor.ReportFragment; import com.mapswithme.maps.location.CompassData; import com.mapswithme.maps.location.LocationHelper; import com.mapswithme.maps.routing.NavigationController; import com.mapswithme.maps.routing.RoutingController; import com.mapswithme.maps.routing.RoutingPlanFragment; import com.mapswithme.maps.routing.RoutingPlanInplaceController; import com.mapswithme.maps.search.FloatingSearchToolbarController; import com.mapswithme.maps.search.HotelsFilter; import com.mapswithme.maps.search.HotelsFilterView; import com.mapswithme.maps.search.NativeSearchListener; import com.mapswithme.maps.search.SearchActivity; import com.mapswithme.maps.search.SearchEngine; import com.mapswithme.maps.search.SearchFilterController; import com.mapswithme.maps.search.SearchFragment; import com.mapswithme.maps.search.SearchResult; import com.mapswithme.maps.settings.SettingsActivity; import com.mapswithme.maps.settings.StoragePathManager; import com.mapswithme.maps.settings.UnitLocale; import com.mapswithme.maps.sound.TtsPlayer; import com.mapswithme.maps.taxi.TaxiInfo; import com.mapswithme.maps.taxi.TaxiManager; import com.mapswithme.maps.traffic.TrafficManager; import com.mapswithme.maps.traffic.widget.TrafficButton; import com.mapswithme.maps.traffic.widget.TrafficButtonController; import com.mapswithme.maps.widget.FadeView; import com.mapswithme.maps.widget.menu.BaseMenu; import com.mapswithme.maps.widget.menu.MainMenu; import com.mapswithme.maps.widget.menu.MyPositionButton; import com.mapswithme.maps.widget.placepage.BasePlacePageAnimationController; import com.mapswithme.maps.widget.placepage.PlacePageView; import com.mapswithme.maps.widget.placepage.PlacePageView.State; import com.mapswithme.util.Animations; import com.mapswithme.util.BottomSheetHelper; import com.mapswithme.util.Counters; import com.mapswithme.util.InputUtils; import com.mapswithme.util.PermissionsUtils; import com.mapswithme.util.ThemeSwitcher; import com.mapswithme.util.ThemeUtils; import com.mapswithme.util.UiUtils; import com.mapswithme.util.Utils; import com.mapswithme.util.concurrency.UiThread; import com.mapswithme.util.permissions.PermissionsResult; import com.mapswithme.util.sharing.ShareOption; import com.mapswithme.util.sharing.SharingHelper; import com.mapswithme.util.statistics.AlohaHelper; import com.mapswithme.util.statistics.Statistics; import java.io.Serializable; import java.util.Locale; import java.util.Stack; public class MwmActivity extends BaseMwmFragmentActivity implements MapObjectListener, View.OnTouchListener, BasePlacePageAnimationController.OnVisibilityChangedListener, BasePlacePageAnimationController.OnAnimationListener, OnClickListener, MapFragment.MapRenderingListener, CustomNavigateUpListener, RoutingController.Container, LocationHelper.UiCallback, FloatingSearchToolbarController.VisibilityListener, NativeSearchListener, NavigationButtonsAnimationController.OnTranslationChangedListener, RoutingPlanInplaceController.RoutingPlanListener { public static final String EXTRA_TASK = "map_task"; public static final String EXTRA_LAUNCH_BY_DEEP_LINK = "launch_by_deep_link"; private static final String EXTRA_CONSUMED = "mwm.extra.intent.processed"; private static final String EXTRA_UPDATE_COUNTRIES = ".extra.update.countries"; private static final String[] DOCKED_FRAGMENTS = { SearchFragment.class.getName(), DownloaderFragment.class.getName(), MigrationFragment.class.getName(), RoutingPlanFragment.class.getName(), EditorHostFragment.class.getName(), ReportFragment.class.getName() }; // Instance state private static final String STATE_PP = "PpState"; private static final String STATE_MAP_OBJECT = "MapObject"; private static final String EXTRA_LOCATION_DIALOG_IS_ANNOYING = "LOCATION_DIALOG_IS_ANNOYING"; private static final int LOCATION_REQUEST = 1; // Map tasks that we run AFTER rendering initialized private final Stack<MapTask> mTasks = new Stack<>(); private final StoragePathManager mPathManager = new StoragePathManager(); @Nullable private MapFragment mMapFragment; @Nullable private PlacePageView mPlacePage; private RoutingPlanInplaceController mRoutingPlanInplaceController; @Nullable private NavigationController mNavigationController; private MainMenu mMainMenu; private PanelAnimator mPanelAnimator; @Nullable private OnmapDownloader mOnmapDownloader; private FadeView mFadeView; @Nullable private MyPositionButton mNavMyPosition; private TrafficButton mTraffic; @Nullable private NavigationButtonsAnimationController mNavAnimationController; @Nullable private TrafficButtonController mTrafficButtonController; private View mPositionChooser; private ViewGroup mRootView; @Nullable private SearchFilterController mFilterController; private boolean mIsFragmentContainer; private boolean mIsFullscreen; private boolean mIsFullscreenAnimating; private boolean mIsAppearMenuLater; private boolean mIsLaunchByDeepLink; private FloatingSearchToolbarController mSearchController; private boolean mPlacePageRestored; private boolean mLocationErrorDialogAnnoying = false; @Nullable private Dialog mLocationErrorDialog; private boolean mRestoreRoutingPlanFragmentNeeded; @Nullable private Bundle mSavedForTabletState; @NonNull private final OnClickListener mOnMyPositionClickListener = new OnClickListener() { @Override public void onClick(View v) { Statistics.INSTANCE.trackEvent(Statistics.EventName.TOOLBAR_MY_POSITION); AlohaHelper.logClick(AlohaHelper.TOOLBAR_MY_POSITION); if (!PermissionsUtils.isLocationGranted()) { if (PermissionsUtils.isLocationExplanationNeeded(MwmActivity.this)) PermissionsUtils.requestLocationPermission(MwmActivity.this, LOCATION_REQUEST); else Toast.makeText(MwmActivity.this, R.string.enable_location_services, Toast.LENGTH_SHORT) .show(); return; } myPositionClick(); } }; public interface LeftAnimationTrackListener { void onTrackStarted(boolean collapsed); void onTrackFinished(boolean collapsed); void onTrackLeftAnimation(float offset); } public interface VisibleRectListener { void onVisibleRectChanged(Rect rect); } class VisibleRectMeasurer implements View.OnLayoutChangeListener { private VisibleRectListener m_listener; private Rect mScreenFullRect = null; private Rect mLastVisibleRect = null; private boolean mPlacePageVisible = false; public VisibleRectMeasurer(VisibleRectListener listener) { m_listener = listener; } void setPlacePageVisible(boolean visible) { int orientation = MwmActivity.this.getResources().getConfiguration().orientation; if(orientation == Configuration.ORIENTATION_LANDSCAPE) { mPlacePageVisible = visible; recalculateVisibleRect(mScreenFullRect); } } void setPreviewVisible(boolean visible) { int orientation = MwmActivity.this.getResources().getConfiguration().orientation; if(orientation == Configuration.ORIENTATION_PORTRAIT) { mPlacePageVisible = visible; recalculateVisibleRect(mScreenFullRect); } } @Override public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { mScreenFullRect = new Rect(left, top, right, bottom); if (mPlacePageVisible && (mPlacePage == null || UiUtils.isHidden(mPlacePage.GetPreview()))) mPlacePageVisible = false; recalculateVisibleRect(mScreenFullRect); } private void recalculateVisibleRect(Rect r) { if (r == null) return; int orientation = MwmActivity.this.getResources().getConfiguration().orientation; Rect rect = new Rect(r.left, r.top, r.right, r.bottom); if (mPlacePage != null && mPlacePageVisible) { int[] loc = new int[2]; mPlacePage.GetPreview().getLocationOnScreen(loc); if(orientation == Configuration.ORIENTATION_PORTRAIT) rect.bottom = loc[1]; else rect.left = mPlacePage.GetPreview().getWidth() + loc[0]; } if (mLastVisibleRect == null || !mLastVisibleRect.equals(rect)) { mLastVisibleRect = new Rect(rect.left, rect.top, rect.right, rect.bottom); if (m_listener != null) m_listener.onVisibleRectChanged(rect); } } } private VisibleRectMeasurer mVisibleRectMeasurer; public static Intent createShowMapIntent(Context context, String countryId, boolean doAutoDownload) { return new Intent(context, DownloadResourcesActivity.class) .putExtra(DownloadResourcesActivity.EXTRA_COUNTRY, countryId) .putExtra(DownloadResourcesActivity.EXTRA_AUTODOWNLOAD, doAutoDownload); } public static Intent createUpdateMapsIntent() { return new Intent(MwmApplication.get(), MwmActivity.class) .putExtra(EXTRA_UPDATE_COUNTRIES, true); } @Override public void onRenderingInitialized() { checkMeasurementSystem(); checkKitkatMigrationMove(); LocationHelper.INSTANCE.attach(this); runTasks(); } @Override public void onRenderingRestored() { runTasks(); } private void myPositionClick() { mLocationErrorDialogAnnoying = false; LocationHelper.INSTANCE.switchToNextMode(); LocationHelper.INSTANCE.restart(); } private void runTasks() { while (!mTasks.isEmpty()) mTasks.pop().run(this); } private static void checkMeasurementSystem() { UnitLocale.initializeCurrentUnits(); } private void checkKitkatMigrationMove() { mPathManager.checkKitkatMigration(this); } @Override protected int getFragmentContentResId() { return (mIsFragmentContainer ? R.id.fragment_container : super.getFragmentContentResId()); } @Nullable Fragment getFragment(Class<? extends Fragment> clazz) { if (!mIsFragmentContainer) throw new IllegalStateException("Must be called for tablets only!"); return getSupportFragmentManager().findFragmentByTag(clazz.getName()); } void replaceFragmentInternal(Class<? extends Fragment> fragmentClass, Bundle args) { super.replaceFragment(fragmentClass, args, null); } @Override public void replaceFragment(@NonNull Class<? extends Fragment> fragmentClass, @Nullable Bundle args, @Nullable Runnable completionListener) { if (mPanelAnimator.isVisible() && getFragment(fragmentClass) != null) { if (completionListener != null) completionListener.run(); return; } mPanelAnimator.show(fragmentClass, args, completionListener); } public boolean containsFragment(@NonNull Class<? extends Fragment> fragmentClass) { return mIsFragmentContainer && getFragment(fragmentClass) != null; } private void showBookmarks() { startActivity(new Intent(this, BookmarkCategoriesActivity.class)); } public void showSearch(String query) { if (mIsFragmentContainer) { mSearchController.hide(); final Bundle args = new Bundle(); args.putString(SearchActivity.EXTRA_QUERY, query); if (mFilterController != null) args.putParcelable(SearchActivity.EXTRA_HOTELS_FILTER, mFilterController.getFilter()); replaceFragment(SearchFragment.class, args, null); } else { SearchActivity.start(this, query, mFilterController != null ? mFilterController.getFilter() : null); } } public void showEditor() { // TODO(yunikkk) think about refactoring. It probably should be called in editor. Editor.nativeStartEdit(); Statistics.INSTANCE.trackEditorLaunch(false); if (mIsFragmentContainer) replaceFragment(EditorHostFragment.class, null, null); else EditorActivity.start(this); } private void shareMyLocation() { final Location loc = LocationHelper.INSTANCE.getSavedLocation(); if (loc != null) { final String geoUrl = Framework.nativeGetGe0Url(loc.getLatitude(), loc.getLongitude(), Framework.nativeGetDrawScale(), ""); final String httpUrl = Framework.getHttpGe0Url(loc.getLatitude(), loc.getLongitude(), Framework.nativeGetDrawScale(), ""); final String body = getString(R.string.my_position_share_sms, geoUrl, httpUrl); ShareOption.ANY.share(this, body); return; } new AlertDialog.Builder(MwmActivity.this) .setMessage(R.string.unknown_current_position) .setCancelable(true) .setPositiveButton(android.R.string.ok, null) .show(); } @Override public void showDownloader(boolean openDownloaded) { if (RoutingController.get().checkMigration(this)) return; final Bundle args = new Bundle(); args.putBoolean(DownloaderActivity.EXTRA_OPEN_DOWNLOADED, openDownloaded); if (mIsFragmentContainer) { SearchEngine.cancelSearch(); mSearchController.refreshToolbar(); replaceFragment(MapManager.nativeIsLegacyMode() ? MigrationFragment.class : DownloaderFragment.class, args, null); } else { startActivity(new Intent(this, DownloaderActivity.class).putExtras(args)); } } @Override @StyleRes public int getThemeResourceId(@NonNull String theme) { if (ThemeUtils.isDefaultTheme(theme)) return R.style.MwmTheme_MainActivity; if (ThemeUtils.isNightTheme(theme)) return R.style.MwmTheme_Night_MainActivity; return super.getThemeResourceId(theme); } @SuppressLint("InlinedApi") @CallSuper @Override protected void safeOnCreate(@Nullable Bundle savedInstanceState) { super.safeOnCreate(savedInstanceState); if (savedInstanceState != null) mLocationErrorDialogAnnoying = savedInstanceState.getBoolean(EXTRA_LOCATION_DIALOG_IS_ANNOYING); mIsFragmentContainer = getResources().getBoolean(R.bool.tabletLayout); if (!mIsFragmentContainer && (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)) getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); setContentView(R.layout.activity_map); mIsLaunchByDeepLink = getIntent().getBooleanExtra(EXTRA_LAUNCH_BY_DEEP_LINK, false); initViews(); Statistics.INSTANCE.trackConnectionState(); Framework.nativeSetMapObjectListener(this); mSearchController = new FloatingSearchToolbarController(this); mSearchController.setVisibilityListener(this); processIntent(getIntent()); SharingHelper.prepare(); SearchEngine.INSTANCE.addListener(this); //TODO: uncomment after correct visible rect calculation. //mVisibleRectMeasurer = new VisibleRectMeasurer(new VisibleRectListener() { // @Override // public void onVisibleRectChanged(Rect rect) { // Framework.nativeSetVisibleRect(rect.left, rect.top, rect.right, rect.bottom); //getWindow().getDecorView().addOnLayoutChangeListener(mVisibleRectMeasurer); } private void initViews() { initMap(); initNavigationButtons(); mPlacePage = (PlacePageView) findViewById(R.id.info_box); if (mPlacePage != null) { mPlacePage.setOnVisibilityChangedListener(this); mPlacePage.setOnAnimationListener(this); } if (!mIsFragmentContainer) { mRoutingPlanInplaceController = new RoutingPlanInplaceController(this, this); removeCurrentFragment(false); } mNavigationController = new NavigationController(this); initMainMenu(); initOnmapDownloader(); initPositionChooser(); initFilterViews(); } private void initFilterViews() { HotelsFilterView hotelsFilterView = (HotelsFilterView) findViewById(R.id.hotels_filter); View frame = findViewById(R.id.filter_frame); if (frame != null && hotelsFilterView != null) { mFilterController = new SearchFilterController( frame, hotelsFilterView, new SearchFilterController.DefaultFilterListener() { @Override public void onViewClick() { showSearch(mSearchController.getQuery()); } @Override public void onFilterClear() { runSearch(); } @Override public void onFilterDone() { runSearch(); } }, R.string.search_in_table); } } private void runSearch() { SearchEngine.searchInteractive(mSearchController.getQuery(), System.nanoTime(), false /* isMapAndTable */, mFilterController != null ? mFilterController.getFilter() : null); SearchEngine.showAllResults(mSearchController.getQuery()); } private void initPositionChooser() { mPositionChooser = findViewById(R.id.position_chooser); if (mPositionChooser == null) return; final Toolbar toolbar = (Toolbar) mPositionChooser.findViewById(R.id.toolbar_position_chooser); UiUtils.extendViewWithStatusBar(toolbar); UiUtils.showHomeUpButton(toolbar); toolbar.setNavigationOnClickListener(new OnClickListener() { @Override public void onClick(View v) { hidePositionChooser(); } }); mPositionChooser.findViewById(R.id.done).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Statistics.INSTANCE.trackEditorLaunch(true); hidePositionChooser(); if (Framework.nativeIsDownloadedMapAtScreenCenter()) startActivity(new Intent(MwmActivity.this, FeatureCategoryActivity.class)); else UiUtils.showAlertDialog(MwmActivity.this, R.string.message_invalid_feature_position); } }); UiUtils.hide(mPositionChooser); } public void showPositionChooser(boolean isBusiness, boolean applyPosition) { UiUtils.show(mPositionChooser); setFullscreen(true); Framework.nativeTurnOnChoosePositionMode(isBusiness, applyPosition); closePlacePage(); mSearchController.hide(); } private void hidePositionChooser() { UiUtils.hide(mPositionChooser); Framework.nativeTurnOffChoosePositionMode(); setFullscreen(false); } private void initMap() { mFadeView = (FadeView) findViewById(R.id.fade_view); mFadeView.setListener(new FadeView.Listener() { @Override public boolean onTouch() { return getCurrentMenu().close(true); } }); mMapFragment = (MapFragment) getSupportFragmentManager().findFragmentByTag(MapFragment.class.getName()); if (mMapFragment == null) { Bundle args = new Bundle(); args.putBoolean(MapFragment.ARG_LAUNCH_BY_DEEP_LINK, mIsLaunchByDeepLink); mMapFragment = (MapFragment) MapFragment.instantiate(this, MapFragment.class.getName(), args); getSupportFragmentManager() .beginTransaction() .replace(R.id.map_fragment_container, mMapFragment, MapFragment.class.getName()) .commit(); } View container = findViewById(R.id.map_fragment_container); if (container != null) { container.setOnTouchListener(this); mRootView = (ViewGroup) container.getParent(); } } public boolean isMapAttached() { return mMapFragment != null && mMapFragment.isAdded(); } private void initNavigationButtons() { View frame = findViewById(R.id.navigation_buttons); if (frame == null) return; View zoomIn = frame.findViewById(R.id.nav_zoom_in); zoomIn.setOnClickListener(this); View zoomOut = frame.findViewById(R.id.nav_zoom_out); zoomOut.setOnClickListener(this); View myPosition = frame.findViewById(R.id.my_position); mNavMyPosition = new MyPositionButton(myPosition, mOnMyPositionClickListener); ImageButton traffic = (ImageButton) frame.findViewById(R.id.traffic); mTraffic = new TrafficButton(this, traffic); mTrafficButtonController = new TrafficButtonController(mTraffic, this); mNavAnimationController = new NavigationButtonsAnimationController( zoomIn, zoomOut, myPosition, getWindow().getDecorView().getRootView(), this); } public boolean closePlacePage() { if (mPlacePage == null || mPlacePage.isHidden()) return false; mPlacePage.hide(); Framework.nativeDeactivatePopup(); return true; } public boolean closeSidePanel() { if (interceptBackPress()) return true; if (removeCurrentFragment(true)) { InputUtils.hideKeyboard(mFadeView); mFadeView.fadeOut(); return true; } return false; } private void closeAllFloatingPanels() { if (!mIsFragmentContainer) return; closePlacePage(); if (removeCurrentFragment(true)) { InputUtils.hideKeyboard(mFadeView); mFadeView.fadeOut(); } } public void closeMenu(String statEvent, String alohaStatEvent, @Nullable Runnable procAfterClose) { Statistics.INSTANCE.trackEvent(statEvent); AlohaHelper.logClick(alohaStatEvent); mFadeView.fadeOut(); mMainMenu.close(true, procAfterClose); } private boolean closePositionChooser() { if (UiUtils.isVisible(mPositionChooser)) { hidePositionChooser(); return true; } return false; } public void startLocationToPoint(String statisticsEvent, String alohaEvent, final @Nullable MapObject endPoint) { closeMenu(statisticsEvent, alohaEvent, new Runnable() { @Override public void run() { RoutingController.get().prepare(endPoint); if (mPlacePage != null && (mPlacePage.isDocked() || !mPlacePage.isFloating())) closePlacePage(); } }); } private void toggleMenu() { getCurrentMenu().toggle(true); refreshFade(); } public void refreshFade() { if (getCurrentMenu().isOpen()) mFadeView.fadeIn(); else mFadeView.fadeOut(); } private void initMainMenu() { mMainMenu = new MainMenu(findViewById(R.id.menu_frame), new BaseMenu.ItemClickListener<MainMenu.Item>() { @Override public void onItemClick(MainMenu.Item item) { if (mIsFullscreenAnimating) return; switch (item) { case TOGGLE: if (!mMainMenu.isOpen()) { if (mPlacePage == null || (mPlacePage.isDocked() && closePlacePage())) return; if (closeSidePanel()) return; } Statistics.INSTANCE.trackEvent(Statistics.EventName.TOOLBAR_MENU); AlohaHelper.logClick(AlohaHelper.TOOLBAR_MENU); toggleMenu(); break; case ADD_PLACE: closePlacePage(); if (mIsFragmentContainer) closeSidePanel(); closeMenu(Statistics.EventName.MENU_ADD_PLACE, AlohaHelper.MENU_ADD_PLACE, new Runnable() { @Override public void run() { Statistics.INSTANCE.trackEvent(Statistics.EventName.EDITOR_ADD_CLICK, Statistics.params().add(Statistics.EventParam.FROM, "main_menu")); showPositionChooser(false, false); } }); break; case SEARCH: RoutingController.get().cancel(); closeMenu(Statistics.EventName.TOOLBAR_SEARCH, AlohaHelper.TOOLBAR_SEARCH, new Runnable() { @Override public void run() { showSearch(mSearchController.getQuery()); } }); break; case P2P: startLocationToPoint(Statistics.EventName.MENU_P2P, AlohaHelper.MENU_POINT2POINT, null); break; case BOOKMARKS: closeMenu(Statistics.EventName.TOOLBAR_BOOKMARKS, AlohaHelper.TOOLBAR_BOOKMARKS, new Runnable() { @Override public void run() { showBookmarks(); } }); break; case SHARE: closeMenu(Statistics.EventName.MENU_SHARE, AlohaHelper.MENU_SHARE, new Runnable() { @Override public void run() { shareMyLocation(); } }); break; case DOWNLOADER: RoutingController.get().cancel(); closeMenu(Statistics.EventName.MENU_DOWNLOADER, AlohaHelper.MENU_DOWNLOADER, new Runnable() { @Override public void run() { showDownloader(false); } }); break; case SETTINGS: closeMenu(Statistics.EventName.MENU_SETTINGS, AlohaHelper.MENU_SETTINGS, new Runnable() { @Override public void run() { startActivity(new Intent(MwmActivity.this, SettingsActivity.class)); } }); break; } } }); if (mIsFragmentContainer) { mPanelAnimator = new PanelAnimator(this); mPanelAnimator.registerListener(mMainMenu.getLeftAnimationTrackListener()); return; } if (mPlacePage != null && mPlacePage.isDocked()) mPlacePage.setLeftAnimationTrackListener(mMainMenu.getLeftAnimationTrackListener()); } private void initOnmapDownloader() { mOnmapDownloader = new OnmapDownloader(this); if (mIsFragmentContainer) mPanelAnimator.registerListener(mOnmapDownloader); } @Override public void onDestroy() { if (!isInitializationComplete()) { super.onDestroy(); return; } // TODO move listeners attach-deattach to onStart-onStop since onDestroy isn't guaranteed. Framework.nativeRemoveMapObjectListener(); BottomSheetHelper.free(); SearchEngine.INSTANCE.removeListener(this); super.onDestroy(); } @Override protected void onSaveInstanceState(Bundle outState) { if (mPlacePage != null && !mPlacePage.isHidden()) { outState.putInt(STATE_PP, mPlacePage.getState().ordinal()); outState.putParcelable(STATE_MAP_OBJECT, mPlacePage.getMapObject()); } if (!mIsFragmentContainer && RoutingController.get().isPlanning()) mRoutingPlanInplaceController.onSaveState(outState); if (mIsFragmentContainer) { RoutingPlanFragment fragment = (RoutingPlanFragment) getFragment(RoutingPlanFragment.class); if (fragment != null) fragment.saveRoutingPanelState(outState); } if (mNavigationController != null) mNavigationController.onSaveState(outState); RoutingController.get().onSaveState(); outState.putBoolean(EXTRA_LOCATION_DIALOG_IS_ANNOYING, mLocationErrorDialogAnnoying); if (mNavMyPosition != null) mNavMyPosition.onSaveState(outState); if(mNavAnimationController != null) mNavAnimationController.onSaveState(outState); if (mFilterController != null) mFilterController.onSaveState(outState); super.onSaveInstanceState(outState); } @Override protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); final State state = State.values()[savedInstanceState.getInt(STATE_PP, 0)]; if (mPlacePage != null && state != State.HIDDEN) { mPlacePageRestored = true; mPlacePage.setMapObject((MapObject) savedInstanceState.getParcelable(STATE_MAP_OBJECT), true, new PlacePageView.SetMapObjectListener() { @Override public void onSetMapObjectComplete() { mPlacePage.setState(state); } }); } if (mIsFragmentContainer) { RoutingPlanFragment fragment = (RoutingPlanFragment) getFragment(RoutingPlanFragment.class); if (fragment != null) { fragment.restoreRoutingPanelState(savedInstanceState); } else if (RoutingController.get().isPlanning()) { mRestoreRoutingPlanFragmentNeeded = true; mSavedForTabletState = savedInstanceState; } } if (!mIsFragmentContainer && RoutingController.get().isPlanning()) mRoutingPlanInplaceController.restoreState(savedInstanceState); if (mNavigationController != null) mNavigationController.onRestoreState(savedInstanceState); if (mNavMyPosition != null) mNavMyPosition.onRestoreState(savedInstanceState); if(mNavAnimationController != null) mNavAnimationController.onRestoreState(savedInstanceState); if (mFilterController != null) mFilterController.onRestoreState(savedInstanceState); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode != LOCATION_REQUEST || grantResults.length == 0) return; PermissionsResult result = PermissionsUtils.computePermissionsResult(permissions, grantResults); if (result.isLocationGranted()) myPositionClick(); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); processIntent(intent); } private void processIntent(Intent intent) { if (intent == null) return; if (intent.hasExtra(EXTRA_TASK)) addTask(intent); else if (intent.hasExtra(EXTRA_UPDATE_COUNTRIES)) showDownloader(true); HotelsFilter filter = intent.getParcelableExtra(SearchActivity.EXTRA_HOTELS_FILTER); if (mFilterController != null) { mFilterController.show(filter != null || !TextUtils.isEmpty(SearchEngine.getQuery()), true); mFilterController.setFilter(filter); } } private void addTask(Intent intent) { if (intent != null && !intent.getBooleanExtra(EXTRA_CONSUMED, false) && intent.hasExtra(EXTRA_TASK) && ((intent.getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == 0)) { final MapTask mapTask = (MapTask) intent.getSerializableExtra(EXTRA_TASK); mTasks.add(mapTask); intent.removeExtra(EXTRA_TASK); if (isMapRendererActive()) runTasks(); // mark intent as consumed intent.putExtra(EXTRA_CONSUMED, true); } } private boolean isMapRendererActive() { return mMapFragment != null && MapFragment.nativeIsEngineCreated() && mMapFragment.isContextCreated(); } private void addTask(MapTask task) { mTasks.add(task); if (isMapRendererActive()) runTasks(); } @CallSuper @Override protected void onResume() { super.onResume(); mPlacePageRestored = mPlacePage != null && mPlacePage.getState() != State.HIDDEN; mSearchController.refreshToolbar(); mMainMenu.onResume(new Runnable() { @Override public void run() { if (Framework.nativeIsInChoosePositionMode()) { UiUtils.show(mPositionChooser); setFullscreen(true); } } }); if (mOnmapDownloader != null) mOnmapDownloader.onResume(); if (mNavigationController != null) mNavigationController.onResume(); if (mNavAnimationController != null) mNavAnimationController.onResume(); mPlacePage.onActivityResume(); } @Override public void recreate() { // Explicitly destroy context before activity recreation. if (mMapFragment != null) mMapFragment.destroyContext(); super.recreate(); } @Override protected void onResumeFragments() { super.onResumeFragments(); RoutingController.get().restore(); if (mPlacePage != null) mPlacePage.restore(); if (!LikesManager.INSTANCE.isNewUser() && Counters.isShowReviewForOldUser()) { LikesManager.INSTANCE.showRateDialogForOldUser(this); Counters.setShowReviewForOldUser(false); } else { LikesManager.INSTANCE.showDialogs(this); } } @Override protected void onPause() { TtsPlayer.INSTANCE.stop(); LikesManager.INSTANCE.cancelDialogs(); if (mOnmapDownloader != null) mOnmapDownloader.onPause(); if (mPlacePage != null) mPlacePage.onActivityPause(); super.onPause(); } @Override protected void onStart() { super.onStart(); RoutingController.get().attach(this); if (MapFragment.nativeIsEngineCreated()) LocationHelper.INSTANCE.attach(this); if (mTrafficButtonController != null) TrafficManager.INSTANCE.attach(mTrafficButtonController); if (mNavigationController != null) TrafficManager.INSTANCE.attach(mNavigationController); mPlacePage.onActivityStarted(); } @Override protected void onStop() { super.onStop(); LocationHelper.INSTANCE.detach(!isFinishing()); RoutingController.get().detach(); TrafficManager.INSTANCE.detachAll(); if (mTrafficButtonController != null) mTrafficButtonController.destroy(); mPlacePage.onActivityStopped(); } @Override public void onBackPressed() { if (mFilterController != null && mFilterController.onBackPressed()) return; if (getCurrentMenu().close(true)) { mFadeView.fadeOut(); return; } if (mSearchController.hide()) { SearchEngine.cancelSearch(); return; } if (!closePlacePage() && !closeSidePanel() && !RoutingController.get().cancel() && !closePositionChooser()) { try { super.onBackPressed(); } catch (IllegalStateException e) { // Sometimes this can be called after onSaveState() for unknown reason. } } } private boolean interceptBackPress() { final FragmentManager manager = getSupportFragmentManager(); for (String tag : DOCKED_FRAGMENTS) { final Fragment fragment = manager.findFragmentByTag(tag); if (fragment != null && fragment.isResumed() && fragment instanceof OnBackPressListener) return ((OnBackPressListener) fragment).onBackPressed(); } return false; } private void removeFragmentImmediate(Fragment fragment) { FragmentManager fm = getSupportFragmentManager(); if (fm.isDestroyed()) return; fm.beginTransaction() .remove(fragment) .commitAllowingStateLoss(); fm.executePendingTransactions(); } private boolean removeCurrentFragment(boolean animate) { for (String tag : DOCKED_FRAGMENTS) if (removeFragment(tag, animate)) return true; return false; } private boolean removeFragment(String className, boolean animate) { if (animate && mPanelAnimator == null) animate = false; final Fragment fragment = getSupportFragmentManager().findFragmentByTag(className); if (fragment == null) return false; if (animate) mPanelAnimator.hide(new Runnable() { @Override public void run() { removeFragmentImmediate(fragment); } }); else removeFragmentImmediate(fragment); return true; } @Override public void onMapObjectActivated(final MapObject object) { if (MapObject.isOfType(MapObject.API_POINT, object)) { final ParsedMwmRequest request = ParsedMwmRequest.getCurrentRequest(); if (request == null) return; request.setPointData(object.getLat(), object.getLon(), object.getTitle(), object.getApiId()); object.setSubtitle(request.getCallerName(MwmApplication.get()).toString()); } setFullscreen(false); if (mPlacePage != null) { mPlacePage.setMapObject(object, true, new PlacePageView.SetMapObjectListener() { @Override public void onSetMapObjectComplete() { if (!mPlacePageRestored) { mPlacePage.setState(State.PREVIEW); if (object != null) Framework.logLocalAdsEvent(Framework.LOCAL_ADS_EVENT_OPEN_INFO, object); } mPlacePageRestored = false; } }); } if (UiUtils.isVisible(mFadeView)) mFadeView.fadeOut(); } @Override public void onDismiss(boolean switchFullScreenMode) { if (switchFullScreenMode) { if ((mPanelAnimator != null && mPanelAnimator.isVisible()) || UiUtils.isVisible(mSearchController.getToolbar())) return; setFullscreen(!mIsFullscreen); } else { if (mPlacePage != null) mPlacePage.hide(); } } private BaseMenu getCurrentMenu() { return (RoutingController.get().isNavigating() && mNavigationController != null ? mNavigationController.getNavMenu() : mMainMenu); } private void setFullscreen(boolean isFullscreen) { if (RoutingController.get().isNavigating() || RoutingController.get().isBuilding() || RoutingController.get().isPlanning()) return; mIsFullscreen = isFullscreen; final BaseMenu menu = getCurrentMenu(); if (isFullscreen) { if (menu.isAnimating()) return; mIsFullscreenAnimating = true; Animations.disappearSliding(menu.getFrame(), Animations.BOTTOM, new Runnable() { @Override public void run() { final int menuHeight = menu.getFrame().getHeight(); adjustRuler(0, menuHeight); mIsFullscreenAnimating = false; if (mIsAppearMenuLater) { appearMenu(menu); mIsAppearMenuLater = false; } } }); if (mNavAnimationController != null) mNavAnimationController.disappearZoomButtons(); if (mNavMyPosition != null) mNavMyPosition.hide(); mTraffic.hide(); } else { if (mPlacePage != null && mPlacePage.isHidden() && mNavAnimationController != null) mNavAnimationController.appearZoomButtons(); if (!mIsFullscreenAnimating) appearMenu(menu); else mIsAppearMenuLater = true; } } private void appearMenu(BaseMenu menu) { Animations.appearSliding(menu.getFrame(), Animations.BOTTOM, new Runnable() { @Override public void run() { adjustRuler(0, 0); } }); if (mNavMyPosition != null) mNavMyPosition.show(); mTraffic.show(); } @Override public void onPreviewVisibilityChanged(boolean isVisible) { if (mVisibleRectMeasurer != null) mVisibleRectMeasurer.setPreviewVisible(isVisible); if (isVisible) { if (mMainMenu.isAnimating() || mMainMenu.isOpen()) UiThread.runLater(new Runnable() { @Override public void run() { if (mMainMenu.close(true)) mFadeView.fadeOut(); } }, BaseMenu.ANIMATION_DURATION * 2); } else { Framework.nativeDeactivatePopup(); if (mPlacePage != null) mPlacePage.setMapObject(null, false, null); } } @Override public void onPlacePageVisibilityChanged(boolean isVisible) { if (mVisibleRectMeasurer != null) mVisibleRectMeasurer.setPlacePageVisible(isVisible); Statistics.INSTANCE.trackEvent(isVisible ? Statistics.EventName.PP_OPEN : Statistics.EventName.PP_CLOSE); AlohaHelper.logClick(isVisible ? AlohaHelper.PP_OPEN : AlohaHelper.PP_CLOSE); } @Override public void onProgress(float translationX, float translationY) { if (mNavAnimationController != null) mNavAnimationController.onPlacePageMoved(translationY); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.nav_zoom_in: Statistics.INSTANCE.trackEvent(Statistics.EventName.ZOOM_IN); AlohaHelper.logClick(AlohaHelper.ZOOM_IN); MapFragment.nativeScalePlus(); break; case R.id.nav_zoom_out: Statistics.INSTANCE.trackEvent(Statistics.EventName.ZOOM_OUT); AlohaHelper.logClick(AlohaHelper.ZOOM_OUT); MapFragment.nativeScaleMinus(); break; } } @Override public boolean onTouch(View view, MotionEvent event) { return (mPlacePage != null && mPlacePage.hideOnTouch()) || (mMapFragment != null && mMapFragment.onTouch(view, event)); } @Override public void customOnNavigateUp() { if (removeCurrentFragment(true)) { InputUtils.hideKeyboard(mMainMenu.getFrame()); mSearchController.refreshToolbar(); } } public interface MapTask extends Serializable { boolean run(MwmActivity target); } public static class OpenUrlTask implements MapTask { private static final long serialVersionUID = 1L; private final String mUrl; OpenUrlTask(String url) { Utils.checkNotNull(url); mUrl = url; } @Override public boolean run(MwmActivity target) { final @ParsedUrlMwmRequest.ParsingResult int result = Framework.nativeParseAndSetApiUrl(mUrl); switch (result) { case ParsedUrlMwmRequest.RESULT_INCORRECT: // TODO: Kernel recognizes "mapsme://", "mwm://" and "mapswithme://" schemas only!!! return MapFragment.nativeShowMapForUrl(mUrl); case ParsedUrlMwmRequest.RESULT_MAP: return MapFragment.nativeShowMapForUrl(mUrl); case ParsedUrlMwmRequest.RESULT_ROUTE: final ParsedRoutingData data = Framework.nativeGetParsedRoutingData(); RoutingController.get().setRouterType(data.mRouterType); final RoutePoint from = data.mPoints[0]; final RoutePoint to = data.mPoints[1]; RoutingController.get().prepare(new MapObject("", 0L, 0, MapObject.API_POINT, from.mName, "", "", "", from.mLat, from.mLon, "", null, null, "", null, null), new MapObject("", 0L, 0, MapObject.API_POINT, to.mName, "", "", "", to.mLat, to.mLon, "", null, null, "", null, null)); return true; case ParsedUrlMwmRequest.RESULT_SEARCH: final ParsedSearchRequest request = Framework.nativeGetParsedSearchRequest(); return true; case ParsedUrlMwmRequest.RESULT_LEAD: return true; } return false; } } public static class ShowCountryTask implements MapTask { private static final long serialVersionUID = 1L; private final String mCountryId; private final boolean mDoAutoDownload; public ShowCountryTask(String countryId, boolean doAutoDownload) { mCountryId = countryId; mDoAutoDownload = doAutoDownload; } @Override public boolean run(MwmActivity target) { if (mDoAutoDownload) MapManager.warn3gAndDownload(target, mCountryId, null); Framework.nativeShowCountry(mCountryId, mDoAutoDownload); return true; } } void adjustCompass(int offsetY) { if (mMapFragment == null || !mMapFragment.isAdded()) return; int resultOffset = offsetY; //If the compass is covered by navigation buttons, we move it beyond the visible screen if (mNavAnimationController != null && mNavAnimationController.isConflictWithCompass(offsetY)) { int halfHeight = (int)(UiUtils.dimen(R.dimen.compass_height) * 0.5f); int margin = UiUtils.dimen(R.dimen.margin_compass_top) + UiUtils.dimen(R.dimen.nav_frame_padding); resultOffset = -(offsetY + halfHeight + margin); } mMapFragment.setupCompass(resultOffset, true); CompassData compass = LocationHelper.INSTANCE.getCompassData(); if (compass != null) MapFragment.nativeCompassUpdated(compass.getMagneticNorth(), compass.getTrueNorth(), true); } private void adjustRuler(int offsetX, int offsetY) { if (mMapFragment == null || !mMapFragment.isAdded()) return; mMapFragment.setupRuler(offsetX, offsetY, true); } @Override public FragmentActivity getActivity() { return this; } public MainMenu getMainMenu() { return mMainMenu; } @Override public void showSearch() { showSearch(""); } @Override public void updateMenu() { adjustMenuLineFrameVisibility(new Runnable() { @Override public void run() { if (mNavigationController != null) { mNavigationController.showSearchButtons(RoutingController.get().isPlanning() || RoutingController.get().isBuilt()); } if (RoutingController.get().isNavigating()) { if (mNavigationController != null) mNavigationController.show(true); mSearchController.hide(); mMainMenu.setState(MainMenu.State.NAVIGATION, false, mIsFullscreen); return; } if (mIsFragmentContainer) { mMainMenu.setEnabled(MainMenu.Item.P2P, !RoutingController.get().isPlanning()); mMainMenu.setEnabled(MainMenu.Item.SEARCH, !RoutingController.get().isWaitingPoiPick()); } else if (RoutingController.get().isPlanning()) { mMainMenu.setState(MainMenu.State.ROUTE_PREPARE, false, mIsFullscreen); return; } mMainMenu.setState(MainMenu.State.MENU, false, mIsFullscreen); } }); } private void adjustMenuLineFrameVisibility(@Nullable final Runnable completion) { final RoutingController controller = RoutingController.get(); if (controller.isBuilt() || controller.isTaxiRequestHandled()) { showLineFrame(); if (completion != null) completion.run(); return; } if (controller.isPlanning() || controller.isBuilding() || controller.isErrorEncountered()) { if (showAddStartOrFinishFrame(controller, true)) { if (completion != null) completion.run(); return; } showLineFrame(false, new Runnable() { @Override public void run() { final int menuHeight = getCurrentMenu().getFrame().getHeight(); adjustRuler(0, menuHeight); if (completion != null) completion.run(); } }); return; } hideRoutingActionFrame(); showLineFrame(); if (completion != null) completion.run(); } private boolean showAddStartOrFinishFrame(@NonNull RoutingController controller, boolean showFrame) { // S - start, F - finish, L - my position // -S-F-L -> Start // -S-F+L -> Finish // -S+F-L -> Start // -S+F+L -> Start + Use // +S-F-L -> Finish // +S-F+L -> Finish // +S+F-L -> Hide // +S+F+L -> Hide MapObject myPosition = LocationHelper.INSTANCE.getMyPosition(); if (myPosition != null && !controller.hasEndPoint()) { showAddFinishFrame(); if (showFrame) showLineFrame(); return true; } if (!controller.hasStartPoint()) { showAddStartFrame(); if (showFrame) showLineFrame(); return true; } if (!controller.hasEndPoint()) { showAddFinishFrame(); if (showFrame) showLineFrame(); return true; } return false; } private void showAddStartFrame() { if (!mIsFragmentContainer) { mRoutingPlanInplaceController.showAddStartFrame(); return; } RoutingPlanFragment fragment = (RoutingPlanFragment) getFragment(RoutingPlanFragment.class); if (fragment != null) fragment.showAddStartFrame(); } private void showAddFinishFrame() { if (!mIsFragmentContainer) { mRoutingPlanInplaceController.showAddFinishFrame(); return; } RoutingPlanFragment fragment = (RoutingPlanFragment) getFragment(RoutingPlanFragment.class); if (fragment != null) fragment.showAddFinishFrame(); } private void hideRoutingActionFrame() { if (!mIsFragmentContainer) { mRoutingPlanInplaceController.hideActionFrame(); return; } RoutingPlanFragment fragment = (RoutingPlanFragment) getFragment(RoutingPlanFragment.class); if (fragment != null) fragment.hideActionFrame(); } private void showLineFrame() { showLineFrame(true, new Runnable() { @Override public void run() { adjustRuler(0, 0); } }); } private void showLineFrame(boolean show, @Nullable Runnable completion) { mMainMenu.showLineFrame(show, completion); } private void setNavButtonsTopLimit(int limit) { if (mNavAnimationController == null) return; mNavAnimationController.setTopLimit(limit); } @Override public void onRoutingPlanStartAnimate(boolean show) { if (mNavAnimationController == null) return; mNavAnimationController.setTopLimit(!show ? 0 : mRoutingPlanInplaceController.getHeight()); mNavAnimationController.setBottomLimit(!show ? 0 : getCurrentMenu().getFrame().getHeight()); adjustCompassAndTraffic(!show ? UiUtils.getStatusBarHeight(getApplicationContext()) : mRoutingPlanInplaceController.getHeight()); } @Override public void showRoutePlan(boolean show, @Nullable Runnable completionListener) { if (show) { mSearchController.hide(); if (mIsFragmentContainer) { replaceFragment(RoutingPlanFragment.class, null, completionListener); if (mRestoreRoutingPlanFragmentNeeded && mSavedForTabletState != null) { RoutingPlanFragment fragment = (RoutingPlanFragment) getFragment(RoutingPlanFragment.class); if (fragment != null) fragment.restoreRoutingPanelState(mSavedForTabletState); } showAddStartOrFinishFrame(RoutingController.get(), false); int width = UiUtils.dimen(R.dimen.panel_width); adjustTraffic(width, UiUtils.getStatusBarHeight(getApplicationContext())); if (mNavigationController != null) mNavigationController.adjustSearchButtons(width); } else { mRoutingPlanInplaceController.show(true); if (completionListener != null) completionListener.run(); } } else { if (mIsFragmentContainer) { adjustCompassAndTraffic(UiUtils.getStatusBarHeight(getApplicationContext())); setNavButtonsTopLimit(0); if (mNavigationController != null) mNavigationController.adjustSearchButtons(0); } else { mRoutingPlanInplaceController.show(false); } closeAllFloatingPanels(); if (mNavigationController != null) mNavigationController.resetSearchWheel(); if (completionListener != null) completionListener.run(); updateSearchBar(); } if (mPlacePage != null) mPlacePage.refreshViews(); } private void adjustCompassAndTraffic(int offsetY) { adjustCompass(offsetY); adjustTraffic(0, offsetY); } private void adjustTraffic(int offsetX, int offsetY) { mTraffic.setOffset(offsetX, offsetY); } @Override public void onSearchVisibilityChanged(boolean visible) { if (mNavAnimationController == null) return; int toolbarHeight = mSearchController.getToolbar().getHeight(); adjustCompassAndTraffic(visible ? toolbarHeight : UiUtils.getStatusBarHeight(this)); setNavButtonsTopLimit(visible ? toolbarHeight : 0); if (mFilterController != null) { boolean show = visible && !TextUtils.isEmpty(SearchEngine.getQuery()) && !RoutingController.get().isNavigating(); mFilterController.show(show, true); mMainMenu.show(!show); } } @Override public void onResultsUpdate(SearchResult[] results, long timestamp, boolean isHotel) { if (mFilterController != null) mFilterController.updateFilterButtonVisibility(isHotel); } @Override public void onResultsEnd(long timestamp) { } @Override public void showNavigation(boolean show) { if (mPlacePage != null) mPlacePage.refreshViews(); if (mNavigationController != null) mNavigationController.show(show); refreshFade(); if (mOnmapDownloader != null) mOnmapDownloader.updateState(false); adjustCompass(UiUtils.getCompassYOffset(this)); if (show) { mSearchController.clear(); mSearchController.hide(); if (mFilterController != null) mFilterController.show(false, true); } } @Override public void updateBuildProgress(int progress, @Framework.RouterType int router) { if (mIsFragmentContainer) { RoutingPlanFragment fragment = (RoutingPlanFragment) getFragment(RoutingPlanFragment.class); if (fragment != null) fragment.updateBuildProgress(progress, router); } else { mRoutingPlanInplaceController.updateBuildProgress(progress, router); } } @Override public void onTaxiInfoReceived(@NonNull TaxiInfo info) { if (mIsFragmentContainer) { RoutingPlanFragment fragment = (RoutingPlanFragment) getFragment(RoutingPlanFragment.class); if (fragment != null) fragment.showTaxiInfo(info); } else { mRoutingPlanInplaceController.showTaxiInfo(info); } } @Override public void onTaxiError(@NonNull TaxiManager.ErrorCode code) { if (mIsFragmentContainer) { RoutingPlanFragment fragment = (RoutingPlanFragment) getFragment(RoutingPlanFragment.class); if (fragment != null) fragment.showTaxiError(code); } else { mRoutingPlanInplaceController.showTaxiError(code); } } @Override public void onNavigationCancelled() { if (mNavigationController != null) mNavigationController.stop(this); updateSearchBar(); ThemeSwitcher.restart(isMapRendererActive()); } @Override public void onNavigationStarted() { ThemeSwitcher.restart(isMapRendererActive()); } @Override public void onAddedStop() { closePlacePage(); } @Override public void onRemovedStop() { closePlacePage(); } @Override public void onBuiltRoute() { if (!RoutingController.get().isPlanning()) return; if (mNavigationController != null) mNavigationController.resetSearchWheel(); } private void updateSearchBar() { if (!TextUtils.isEmpty(SearchEngine.getQuery())) mSearchController.refreshToolbar(); } @Override public void onMyPositionModeChanged(int newMode) { if (mNavMyPosition != null) mNavMyPosition.update(newMode); RoutingController controller = RoutingController.get(); if (controller.isPlanning()) showAddStartOrFinishFrame(controller, true); } @Override public void onLocationUpdated(@NonNull Location location) { if (mPlacePage != null && !mPlacePage.isHidden()) mPlacePage.refreshLocation(location); if (!RoutingController.get().isNavigating()) return; if (mNavigationController != null) mNavigationController.update(Framework.nativeGetRouteFollowingInfo()); TtsPlayer.INSTANCE.playTurnNotifications(); } @Override public void onCompassUpdated(@NonNull CompassData compass) { MapFragment.nativeCompassUpdated(compass.getMagneticNorth(), compass.getTrueNorth(), false); if (mPlacePage != null) mPlacePage.refreshAzimuth(compass.getNorth()); if (mNavigationController != null) mNavigationController.updateNorth(compass.getNorth()); } @Override public void onLocationError() { if (mLocationErrorDialogAnnoying) return; Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); if (intent.resolveActivity(MwmApplication.get().getPackageManager()) == null) { intent = new Intent(android.provider.Settings.ACTION_SECURITY_SETTINGS); if (intent.resolveActivity(MwmApplication.get().getPackageManager()) == null) return; } showLocationErrorDialog(intent); } @Override public void onTranslationChanged(float translation) { if (mNavigationController != null) mNavigationController.updateSearchButtonsTranslation(translation); } @Override public void onFadeInZoomButtons() { if (mNavigationController != null && (RoutingController.get().isPlanning() || RoutingController.get().isNavigating())) mNavigationController.fadeInSearchButtons(); } @Override public void onFadeOutZoomButtons() { if (mNavigationController != null && (RoutingController.get().isPlanning() || RoutingController.get().isNavigating())) { if (UiUtils.isLandscape(this)) mTraffic.hide(); else mNavigationController.fadeOutSearchButtons(); } } private void showLocationErrorDialog(@NonNull final Intent intent) { if (mLocationErrorDialog != null && mLocationErrorDialog.isShowing()) return; mLocationErrorDialog = new AlertDialog.Builder(this) .setTitle(R.string.enable_location_services) .setMessage(R.string.location_is_disabled_long_text) .setNegativeButton(R.string.close, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mLocationErrorDialogAnnoying = true; } }) .setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { mLocationErrorDialogAnnoying = true; } }) .setPositiveButton(R.string.connection_settings, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { startActivity(intent); } }).show(); } @Override public void onLocationNotFound() { showLocationNotFoundDialog(); } private void showLocationNotFoundDialog() { String message = String.format("%s\n\n%s", getString(R.string.current_location_unknown_message), getString(R.string.current_location_unknown_title)); new AlertDialog.Builder(this) .setMessage(message) .setNegativeButton(R.string.current_location_unknown_stop_button, null) .setPositiveButton(R.string.current_location_unknown_continue_button, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (!LocationHelper.INSTANCE.isActive()) LocationHelper.INSTANCE.start(); } }).show(); } public static class ShowAuthorizationTask implements MapTask { @Override public boolean run(MwmActivity target) { final DialogFragment fragment = (DialogFragment) Fragment.instantiate(target, AuthDialogFragment.class.getName()); fragment.show(target.getSupportFragmentManager(), AuthDialogFragment.class.getName()); return true; } } public static abstract class BaseUserMarkTask implements MapTask { private static final long serialVersionUID = 1L; final int mCategoryId; final int mId; BaseUserMarkTask(int categoryId, int id) { mCategoryId = categoryId; mId = id; } } public static class ShowBookmarkTask extends BaseUserMarkTask { public ShowBookmarkTask(int categoryId, int bookmarkId) { super(categoryId, bookmarkId); } @Override public boolean run(MwmActivity target) { BookmarkManager.INSTANCE.nativeShowBookmarkOnMap(mCategoryId, mId); return true; } } public static class ShowTrackTask extends BaseUserMarkTask { public ShowTrackTask(int categoryId, int trackId) { super(categoryId, trackId); } @Override public boolean run(MwmActivity target) { Framework.nativeShowTrackRect(mCategoryId, mId); return true; } } static class ShowPointTask implements MapTask { private final double mLat; private final double mLon; ShowPointTask(double lat, double lon) { mLat = lat; mLon = lon; } @Override public boolean run(MwmActivity target) { MapFragment.nativeShowMapForUrl(String.format(Locale.US, "mapsme://map?ll=%f,%f", mLat, mLon)); return true; } } static class BuildRouteTask implements MapTask { private final double mLatTo; private final double mLonTo; @Nullable private final Double mLatFrom; @Nullable private final Double mLonFrom; @Nullable private final String mRouter; @NonNull private static MapObject fromLatLon(double lat, double lon) { return new MapObject("", 0L, 0, MapObject.API_POINT, "", "", "", "", lat, lon, "", null, null, "", null, null); } BuildRouteTask(double latTo, double lonTo) { this(latTo, lonTo, null, null, null); } BuildRouteTask(double latTo, double lonTo, @Nullable Double latFrom, @Nullable Double lonFrom) { this(latTo, lonTo, latFrom, lonFrom, null); } BuildRouteTask(double latTo, double lonTo, @Nullable Double latFrom, @Nullable Double lonFrom, @Nullable String router) { mLatTo = latTo; mLonTo = lonTo; mLatFrom = latFrom; mLonFrom = lonFrom; mRouter = router; } @Override public boolean run(MwmActivity target) { @Framework.RouterType int routerType = -1; if (!TextUtils.isEmpty(mRouter)) { switch (mRouter) { case "vehicle": routerType = Framework.ROUTER_TYPE_VEHICLE; break; case "pedestrian": routerType = Framework.ROUTER_TYPE_PEDESTRIAN; break; case "bicycle": routerType = Framework.ROUTER_TYPE_BICYCLE; break; case "taxi": routerType = Framework.ROUTER_TYPE_TAXI; break; } } if (mLatFrom != null && mLonFrom != null && routerType >= 0) { RoutingController.get().prepare(fromLatLon(mLatFrom, mLonFrom), fromLatLon(mLatTo, mLonTo), routerType); } else if (mLatFrom != null && mLonFrom != null) { RoutingController.get().prepare(fromLatLon(mLatFrom, mLonFrom), fromLatLon(mLatTo, mLonTo)); } else { RoutingController.get().prepare(fromLatLon(mLatTo, mLonTo)); } return true; } } }
package me.yokeyword.sample; import android.app.Application; import me.yokeyword.fragmentation.Fragmentation; import me.yokeyword.fragmentation.helper.ExceptionHandler; public class App extends Application { @Override public void onCreate() { super.onCreate(); Fragmentation.builder() // SHAKE: NONE Debug .stackViewMode(Fragmentation.BUBBLE) // true"Can not perform this action after onSaveInstanceState!"Crash; // falseCrashhandleException() .debug(true) // .debug(BuildConfig.DEBUG) // crash .handleException(new ExceptionHandler() { @Override public void onException(Exception e) { // Bugtags: Exception Bugtags // Bugtags.sendException(e); } }) .install(); } }
package com.mapswithme.maps; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.location.Location; import android.os.Bundle; import android.os.Handler; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v7.app.AlertDialog; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.Toast; import java.io.Serializable; import java.util.Stack; import com.mapswithme.country.ActiveCountryTree; import com.mapswithme.country.DownloadActivity; import com.mapswithme.country.DownloadFragment; import com.mapswithme.maps.Framework.OnBalloonListener; import com.mapswithme.maps.MapStorage.Index; import com.mapswithme.maps.activity.CustomNavigateUpListener; import com.mapswithme.maps.ads.LikesManager; import com.mapswithme.maps.api.ParsedMwmRequest; import com.mapswithme.maps.base.BaseMwmFragmentActivity; import com.mapswithme.maps.base.OnBackPressListener; import com.mapswithme.maps.bookmarks.BookmarkCategoriesActivity; import com.mapswithme.maps.bookmarks.ChooseBookmarkCategoryFragment; import com.mapswithme.maps.bookmarks.data.BookmarkManager; import com.mapswithme.maps.bookmarks.data.MapObject; import com.mapswithme.maps.bookmarks.data.MapObject.ApiPoint; import com.mapswithme.maps.location.LocationHelper; import com.mapswithme.maps.location.LocationPredictor; import com.mapswithme.maps.routing.NavigationController; import com.mapswithme.maps.routing.RoutingController; import com.mapswithme.maps.routing.RoutingInfo; import com.mapswithme.maps.routing.RoutingPlanFragment; import com.mapswithme.maps.routing.RoutingPlanInplaceController; import com.mapswithme.maps.search.FloatingSearchToolbarController; import com.mapswithme.maps.search.SearchActivity; import com.mapswithme.maps.search.SearchEngine; import com.mapswithme.maps.search.SearchFragment; import com.mapswithme.maps.settings.SettingsActivity; import com.mapswithme.maps.settings.StoragePathManager; import com.mapswithme.maps.settings.UnitLocale; import com.mapswithme.maps.sound.TtsPlayer; import com.mapswithme.maps.widget.FadeView; import com.mapswithme.maps.widget.menu.MainMenu; import com.mapswithme.maps.widget.placepage.BasePlacePageAnimationController; import com.mapswithme.maps.widget.placepage.PlacePageView; import com.mapswithme.maps.widget.placepage.PlacePageView.State; import com.mapswithme.util.Animations; import com.mapswithme.util.BottomSheetHelper; import com.mapswithme.util.Config; import com.mapswithme.util.InputUtils; import com.mapswithme.util.LocationUtils; import com.mapswithme.util.UiUtils; import com.mapswithme.util.Utils; import com.mapswithme.util.Yota; import com.mapswithme.util.sharing.ShareOption; import com.mapswithme.util.sharing.SharingHelper; import com.mapswithme.util.statistics.AlohaHelper; import com.mapswithme.util.statistics.MytargetHelper; import com.mapswithme.util.statistics.Statistics; import ru.mail.android.mytarget.nativeads.NativeAppwallAd; import ru.mail.android.mytarget.nativeads.banners.NativeAppwallBanner; public class MwmActivity extends BaseMwmFragmentActivity implements LocationHelper.LocationListener, OnBalloonListener, View.OnTouchListener, BasePlacePageAnimationController.OnVisibilityChangedListener, OnClickListener, MapFragment.MapRenderingListener, CustomNavigateUpListener, ChooseBookmarkCategoryFragment.Listener, RoutingController.Container { public static final String EXTRA_TASK = "map_task"; private static final String EXTRA_CONSUMED = "mwm.extra.intent.processed"; private static final String EXTRA_UPDATE_COUNTRIES = ".extra.update.countries"; private static final String[] DOCKED_FRAGMENTS = { SearchFragment.class.getName(), DownloadFragment.class.getName(), RoutingPlanFragment.class.getName() }; // Instance state private static final String STATE_PP_OPENED = "PpOpened"; private static final String STATE_MAP_OBJECT = "MapObject"; // Map tasks that we run AFTER rendering initialized private final Stack<MapTask> mTasks = new Stack<>(); private final StoragePathManager mPathManager = new StoragePathManager(); private View mFrame; // map private MapFragment mMapFragment; // Place page private PlacePageView mPlacePage; // Routing private RoutingPlanInplaceController mRoutingPlanInplaceController; private NavigationController mNavigationController; private MainMenu mMainMenu; private PanelAnimator mPanelAnimator; private MytargetHelper mMytargetHelper; private FadeView mFadeView; private ImageButton mBtnZoomIn; private ImageButton mBtnZoomOut; private boolean mIsFragmentContainer; private boolean mIsFullscreen; private LocationPredictor mLocationPredictor; private FloatingSearchToolbarController mSearchController; private LastCompassData mLastCompassData; public interface LeftAnimationTrackListener { void onTrackStarted(boolean collapsed); void onTrackFinished(boolean collapsed); void onTrackLeftAnimation(float offset); } private static class LastCompassData { double magneticNorth; double trueNorth; double north; void update(int rotation, double magneticNorth, double trueNorth) { this.magneticNorth = LocationUtils.correctCompassAngle(rotation, magneticNorth); this.trueNorth = LocationUtils.correctCompassAngle(rotation, trueNorth); north = (this.trueNorth >= 0.0) ? this.trueNorth : this.magneticNorth; } } public static Intent createShowMapIntent(Context context, Index index, boolean doAutoDownload) { return new Intent(context, DownloadResourcesActivity.class) .putExtra(DownloadResourcesActivity.EXTRA_COUNTRY_INDEX, index) .putExtra(DownloadResourcesActivity.EXTRA_AUTODOWNLOAD_COUNTRY, doAutoDownload); } public static Intent createUpdateMapsIntent() { return new Intent(MwmApplication.get(), MwmActivity.class) .putExtra(EXTRA_UPDATE_COUNTRIES, true); } @Override public void onRenderingInitialized() { checkMeasurementSystem(); checkKitkatMigrationMove(); runTasks(); } private void runTasks() { // Task are not UI-thread bounded, // if any task need UI-thread it should implicitly // use Activity.runOnUiThread(). while (!mTasks.isEmpty()) mTasks.pop().run(this); } private static void checkMeasurementSystem() { UnitLocale.initializeCurrentUnits(); } private void checkKitkatMigrationMove() { mPathManager.checkKitkatMigration(this); } @Override protected int getFragmentContentResId() { return (mIsFragmentContainer ? R.id.fragment_container : super.getFragmentContentResId()); } public @Nullable Fragment getFragment(Class<? extends Fragment> clazz) { if (!mIsFragmentContainer) throw new IllegalStateException("Must be called for tablets only!"); return getSupportFragmentManager().findFragmentByTag(clazz.getName()); } void replaceFragmentInternal(Class<? extends Fragment> fragmentClass, Bundle args) { super.replaceFragment(fragmentClass, args, null); } @Override public void replaceFragment(Class<? extends Fragment> fragmentClass, Bundle args, Runnable completionListener) { if (mPanelAnimator.isVisible() && getFragment(fragmentClass) != null) { if (completionListener != null) completionListener.run(); return; } mPanelAnimator.show(fragmentClass, args, completionListener); } private void showBookmarks() { startActivity(new Intent(this, BookmarkCategoriesActivity.class)); } public void showSearch(String query) { if (mIsFragmentContainer) { mSearchController.hide(); final Bundle args = new Bundle(); args.putString(SearchActivity.EXTRA_QUERY, query); replaceFragment(SearchFragment.class, args, null); } else SearchActivity.start(this, query); } private void shareMyLocation() { final Location loc = LocationHelper.INSTANCE.getLastLocation(); if (loc != null) { final String geoUrl = Framework.nativeGetGe0Url(loc.getLatitude(), loc.getLongitude(), Framework.getDrawScale(), ""); final String httpUrl = Framework.getHttpGe0Url(loc.getLatitude(), loc.getLongitude(), Framework.getDrawScale(), ""); final String body = getString(R.string.my_position_share_sms, geoUrl, httpUrl); ShareOption.ANY.share(this, body); return; } new AlertDialog.Builder(MwmActivity.this) .setMessage(R.string.unknown_current_position) .setCancelable(true) .setPositiveButton(android.R.string.ok, new Dialog.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).show(); } @Override public void showDownloader(boolean openDownloadedList) { final Bundle args = new Bundle(); args.putBoolean(DownloadActivity.EXTRA_OPEN_DOWNLOADED_LIST, openDownloadedList); if (mIsFragmentContainer) { SearchEngine.cancelSearch(); mSearchController.refreshToolbar(); replaceFragment(DownloadFragment.class, args, null); } else { startActivity(new Intent(this, DownloadActivity.class).putExtras(args)); } } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_map); initViews(); Statistics.INSTANCE.trackConnectionState(); Framework.nativeSetBalloonListener(this); mSearchController = new FloatingSearchToolbarController(this); mLocationPredictor = new LocationPredictor(new Handler(), this); processIntent(getIntent()); SharingHelper.prepare(); RoutingController.get().attach(this); } private void initViews() { initMap(); initYota(); initPlacePage(); initNavigationButtons(); if (findViewById(R.id.fragment_container) != null) mIsFragmentContainer = true; else { mRoutingPlanInplaceController = new RoutingPlanInplaceController(this); removeCurrentFragment(false); } mNavigationController = new NavigationController(this); initMenu(); } private void initMap() { mFrame = findViewById(R.id.map_fragment_container); mFadeView = (FadeView) findViewById(R.id.fade_view); mFadeView.setListener(new FadeView.Listener() { @Override public void onTouch() { mMainMenu.close(true); } }); mMapFragment = (MapFragment) getSupportFragmentManager().findFragmentByTag(MapFragment.FRAGMENT_TAG); if (mMapFragment == null) { mMapFragment = (MapFragment) MapFragment.instantiate(this, MapFragment.class.getName(), null); getSupportFragmentManager() .beginTransaction() .replace(R.id.map_fragment_container, mMapFragment, MapFragment.FRAGMENT_TAG) .commit(); } mFrame.setOnTouchListener(this); } private void initNavigationButtons() { View frame = findViewById(R.id.navigation_buttons); mBtnZoomIn = (ImageButton) frame.findViewById(R.id.map_button_plus); mBtnZoomIn.setOnClickListener(this); mBtnZoomOut = (ImageButton) frame.findViewById(R.id.map_button_minus); mBtnZoomOut.setOnClickListener(this); } private void initPlacePage() { mPlacePage = (PlacePageView) findViewById(R.id.info_box); mPlacePage.setOnVisibilityChangedListener(this); mPlacePage.findViewById(R.id.ll__route).setOnClickListener(this); } private void initYota() { if (Yota.isFirstYota()) findViewById(R.id.yop_it).setOnClickListener(this); } private boolean closePlacePage() { if (mPlacePage.getState() == State.HIDDEN) return false; mPlacePage.hide(); Framework.deactivatePopup(); return true; } private boolean closeSidePanel() { if (interceptBackPress()) return true; if (removeCurrentFragment(true)) { InputUtils.hideKeyboard(mFadeView); mFadeView.fadeOut(false); return true; } return false; } public void closeMenu(String statEvent, String alohaStatEvent, @Nullable Runnable procAfterClose) { Statistics.INSTANCE.trackEvent(statEvent); AlohaHelper.logClick(alohaStatEvent); mFadeView.fadeOut(false); mMainMenu.close(true, procAfterClose); } private void startLocationToPoint(String statisticsEvent, String alohaEvent, final @Nullable MapObject endPoint) { closeMenu(statisticsEvent, alohaEvent, new Runnable() { @Override public void run() { RoutingController.get().prepare(endPoint); if (mPlacePage.isDocked() || !mPlacePage.isFloating()) closePlacePage(); } }); } private void toggleMenu() { if (mMainMenu.isOpen()) mFadeView.fadeOut(false); else mFadeView.fadeIn(); mMainMenu.toggle(true); } private void initMenu() { mMainMenu = new MainMenu((ViewGroup) findViewById(R.id.menu_frame), new MainMenu.Container() { @Override public Activity getActivity() { return MwmActivity.this; } @Override public void onItemClick(MainMenu.Item item) { switch (item) { case TOGGLE: if (!mMainMenu.isOpen()) { if (mPlacePage.isDocked() && closePlacePage()) return; if (closeSidePanel()) return; } Statistics.INSTANCE.trackEvent(Statistics.EventName.TOOLBAR_MENU); AlohaHelper.logClick(AlohaHelper.TOOLBAR_MENU); toggleMenu(); break; case SEARCH: RoutingController.get().cancelPlanning(); closeMenu(Statistics.EventName.TOOLBAR_SEARCH, AlohaHelper.TOOLBAR_SEARCH, new Runnable() { @Override public void run() { showSearch(mSearchController.getQuery()); } }); break; case P2P: startLocationToPoint(Statistics.EventName.MENU_P2P, AlohaHelper.MENU_POINT2POINT, null); break; case BOOKMARKS: closeMenu(Statistics.EventName.TOOLBAR_BOOKMARKS, AlohaHelper.TOOLBAR_BOOKMARKS, new Runnable() { @Override public void run() { showBookmarks(); } }); break; case SHARE: closeMenu(Statistics.EventName.MENU_SHARE, AlohaHelper.MENU_SHARE, new Runnable() { @Override public void run() { shareMyLocation(); } }); break; case DOWNLOADER: RoutingController.get().cancelPlanning(); closeMenu(Statistics.EventName.MENU_DOWNLOADER, AlohaHelper.MENU_DOWNLOADER, new Runnable() { @Override public void run() { showDownloader(false); } }); break; case SETTINGS: closeMenu(Statistics.EventName.MENU_SETTINGS, AlohaHelper.MENU_SETTINGS, new Runnable() { @Override public void run() { startActivity(new Intent(getActivity(), SettingsActivity.class)); } }); break; case SHOWCASE: closeMenu(Statistics.EventName.MENU_SHOWCASE, AlohaHelper.MENU_SHOWCASE, new Runnable() { @Override public void run() { mMytargetHelper.displayShowcase(); } }); break; } } }); if (mIsFragmentContainer) { mPanelAnimator = new PanelAnimator(this, mMainMenu.getLeftAnimationTrackListener()); return; } mRoutingPlanInplaceController.setStartButton(); if (mPlacePage.isDocked()) mPlacePage.setLeftAnimationTrackListener(mMainMenu.getLeftAnimationTrackListener()); } @Override public void onDestroy() { Framework.nativeRemoveBalloonListener(); BottomSheetHelper.free(); RoutingController.get().detach(); super.onDestroy(); } @Override protected void onSaveInstanceState(Bundle outState) { if (mPlacePage.getState() != State.HIDDEN) { outState.putBoolean(STATE_PP_OPENED, true); outState.putParcelable(STATE_MAP_OBJECT, mPlacePage.getMapObject()); } if (!mIsFragmentContainer && RoutingController.get().isPlanning()) mRoutingPlanInplaceController.onSaveState(outState); RoutingController.get().onSaveState(); super.onSaveInstanceState(outState); } @Override protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); if (savedInstanceState.getBoolean(STATE_PP_OPENED)) { mPlacePage.setMapObject((MapObject) savedInstanceState.getParcelable(STATE_MAP_OBJECT)); mPlacePage.setState(State.PREVIEW); } if (!mIsFragmentContainer && RoutingController.get().isPlanning()) mRoutingPlanInplaceController.restoreState(savedInstanceState); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); processIntent(intent); } private void processIntent(Intent intent) { if (intent == null) return; if (intent.hasExtra(EXTRA_TASK)) addTask(intent); else if (intent.hasExtra(EXTRA_UPDATE_COUNTRIES)) { ActiveCountryTree.updateAll(); showDownloader(true); } } private void addTask(Intent intent) { if (intent != null && !intent.getBooleanExtra(EXTRA_CONSUMED, false) && intent.hasExtra(EXTRA_TASK) && ((intent.getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == 0)) { final MapTask mapTask = (MapTask) intent.getSerializableExtra(EXTRA_TASK); mTasks.add(mapTask); intent.removeExtra(EXTRA_TASK); if (MapFragment.nativeIsEngineCreated()) runTasks(); // mark intent as consumed intent.putExtra(EXTRA_CONSUMED, true); } } @Override public void onLocationError(int errorCode) { MapFragment.nativeOnLocationError(errorCode); if (errorCode == LocationHelper.ERROR_DENIED) { LocationState.INSTANCE.turnOff(); Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); if (intent.resolveActivity(getPackageManager()) == null) { intent = new Intent(android.provider.Settings.ACTION_SECURITY_SETTINGS); if (intent.resolveActivity(getPackageManager()) == null) return; } final Intent finIntent = intent; new AlertDialog.Builder(this) .setTitle(R.string.enable_location_service) .setMessage(R.string.location_is_disabled_long_text) .setPositiveButton(R.string.connection_settings, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { startActivity(finIntent); } }) .setNegativeButton(R.string.close, null) .show(); } else if (errorCode == LocationHelper.ERROR_GPS_OFF) { Toast.makeText(this, R.string.gps_is_disabled_long_text, Toast.LENGTH_LONG).show(); } } @Override public void onLocationUpdated(final Location location) { if (!location.getProvider().equals(LocationHelper.LOCATION_PREDICTOR_PROVIDER)) mLocationPredictor.reset(location); MapFragment.nativeLocationUpdated(location.getTime(), location.getLatitude(), location.getLongitude(), location.getAccuracy(), location.getAltitude(), location.getSpeed(), location.getBearing()); if (mPlacePage.getState() != State.HIDDEN) mPlacePage.refreshLocation(location); if (!RoutingController.get().isNavigating()) return; RoutingInfo info = Framework.nativeGetRouteFollowingInfo(); mNavigationController.update(info); mMainMenu.updateRoutingInfo(info); TtsPlayer.INSTANCE.playTurnNotifications(); } @Override public void onCompassUpdated(long time, double magneticNorth, double trueNorth, double accuracy) { if (mLastCompassData == null) mLastCompassData = new LastCompassData(); mLastCompassData.update(getWindowManager().getDefaultDisplay().getRotation(), magneticNorth, trueNorth); MapFragment.nativeCompassUpdated(mLastCompassData.magneticNorth, mLastCompassData.trueNorth, false); mPlacePage.refreshAzimuth(mLastCompassData.north); mNavigationController.updateNorth(mLastCompassData.north); } // Callback from native location state mode element processing. @SuppressWarnings("unused") public void onMyPositionModeChangedCallback(final int newMode) { mLocationPredictor.myPositionModeChanged(newMode); mMainMenu.getMyPositionButton().update(newMode); switch (newMode) { case LocationState.UNKNOWN_POSITION: pauseLocation(); break; case LocationState.PENDING_POSITION: resumeLocation(); break; } } @Override protected void onResume() { super.onResume(); LocationState.INSTANCE.setMyPositionModeListener(this); invalidateLocationState(); mSearchController.refreshToolbar(); mPlacePage.onResume(); // if (!NewsFragment.showOn(this)) LikesManager.INSTANCE.showDialogs(this); mMainMenu.onResume(); } private void initShowcase() { NativeAppwallAd.AppwallAdListener listener = new NativeAppwallAd.AppwallAdListener() { @Override public void onLoad(NativeAppwallAd nativeAppwallAd) { if (nativeAppwallAd.getBanners().isEmpty()) { mMainMenu.showShowcase(false); return; } final NativeAppwallBanner menuBanner = nativeAppwallAd.getBanners().get(0); mMainMenu.showShowcase(true); } @Override public void onNoAd(String reason, NativeAppwallAd nativeAppwallAd) { mMainMenu.showShowcase(false); } @Override public void onClick(NativeAppwallBanner nativeAppwallBanner, NativeAppwallAd nativeAppwallAd) {} @Override public void onDismissDialog(NativeAppwallAd nativeAppwallAd) {} }; mMytargetHelper = new MytargetHelper(listener, this); } @Override protected void onResumeFragments() { super.onResumeFragments(); RoutingController.get().restore(); mPlacePage.restore(); } private void adjustZoomButtons() { final boolean show = showZoomButtons(); UiUtils.showIf(show, mBtnZoomIn, mBtnZoomOut); if (!show) return; mFrame.post(new Runnable() { @Override public void run() { int height = mFrame.getMeasuredHeight(); int top = UiUtils.dimen(R.dimen.zoom_buttons_top_required_space); int bottom = UiUtils.dimen(R.dimen.zoom_buttons_bottom_max_space); int space = (top + bottom < height ? bottom : height - top); LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mBtnZoomOut.getLayoutParams(); lp.bottomMargin = space; mBtnZoomOut.setLayoutParams(lp); } }); } private boolean showZoomButtons() { return RoutingController.get().isNavigating() || Config.showZoomButtons(); } @Override protected void onPause() { LocationState.INSTANCE.removeMyPositionModeListener(); pauseLocation(); TtsPlayer.INSTANCE.stop(); LikesManager.INSTANCE.cancelDialogs(); super.onPause(); } private void resumeLocation() { LocationHelper.INSTANCE.addLocationListener(this); // Do not turn off the screen while displaying position Utils.keepScreenOn(true, getWindow()); mLocationPredictor.resume(); } private void pauseLocation() { LocationHelper.INSTANCE.removeLocationListener(this); // Enable automatic turning screen off while app is idle Utils.keepScreenOn(false, getWindow()); mLocationPredictor.pause(); } private void refreshLocationState(int newMode) { mMainMenu.getMyPositionButton().update(newMode); switch (newMode) { case LocationState.UNKNOWN_POSITION: pauseLocation(); break; case LocationState.PENDING_POSITION: resumeLocation(); break; default: break; } } /** * Invalidates location state in core. * Updates location button accordingly. */ public void invalidateLocationState() { final int currentLocationMode = LocationState.INSTANCE.getLocationStateMode(); refreshLocationState(currentLocationMode); LocationState.INSTANCE.invalidatePosition(); } @Override protected void onStart() { super.onStart(); initShowcase(); } @Override protected void onStop() { super.onStop(); mMytargetHelper.cancel(); } @Override public void onBackPressed() { if (mMainMenu.close(true)) { mFadeView.fadeOut(false); return; } if (mSearchController.hide()) { SearchEngine.cancelSearch(); return; } if (!closePlacePage() && !closeSidePanel() && !RoutingController.get().cancel()) super.onBackPressed(); } private boolean interceptBackPress() { final FragmentManager manager = getSupportFragmentManager(); for (String tag : DOCKED_FRAGMENTS) { final Fragment fragment = manager.findFragmentByTag(tag); if (fragment != null && fragment.isResumed() && fragment instanceof OnBackPressListener) return ((OnBackPressListener) fragment).onBackPressed(); } return false; } private void removeFragmentImmediate(Fragment fragment) { getSupportFragmentManager().beginTransaction() .remove(fragment) .commitAllowingStateLoss(); getSupportFragmentManager().executePendingTransactions(); } boolean removeCurrentFragment(boolean animate) { for (String tag : DOCKED_FRAGMENTS) if (removeFragment(tag, animate)) return true; return false; } private boolean removeFragment(String className, boolean animate) { if (animate && mPanelAnimator == null) animate = false; final Fragment fragment = getSupportFragmentManager().findFragmentByTag(className); if (fragment == null) return false; if (animate) mPanelAnimator.hide(new Runnable() { @Override public void run() { removeFragmentImmediate(fragment); } }); else removeFragmentImmediate(fragment); return true; } // Callbacks from native touch events on map objects. @Override public void onApiPointActivated(final double lat, final double lon, final String name, final String id) { final ParsedMwmRequest request = ParsedMwmRequest.getCurrentRequest(); if (request == null) return; request.setPointData(lat, lon, name, id); runOnUiThread(new Runnable() { @Override public void run() { final String poiType = request.getCallerName(MwmApplication.get()).toString(); activateMapObject(new ApiPoint(name, id, poiType, lat, lon)); } }); } @Override public void onPoiActivated(final String name, final String type, final String address, final double lat, final double lon, final int[] metaTypes, final String[] metaValues) { final MapObject poi = new MapObject.Poi(name, lat, lon, type); poi.addMetadata(metaTypes, metaValues); activateMapObject(poi); } @Override public void onBookmarkActivated(final int category, final int bookmarkIndex) { activateMapObject(BookmarkManager.INSTANCE.getBookmark(category, bookmarkIndex)); } @Override public void onMyPositionActivated(final double lat, final double lon) { final MapObject mypos = new MapObject.MyPosition(lat, lon); runOnUiThread(new Runnable() { @Override public void run() { if (!Framework.nativeIsRoutingActive()) { activateMapObject(mypos); } } }); } @Override public void onAdditionalLayerActivated(final String name, final String type, final double lat, final double lon, final int[] metaTypes, final String[] metaValues) { final MapObject sr = new MapObject.SearchResult(name, type, lat, lon); sr.addMetadata(metaTypes, metaValues); activateMapObject(sr); } private void activateMapObject(MapObject object) { setFullscreen(false); if (!mPlacePage.hasMapObject(object)) { mPlacePage.setMapObject(object); mPlacePage.setState(State.PREVIEW); if (UiUtils.isVisible(mFadeView)) mFadeView.fadeOut(false); } } @Override public void onDismiss() { if (!mPlacePage.hasMapObject(null)) mPlacePage.hide(); else { if ((mPanelAnimator != null && mPanelAnimator.isVisible()) || UiUtils.isVisible(mSearchController.getToolbar())) return; setFullscreen(!mIsFullscreen); } } private void setFullscreen(boolean isFullscreen) { mIsFullscreen = isFullscreen; if (isFullscreen) { Animations.disappearSliding(mMainMenu.getFrame(), Animations.BOTTOM, new Runnable() { @Override public void run() { final int menuHeight = mMainMenu.getFrame().getHeight(); adjustCompass(0, menuHeight); adjustRuler(0, menuHeight); } }); if (showZoomButtons()) { Animations.disappearSliding(mBtnZoomOut, Animations.RIGHT, null); Animations.disappearSliding(mBtnZoomIn, Animations.RIGHT, null); } } else { Animations.appearSliding(mMainMenu.getFrame(), Animations.BOTTOM, new Runnable() { @Override public void run() { adjustCompass(0, 0); adjustRuler(0, 0); } }); if (showZoomButtons()) { Animations.appearSliding(mBtnZoomOut, Animations.RIGHT, null); Animations.appearSliding(mBtnZoomIn, Animations.RIGHT, null); } } } @Override public void onPreviewVisibilityChanged(boolean isVisible) { if (!isVisible) { Framework.deactivatePopup(); mPlacePage.setMapObject(null); mMainMenu.show(true); } } @Override public void onPlacePageVisibilityChanged(boolean isVisible) { Statistics.INSTANCE.trackEvent(isVisible ? Statistics.EventName.PP_OPEN : Statistics.EventName.PP_CLOSE); AlohaHelper.logClick(isVisible ? AlohaHelper.PP_OPEN : AlohaHelper.PP_CLOSE); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.ll__route: startLocationToPoint(Statistics.EventName.PP_ROUTE, AlohaHelper.PP_ROUTE, mPlacePage.getMapObject()); break; case R.id.map_button_plus: Statistics.INSTANCE.trackEvent(Statistics.EventName.ZOOM_IN); AlohaHelper.logClick(AlohaHelper.ZOOM_IN); MapFragment.nativeScalePlus(); break; case R.id.map_button_minus: Statistics.INSTANCE.trackEvent(Statistics.EventName.ZOOM_OUT); AlohaHelper.logClick(AlohaHelper.ZOOM_OUT); MapFragment.nativeScaleMinus(); break; } } @Override public boolean onTouch(View view, MotionEvent event) { return mPlacePage.hideOnTouch() || mMapFragment.onTouch(view, event); } @Override public void customOnNavigateUp() { if (removeCurrentFragment(true)) { InputUtils.hideKeyboard(mMainMenu.getFrame()); mSearchController.refreshToolbar(); } } public interface MapTask extends Serializable { boolean run(MwmActivity target); } public static class OpenUrlTask implements MapTask { private static final long serialVersionUID = 1L; private final String mUrl; public OpenUrlTask(String url) { Utils.checkNotNull(url); mUrl = url; } @Override public boolean run(MwmActivity target) { return MapFragment.nativeShowMapForUrl(mUrl); } } public static class ShowCountryTask implements MapTask { private static final long serialVersionUID = 1L; private final Index mIndex; private final boolean mDoAutoDownload; public ShowCountryTask(Index index, boolean doAutoDownload) { mIndex = index; mDoAutoDownload = doAutoDownload; } @Override public boolean run(MwmActivity target) { if (mDoAutoDownload) Framework.downloadCountry(mIndex); Framework.nativeShowCountry(mIndex, mDoAutoDownload); return true; } } public void adjustCompass(int offsetX, int offsetY) { if (mMapFragment == null || !mMapFragment.isAdded()) return; mMapFragment.setupCompass((mPanelAnimator != null && mPanelAnimator.isVisible()) ? offsetX : 0, offsetY, true); if (mLastCompassData != null) MapFragment.nativeCompassUpdated(mLastCompassData.magneticNorth, mLastCompassData.trueNorth, true); } public void adjustRuler(int offsetX, int offsetY) { if (mMapFragment == null || !mMapFragment.isAdded()) return; mMapFragment.setupRuler(offsetX, offsetY, true); } @Override public void onCategoryChanged(int bookmarkId, int newCategoryId) { mPlacePage.setMapObject(BookmarkManager.INSTANCE.getBookmark(newCategoryId, bookmarkId)); } @Override public FragmentActivity getActivity() { return this; } public MainMenu getMainMenu() { return mMainMenu; } @Override public void showSearch() { showSearch(""); } @Override public void updateMenu() { if (RoutingController.get().isNavigating()) { mMainMenu.setState(MainMenu.State.NAVIGATION, false); return; } if (mIsFragmentContainer) { mMainMenu.setEnabled(MainMenu.Item.P2P, !RoutingController.get().isPlanning()); mMainMenu.setEnabled(MainMenu.Item.SEARCH, !RoutingController.get().isWaitingPoiPick()); } else if (RoutingController.get().isPlanning()) { mMainMenu.setState(MainMenu.State.ROUTE_PREPARE, false); return; } mMainMenu.setState(MainMenu.State.MENU, false); } @Override public void showRoutePlan(boolean show, @Nullable Runnable completionListener) { if (show) { mSearchController.hide(); if (mIsFragmentContainer) { replaceFragment(RoutingPlanFragment.class, null, completionListener); } else { mRoutingPlanInplaceController.show(true); if (completionListener != null) completionListener.run(); } } else { if (mIsFragmentContainer) closeSidePanel(); else mRoutingPlanInplaceController.show(false); if (completionListener != null) completionListener.run(); } mPlacePage.refreshViews(); } @Override public void showNavigation(boolean show) { adjustZoomButtons(); mPlacePage.refreshViews(); mNavigationController.show(show); } @Override public void updatePoints() { if (mIsFragmentContainer) { RoutingPlanFragment fragment = (RoutingPlanFragment)getFragment(RoutingPlanFragment.class); if (fragment != null) fragment.updatePoints(); } else { mRoutingPlanInplaceController.updatePoints(); } } @Override public void updateBuildProgress(int progress, int router) { if (mIsFragmentContainer) { RoutingPlanFragment fragment = (RoutingPlanFragment)getFragment(RoutingPlanFragment.class); if (fragment != null) fragment.updateBuildProgress(progress, router); } else { mRoutingPlanInplaceController.updateBuildProgress(progress, router); } } }
package info.tregmine.lookup; import java.io.IOException; import java.net.InetSocketAddress; //import org.bukkit.ChatColor; import org.bukkit.ChatColor; import org.bukkit.entity.Player; //import org.bukkit.event.player.PlayerEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerListener; import com.maxmind.geoip.Location; import com.maxmind.geoip.LookupService; public class LookupPlayer extends PlayerListener { private final Lookup plugin; private LookupService cl = null; public LookupPlayer(Lookup instance) { plugin = instance; try { cl = new LookupService("/home/minecraft/minecraft/GeoIPCity.dat", LookupService.GEOIP_MEMORY_CACHE ); } catch (IOException e) { throw new RuntimeException(e); } } public void onPlayerJoin(PlayerJoinEvent event) { Player player = event.getPlayer(); InetSocketAddress sock = player.getAddress(); String ip = sock.getAddress().getHostAddress(); String host = sock.getAddress().getCanonicalHostName(); info.tregmine.api.TregminePlayer tregminePlayer = this.plugin.tregmine.tregminePlayer.get(player.getName()); if (cl != null) { Location l1 = cl.getLocation(ip); plugin.log.info(event.getPlayer().getName() + ": " + l1.countryName + ", " + l1.city + ", " + ip + ", " + l1.postalCode + ", " + l1.region + ", " + host); tregminePlayer.setMetaString("countryName", l1.countryName); tregminePlayer.setMetaString("city", l1.city); tregminePlayer.setMetaString("ip", ip); tregminePlayer.setMetaString("postalCode", l1.postalCode); tregminePlayer.setMetaString("region", l1.region); tregminePlayer.setMetaString("hostname", host); if(!event.getPlayer().getName().matches("einand") && !event.getPlayer().getName().matches("mejjad")) { this.plugin.getServer().broadcastMessage(ChatColor.DARK_AQUA + "Welcome! " + tregminePlayer.getChatName() + ChatColor.DARK_AQUA + " from " +l1.countryName); event.getPlayer().sendMessage(ChatColor.DARK_AQUA + l1.city + " - " + l1.postalCode); } else { event.getPlayer().sendMessage("Version 1"); event.getPlayer().setPlayerListName("DuckHunt2"); } } } }
package nordpol.android; import android.nfc.Tag; import android.nfc.NfcAdapter; import android.nfc.tech.IsoDep; import android.annotation.TargetApi; import android.app.Activity; import android.app.PendingIntent; import android.content.Intent; import android.content.IntentFilter; import android.os.Build; import android.os.Bundle; public class TagDispatcher { private static final int DELAY_PRESENCE = 5000; private OnDiscoveredTagListener listener; private Activity activity; private TagDispatcher(Activity activity, OnDiscoveredTagListener listener) { this.activity = activity; this.listener = listener; } public static TagDispatcher get(Activity activity, OnDiscoveredTagListener listener) { return new TagDispatcher(activity, listener); } /** Enable exclusive NFC access for the given activity. * Using this method makes NFC intent filters in the AndroidManifest.xml redundant. * @returns true if NFC was available and false if no NFC is available * on device. */ @TargetApi(Build.VERSION_CODES.KITKAT) public boolean enableExclusiveNfc() { NfcAdapter adapter = NfcAdapter.getDefaultAdapter(activity); if (adapter != null) { if (!adapter.isEnabled()) { activity.startActivity(new Intent( android.provider.Settings.ACTION_NFC_SETTINGS)); return false; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { enableReaderMode(adapter); } else { enableForegroundDispatch(adapter); } return true; } return false; } /** Disable exclusive NFC access for the given activity. * @returns true if NFC was available and false if no NFC is available * on device. */ @TargetApi(Build.VERSION_CODES.KITKAT) public boolean disableExclusiveNfc() { NfcAdapter adapter = NfcAdapter.getDefaultAdapter(activity); if (adapter != null) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { disableReaderMode(adapter); } else { disableForegroundDispatch(adapter); } return true; } return false; } public boolean interceptIntent(Intent intent) { Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); if(tag != null) { listener.tagDiscovered(tag); return true; } else { return false; } } @TargetApi(Build.VERSION_CODES.KITKAT) private void enableReaderMode(NfcAdapter adapter) { Bundle options = new Bundle(); /* This is a work around for some Broadcom chipsets that does * the presence check by sending commands that interrupt the * processing of the ongoing command. */ options.putInt(NfcAdapter.EXTRA_READER_PRESENCE_CHECK_DELAY, DELAY_PRESENCE); NfcAdapter.ReaderCallback callback = new NfcAdapter.ReaderCallback() { public void onTagDiscovered(Tag tag) { listener.tagDiscovered(tag); } }; adapter.enableReaderMode(activity, callback, NfcAdapter.FLAG_READER_NFC_A | NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK | NfcAdapter.FLAG_READER_NO_PLATFORM_SOUNDS, options); } @TargetApi(Build.VERSION_CODES.KITKAT) private void disableReaderMode(NfcAdapter adapter) { adapter.disableReaderMode(activity); } private void enableForegroundDispatch(NfcAdapter adapter) { Intent intent = new Intent(activity, activity.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); enableForegroundDispatch(adapter, intent); } private void enableForegroundDispatch(NfcAdapter adapter, Intent intent) { if(adapter.isEnabled()) { PendingIntent tagIntent = PendingIntent.getActivity(activity, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT); IntentFilter tag = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED); adapter.enableForegroundDispatch(activity, tagIntent, new IntentFilter[]{tag}, new String[][]{new String[]{IsoDep.class.getName()}}); } } private void disableForegroundDispatch(NfcAdapter adapter) { adapter.disableForegroundDispatch(activity); } }
package net.katsuster.ememu.generic; /** * SD Card * * : SD Specifications Part 1 Physical Layer * Simplified Specification Version 6.00 * August 29, 2018 */ public class SDCard extends AbstractParentCore { public static final int REG_IO = 0x00; private SDCardState st; private int blockAddr; private int blockLen; public SDCard(String n) { super(n); setSlaveCore(new SDCardSlave()); st = new CmdState(); } class SDCardState { public SDCardState() { } public int readData() { return 0; } public void writeData(int b) { } } class CmdStateCommon extends SDCardState { protected int cmd = 0; protected int arg = 0; protected int crc = 0; protected int resp = 0xff; protected int pos = 0; public CmdStateCommon() { } public void reset() { cmd = 0; arg = 0; crc = 0; resp = 0xff; pos = 0; } public void recvCommand() { int[] dat; //Do not support dat = new int[1]; dat[0] = 0x3; st = new RespState(dat, new CmdState()); } @Override public int readData() { return resp; } @Override public void writeData(int b) { if (pos == 0 && b == 0xff) { resp = 0xff; return; } resp = 0xff; switch (pos) { case 0: cmd = b & 0x3f; break; case 1: arg |= (b & 0xff) << 24; break; case 2: arg |= (b & 0xff) << 16; break; case 3: arg |= (b & 0xff) << 8; break; case 4: arg |= b & 0xff; break; case 5: crc = b >> 1; break; case 7: recvCommand(); break; } pos++; } } class CmdState extends CmdStateCommon { public CmdState() { } @Override public void recvCommand() { int[] dat; switch (cmd) { case 0x00: //CMD 0: GO_IDLE_STATE dat = new int[1]; dat[0] = 0x1; st = new RespState(dat, new CmdState()); break; case 0x08: //CMD 8: SEND_EXT_CSD dat = new int[5]; dat[0] = 0x01; dat[1] = 0x00; dat[2] = 0x00; //voltage accepted: 2.6-3.7V dat[3] = 0x01; //echo back dat[4] = arg & 0xff; st = new RespState(dat, new CmdState()); break; case 0x10: //CMD 16: SET_BLOCKLEN System.out.printf("CMD16: len 0x%x\n", arg); blockLen = arg; dat = new int[1]; dat[0] = 0x00; st = new RespState(dat, new CmdState()); break; case 0x12: //CMD 18: READ_MULTIPLE_BLOCK System.out.printf("CMD18: addr 0x%x\n", arg); blockAddr = arg; dat = new int[1]; dat[0] = 0x01; st = new RespState(dat, new CmdState()); break; case 0x37: //CMD 55: APP_CMD dat = new int[1]; dat[0] = 0x1; st = new RespState(dat, new AcmdState()); break; default: //Do not support super.recvCommand(); break; } } } class AcmdState extends CmdStateCommon { public AcmdState() { } @Override public void recvCommand() { int[] dat; switch (cmd) { case 0x29: //ACMD 41: SD_SEND_OP_COND int hsc = BitOp.getField32(arg, 30, 1); int xpc = BitOp.getField32(arg, 28, 1); int s18r = BitOp.getField32(arg, 24, 1); int ocr = BitOp.getField32(arg, 8, 16); System.out.printf("ACMD41: arg 0x%x\n" + " %s: 0x%x, \n" + " %s: 0x%x, \n" + " %s: 0x%x, \n" + " %s: 0x%x, \n", arg, "hsc", hsc, "xpc", xpc, "s18r", s18r, "ocr", ocr); dat = new int[1]; dat[0] = 0x00; st = new RespState(dat, new CmdState()); break; default: //Do not support super.recvCommand(); break; } } } class RespState extends SDCardState { private int[] resp; private SDCardState nextState; private int pos; public RespState(int[] r, SDCardState n) { resp = r; nextState = n; pos = 0; } @Override public int readData() { if (pos >= resp.length) { st = nextState; return 0xff; } else { int result = resp[pos]; pos++; return result; } } @Override public void writeData(int b) { } } class SDCardSlave extends Controller32 { public SDCardSlave() { addReg(REG_IO, "IO", 0x00000000); } @Override public int readWord(BusMaster64 m, long addr) { int result = st.readData() & 0xff; return result; } @Override public void writeWord(BusMaster64 m, long addr, int data) { st.writeData(data & 0xff); } } }
package net.argius.stew.ui.window; import static java.awt.EventQueue.invokeLater; import static java.awt.event.InputEvent.ALT_DOWN_MASK; import static java.awt.event.InputEvent.SHIFT_DOWN_MASK; import static java.awt.event.KeyEvent.VK_C; import static java.util.Collections.emptyList; import static java.util.Collections.nCopies; import static javax.swing.KeyStroke.getKeyStroke; import static net.argius.stew.text.TextUtilities.join; import static net.argius.stew.ui.window.AnyActionKey.copy; import static net.argius.stew.ui.window.AnyActionKey.refresh; import static net.argius.stew.ui.window.DatabaseInfoTree.ActionKey.*; import static net.argius.stew.ui.window.WindowOutputProcessor.showInformationMessageDialog; import java.awt.*; import java.awt.event.*; import java.io.*; import java.sql.*; import java.util.*; import java.util.Map.Entry; import java.util.List; import javax.swing.*; import javax.swing.event.*; import javax.swing.tree.*; import net.argius.stew.*; /** * The Database Information Tree is a tree pane that provides to * display database object information from DatabaseMetaData. */ final class DatabaseInfoTree extends JTree implements AnyActionListener, TextSearch { enum ActionKey { copySimpleName, copyFullName, generateWherePhrase, generateSelectPhrase, generateUpdateStatement, generateInsertStatement, jumpToColumnByName, toggleShowColumnNumber } private static final Logger log = Logger.getLogger(DatabaseInfoTree.class); private static final ResourceManager res = ResourceManager.getInstance(DatabaseInfoTree.class); static volatile boolean showColumnNumber; private Connector currentConnector; private DatabaseMetaData dbmeta; private AnyActionListener anyActionListener; DatabaseInfoTree(AnyActionListener anyActionListener) { this.anyActionListener = anyActionListener; setRootVisible(false); setShowsRootHandles(false); setScrollsOnExpand(true); setCellRenderer(new Renderer()); setModel(new DefaultTreeModel(null)); // [Events] int sckm = Utilities.getMenuShortcutKeyMask(); AnyAction aa = new AnyAction(this); aa.bindKeyStroke(false, copy, KeyStroke.getKeyStroke(VK_C, sckm)); aa.bindSelf(copySimpleName, getKeyStroke(VK_C, sckm | ALT_DOWN_MASK)); aa.bindSelf(copyFullName, getKeyStroke(VK_C, sckm | SHIFT_DOWN_MASK)); } @Override protected void processMouseEvent(MouseEvent e) { super.processMouseEvent(e); if (e.getID() == MouseEvent.MOUSE_CLICKED && e.getClickCount() % 2 == 0) { anyActionPerformed(new AnyActionEvent(this, jumpToColumnByName)); } } @Override public void anyActionPerformed(AnyActionEvent ev) { log.atEnter("anyActionPerformed", ev); if (ev.isAnyOf(copySimpleName)) { copySimpleName(); } else if (ev.isAnyOf(copyFullName)) { copyFullName(); } else if (ev.isAnyOf(refresh)) { for (TreePath path : getSelectionPaths()) { refresh((InfoNode)path.getLastPathComponent()); } } else if (ev.isAnyOf(generateWherePhrase)) { generateWherePhrase(); } else if (ev.isAnyOf(generateSelectPhrase)) { generateSelectPhrase(); } else if (ev.isAnyOf(generateUpdateStatement)) { generateUpdateStatement(); } else if (ev.isAnyOf(generateInsertStatement)) { generateInsertStatement(); } else if (ev.isAnyOf(jumpToColumnByName)) { jumpToColumnByName(); } else if (ev.isAnyOf(toggleShowColumnNumber)) { showColumnNumber = !showColumnNumber; repaint(); } else { log.warn("not expected: Event=%s", ev); } log.atExit("anyActionPerformed"); } private void insertTextToTextArea(String s) { AnyActionEvent ev = new AnyActionEvent(this, ConsoleTextArea.ActionKey.insertText, s); anyActionListener.anyActionPerformed(ev); } private void copySimpleName() { TreePath[] paths = getSelectionPaths(); if (paths == null || paths.length == 0) { return; } List<String> names = new ArrayList<String>(paths.length); for (TreePath path : paths) { if (path == null) { continue; } Object o = path.getLastPathComponent(); assert o instanceof InfoNode; final String name; if (o instanceof ColumnNode) { name = ((ColumnNode)o).getName(); } else if (o instanceof TableNode) { name = ((TableNode)o).getName(); } else { name = o.toString(); } names.add(name); } ClipboardHelper.setStrings(names); } private void copyFullName() { TreePath[] paths = getSelectionPaths(); if (paths == null || paths.length == 0) { return; } List<String> names = new ArrayList<String>(paths.length); for (TreePath path : paths) { if (path == null) { continue; } Object o = path.getLastPathComponent(); assert o instanceof InfoNode; names.add(((InfoNode)o).getNodeFullName()); } ClipboardHelper.setStrings(names); } private void generateWherePhrase() { List<ColumnNode> columns = collectColumnNode(getSelectionPaths()); if (!columns.isEmpty()) { insertTextToTextArea(generateEquivalentJoinClause(columns)); } } private void generateSelectPhrase() { TreePath[] paths = getSelectionPaths(); List<ColumnNode> columns = collectColumnNode(paths); final String columnString; final List<String> tableNames; if (columns.isEmpty()) { List<TableNode> tableNodes = collectTableNode(paths); if (tableNodes.isEmpty()) { return; } tableNames = new ArrayList<String>(); for (final TableNode tableNode : tableNodes) { tableNames.add(tableNode.getNodeFullName()); } columnString = "*"; } else { List<String> columnNames = new ArrayList<String>(); tableNames = collectTableName(columns); final boolean one = tableNames.size() == 1; for (ColumnNode node : columns) { columnNames.add(one ? node.getName() : node.getNodeFullName()); } columnString = join(", ", columnNames); } final String tableString = join(",", tableNames); insertTextToTextArea(String.format("SELECT %s FROM %s WHERE ", columnString, tableString)); } private void generateUpdateStatement() { TreePath[] paths = getSelectionPaths(); List<ColumnNode> columns = collectColumnNode(paths); if (columns.isEmpty()) { return; } List<String> tableNamesOfColumns = collectTableName(columns); if (collectTableNode(paths).size() > 1) { showInformationMessageDialog(this, res.get("e.enables-select-just-1-table"), ""); return; } List<String> columnExpressions = new ArrayList<String>(); for (ColumnNode columnNode : columns) { columnExpressions.add(columnNode.getName() + "=?"); } insertTextToTextArea(String.format("UPDATE %s SET %s WHERE ", tableNamesOfColumns.get(0), join(",", columnExpressions))); } private void generateInsertStatement() { TreePath[] paths = getSelectionPaths(); List<ColumnNode> columns = collectColumnNode(paths); final String tableName; final int tableCount; if (columns.isEmpty()) { List<TableNode> tables = collectTableNode(paths); if (tables.isEmpty()) { return; } TableNode tableNode = tables.get(0); if (tableNode.getChildCount() == 0) { showInformationMessageDialog(this, res.get("i.can-only-use-after-tablenode-expanded"), ""); return; } @SuppressWarnings("unchecked") List<ColumnNode> list = Collections.list(tableNode.children()); columns.addAll(list); tableName = tableNode.getNodeFullName(); tableCount = tables.size(); } else { List<String> tableNames = collectTableName(columns); tableCount = tableNames.size(); if (tableCount == 0) { return; } tableName = tableNames.get(0); } if (tableCount != 1) { showInformationMessageDialog(this, res.get("e.enables-select-just-1-table"), ""); return; } List<String> columnNames = new ArrayList<String>(); for (ColumnNode node : columns) { columnNames.add(node.getName()); } final int columnCount = columnNames.size(); insertTextToTextArea(String.format("INSERT INTO %s (%s) VALUES (%s);%s", tableName, join(",", columnNames), join(",", nCopies(columnCount, "?")), join(",", nCopies(columnCount, "")))); } private void jumpToColumnByName() { TreePath[] paths = getSelectionPaths(); if (paths == null || paths.length == 0) { return; } final TreePath path = paths[0]; Object o = path.getLastPathComponent(); if (o instanceof ColumnNode) { ColumnNode node = (ColumnNode)o; AnyActionEvent ev = new AnyActionEvent(this, ResultSetTable.ActionKey.jumpToColumn, node.getName()); anyActionListener.anyActionPerformed(ev); } } private static List<ColumnNode> collectColumnNode(TreePath[] paths) { List<ColumnNode> a = new ArrayList<ColumnNode>(); if (paths != null) { for (TreePath path : paths) { InfoNode node = (InfoNode)path.getLastPathComponent(); if (node instanceof ColumnNode) { ColumnNode columnNode = (ColumnNode)node; a.add(columnNode); } } } return a; } private static List<TableNode> collectTableNode(TreePath[] paths) { List<TableNode> a = new ArrayList<TableNode>(); if (paths != null) { for (TreePath path : paths) { InfoNode node = (InfoNode)path.getLastPathComponent(); if (node instanceof TableNode) { TableNode columnNode = (TableNode)node; a.add(columnNode); } } } return a; } private static List<String> collectTableName(List<ColumnNode> columnNodes) { Set<String> tableNames = new LinkedHashSet<String>(); for (final ColumnNode node : columnNodes) { tableNames.add(node.getTableNode().getNodeFullName()); } return new ArrayList<String>(tableNames); } static String generateEquivalentJoinClause(List<ColumnNode> nodes) { if (nodes.isEmpty()) { return ""; } ListMap tm = new ListMap(); ListMap cm = new ListMap(); for (ColumnNode node : nodes) { final String tableName = node.getTableNode().getName(); final String columnName = node.getName(); tm.add(tableName, columnName); cm.add(columnName, String.format("%s.%s", tableName, columnName)); } List<String> expressions = new ArrayList<String>(); if (tm.size() == 1) { for (ColumnNode node : nodes) { expressions.add(String.format("%s=?", node.getName())); } } else { final String tableName = nodes.get(0).getTableNode().getName(); for (String c : tm.get(tableName)) { expressions.add(String.format("%s.%s=?", tableName, c)); } for (Entry<String, List<String>> entry : cm.entrySet()) { if (!entry.getKey().equals(tableName) && entry.getValue().size() == 1) { expressions.add(String.format("%s=?", entry.getValue().get(0))); } } for (Entry<String, List<String>> entry : cm.entrySet()) { Object[] a = entry.getValue().toArray(); final int n = a.length; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { expressions.add(String.format("%s=%s", a[i], a[j])); } } } } return join(" AND ", expressions) + ';'; } // text-search @Override public boolean search(Matcher matcher) { return search(resolveTargetPath(getSelectionPath()), matcher); } private static TreePath resolveTargetPath(TreePath path) { if (path != null) { TreePath parent = path.getParentPath(); if (parent != null) { return parent; } } return path; } private boolean search(TreePath path, Matcher matcher) { if (path == null) { return false; } TreeNode node = (TreeNode)path.getLastPathComponent(); if (node == null) { return false; } boolean found = false; found = matcher.find(node.toString()); if (found) { addSelectionPath(path); } else { removeSelectionPath(path); } if (!node.isLeaf() && node.getChildCount() >= 0) { @SuppressWarnings("unchecked") Iterable<DefaultMutableTreeNode> children = Collections.list(node.children()); for (DefaultMutableTreeNode child : children) { if (search(path.pathByAddingChild(child), matcher)) { found = true; } } } return found; } @Override public void reset() { // empty } // node expansion /** * Refreshes the root and its children. * @param env Environment * @throws SQLException */ void refreshRoot(Environment env) throws SQLException { Connector c = env.getCurrentConnector(); if (c == null) { if (log.isDebugEnabled()) { log.debug("not connected"); } currentConnector = null; return; } if (c == currentConnector && getModel().getRoot() != null) { if (log.isDebugEnabled()) { log.debug("not changed"); } return; } if (log.isDebugEnabled()) { log.debug("updating"); } // initializing models ConnectorNode connectorNode = new ConnectorNode(c.getName()); DefaultTreeModel model = new DefaultTreeModel(connectorNode); setModel(model); final DefaultTreeSelectionModel m = new DefaultTreeSelectionModel(); m.setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION); setSelectionModel(m); // initializing nodes final DatabaseMetaData dbmeta = env.getCurrentConnection().getMetaData(); final Set<InfoNode> createdStatusSet = new HashSet<InfoNode>(); expandNode(connectorNode, dbmeta); createdStatusSet.add(connectorNode); // events addTreeWillExpandListener(new TreeWillExpandListener() { @Override public void treeWillExpand(TreeExpansionEvent event) throws ExpandVetoException { TreePath path = event.getPath(); final Object lastPathComponent = path.getLastPathComponent(); if (!createdStatusSet.contains(lastPathComponent)) { InfoNode node = (InfoNode)lastPathComponent; if (node.isLeaf()) { return; } createdStatusSet.add(node); try { expandNode(node, dbmeta); } catch (SQLException ex) { throw new RuntimeException(ex); } } } @Override public void treeWillCollapse(TreeExpansionEvent event) throws ExpandVetoException { // ignore } }); this.dbmeta = dbmeta; // showing model.reload(); setRootVisible(true); this.currentConnector = c; // auto-expansion try { File confFile = Bootstrap.getSystemFile("autoexpansion.tsv"); if (confFile.exists() && confFile.length() > 0) { AnyAction aa = new AnyAction(this); Scanner r = new Scanner(confFile); try { while (r.hasNextLine()) { final String line = r.nextLine(); if (line.matches("^\\s* continue; } aa.doParallel("expandNodes", Arrays.asList(line.split("\t"))); } } finally { r.close(); } } } catch (IOException ex) { throw new IllegalStateException(ex); } } void expandNodes(List<String> a) { long startTime = System.currentTimeMillis(); AnyAction aa = new AnyAction(this); int index = 1; while (index < a.size()) { final String s = a.subList(0, index + 1).toString(); for (int i = 0, n = getRowCount(); i < n; i++) { TreePath target; try { target = getPathForRow(i); } catch (IndexOutOfBoundsException ex) { // FIXME when IndexOutOfBoundsException was thrown at expandNodes log.warn(ex); break; } if (target != null && target.toString().equals(s)) { if (!isExpanded(target)) { aa.doLater("expandLater", target); Utilities.sleep(200L); } index++; break; } } if (System.currentTimeMillis() - startTime > 5000L) { break; // timeout } } } // called by expandNodes @SuppressWarnings("unused") private void expandLater(TreePath parent) { expandPath(parent); } /** * Refreshes a node and its children. * @param node */ void refresh(InfoNode node) { if (dbmeta == null) { return; } node.removeAllChildren(); final DefaultTreeModel model = (DefaultTreeModel)getModel(); model.reload(node); try { expandNode(node, dbmeta); } catch (SQLException ex) { throw new RuntimeException(ex); } } /** * Expands a node. * @param parent * @param dbmeta * @throws SQLException */ void expandNode(final InfoNode parent, final DatabaseMetaData dbmeta) throws SQLException { if (parent.isLeaf()) { return; } final DefaultTreeModel model = (DefaultTreeModel)getModel(); final InfoNode tmpNode = new InfoNode(res.get("i.paren-in-processing")) { @Override protected List<InfoNode> createChildren(DatabaseMetaData dbmeta) throws SQLException { return Collections.emptyList(); } @Override public boolean isLeaf() { return true; } }; invokeLater(new Runnable() { @Override public void run() { model.insertNodeInto(tmpNode, parent, 0); } }); // asynchronous DaemonThreadFactory.execute(new Runnable() { @Override public void run() { try { final List<InfoNode> children = new ArrayList<InfoNode>(parent.createChildren(dbmeta)); invokeLater(new Runnable() { @Override public void run() { for (InfoNode child : children) { model.insertNodeInto(child, parent, parent.getChildCount()); } model.removeNodeFromParent(tmpNode); } }); } catch (SQLException ex) { throw new RuntimeException(ex); } } }); } /** * Clears (root). */ void clear() { for (TreeWillExpandListener listener : getListeners(TreeWillExpandListener.class).clone()) { removeTreeWillExpandListener(listener); } setModel(new DefaultTreeModel(null)); currentConnector = null; dbmeta = null; if (log.isDebugEnabled()) { log.debug("cleared"); } } @Override public TreePath[] getSelectionPaths() { TreePath[] a = super.getSelectionPaths(); if (a == null) { return new TreePath[0]; } return a; } // subclasses private static final class ListMap extends LinkedHashMap<String, List<String>> { ListMap() { // empty } void add(String key, String value) { if (get(key) == null) { put(key, new ArrayList<String>()); } get(key).add(value); } } private static class Renderer extends DefaultTreeCellRenderer { Renderer() { // empty } @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); if (value instanceof InfoNode) { setIcon(Utilities.getImageIcon(((InfoNode)value).getIconName())); } if (value instanceof ColumnNode) { if (showColumnNumber) { TreePath path = tree.getPathForRow(row); if (path != null) { TreePath parent = path.getParentPath(); if (parent != null) { final int index = row - tree.getRowForPath(parent); setText(String.format("%d %s", index, getText())); } } } } return this; } } private abstract static class InfoNode extends DefaultMutableTreeNode { InfoNode(Object userObject) { super(userObject, true); } @Override public boolean isLeaf() { return false; } abstract protected List<InfoNode> createChildren(DatabaseMetaData dbmeta) throws SQLException; String getIconName() { final String className = getClass().getName(); final String nodeType = className.replaceFirst(".+?([^\\$]+)Node$", "$1"); return "node-" + nodeType.toLowerCase() + ".png"; } protected String getNodeFullName() { return String.valueOf(userObject); } static List<TableTypeNode> getTableTypeNodes(DatabaseMetaData dbmeta, String catalog, String schema) throws SQLException { List<TableTypeNode> a = new ArrayList<TableTypeNode>(); ResultSet rs = dbmeta.getTableTypes(); try { while (rs.next()) { TableTypeNode typeNode = new TableTypeNode(catalog, schema, rs.getString(1)); if (typeNode.hasItems(dbmeta)) { a.add(typeNode); } } } finally { rs.close(); } if (a.isEmpty()) { a.add(new TableTypeNode(catalog, schema, "TABLE")); } return a; } } private static class ConnectorNode extends InfoNode { ConnectorNode(String name) { super(name); } @Override protected List<InfoNode> createChildren(DatabaseMetaData dbmeta) throws SQLException { List<InfoNode> a = new ArrayList<InfoNode>(); if (dbmeta.supportsCatalogsInDataManipulation()) { ResultSet rs = dbmeta.getCatalogs(); try { while (rs.next()) { a.add(new CatalogNode(rs.getString(1))); } } finally { rs.close(); } } else if (dbmeta.supportsSchemasInDataManipulation()) { ResultSet rs = dbmeta.getSchemas(); try { while (rs.next()) { a.add(new SchemaNode(null, rs.getString(1))); } } finally { rs.close(); } } else { a.addAll(getTableTypeNodes(dbmeta, null, null)); } return a; } } private static final class CatalogNode extends InfoNode { private final String name; CatalogNode(String name) { super(name); this.name = name; } @Override protected List<InfoNode> createChildren(DatabaseMetaData dbmeta) throws SQLException { List<InfoNode> a = new ArrayList<InfoNode>(); if (dbmeta.supportsSchemasInDataManipulation()) { ResultSet rs = dbmeta.getSchemas(); try { while (rs.next()) { a.add(new SchemaNode(name, rs.getString(1))); } } finally { rs.close(); } } else { a.addAll(getTableTypeNodes(dbmeta, name, null)); } return a; } } private static final class SchemaNode extends InfoNode { private final String catalog; private final String schema; SchemaNode(String catalog, String schema) { super(schema); this.catalog = catalog; this.schema = schema; } @Override protected List<InfoNode> createChildren(DatabaseMetaData dbmeta) throws SQLException { List<InfoNode> a = new ArrayList<InfoNode>(); a.addAll(getTableTypeNodes(dbmeta, catalog, schema)); return a; } } private static final class TableTypeNode extends InfoNode { private static final String ICON_NAME_FORMAT = "node-tabletype-%s.png"; private final String catalog; private final String schema; private final String tableType; TableTypeNode(String catalog, String schema, String tableType) { super(tableType); this.catalog = catalog; this.schema = schema; this.tableType = tableType; } @Override protected List<InfoNode> createChildren(DatabaseMetaData dbmeta) throws SQLException { List<InfoNode> a = new ArrayList<InfoNode>(); ResultSet rs = dbmeta.getTables(catalog, schema, null, new String[]{tableType}); try { while (rs.next()) { final String table = rs.getString(3); final String type = rs.getString(4); final boolean kindOfTable = type.matches("TABLE|VIEW|SYNONYM"); a.add(new TableNode(catalog, schema, table, kindOfTable)); } } finally { rs.close(); } return a; } @Override String getIconName() { final String name = String.format(ICON_NAME_FORMAT, getUserObject()); if (getClass().getResource("icon/" + name) == null) { return String.format(ICON_NAME_FORMAT, ""); } return name; } boolean hasItems(DatabaseMetaData dbmeta) throws SQLException { ResultSet rs = dbmeta.getTables(catalog, schema, null, new String[]{tableType}); try { return rs.next(); } finally { rs.close(); } } } static final class TableNode extends InfoNode { private final String catalog; private final String schema; private final String name; private final boolean kindOfTable; TableNode(String catalog, String schema, String name, boolean kindOfTable) { super(name); this.catalog = catalog; this.schema = schema; this.name = name; this.kindOfTable = kindOfTable; } @Override protected List<InfoNode> createChildren(DatabaseMetaData dbmeta) throws SQLException { List<InfoNode> a = new ArrayList<InfoNode>(); ResultSet rs = dbmeta.getColumns(catalog, schema, name, null); try { while (rs.next()) { a.add(new ColumnNode(rs.getString(4), rs.getString(6), rs.getInt(7), rs.getString(18), this)); } } finally { rs.close(); } return a; } @Override public boolean isLeaf() { return false; } @Override protected String getNodeFullName() { List<String> a = new ArrayList<String>(); if (catalog != null) { a.add(catalog); } if (schema != null) { a.add(schema); } a.add(name); return join(".", a); } String getName() { return name; } boolean isKindOfTable() { return kindOfTable; } } static final class ColumnNode extends InfoNode { private final String name; private final TableNode tableNode; ColumnNode(String name, String type, int size, String nulls, TableNode tableNode) { super(format(name, type, size, nulls)); setAllowsChildren(false); this.name = name; this.tableNode = tableNode; } String getName() { return name; } TableNode getTableNode() { return tableNode; } private static String format(String name, String type, int size, String nulls) { final String nonNull = "NO".equals(nulls) ? " NOT NULL" : ""; return String.format("%s [%s(%d)%s]", name, type, size, nonNull); } @Override public boolean isLeaf() { return true; } @Override protected List<InfoNode> createChildren(DatabaseMetaData dbmeta) throws SQLException { return emptyList(); } @Override protected String getNodeFullName() { return String.format("%s.%s", tableNode.getNodeFullName(), name); } } }
package net.localizethat.tasks; import java.io.File; import java.text.ParseException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.persistence.EntityManager; import javax.swing.JButton; import javax.swing.JTextArea; import javax.swing.SwingWorker; import net.localizethat.Main; import net.localizethat.model.L10n; import net.localizethat.model.LocaleContainer; import net.localizethat.model.LocaleContent; import net.localizethat.model.LocaleFile; import net.localizethat.model.LocalePath; import net.localizethat.model.ParseableFile; import net.localizethat.model.TextFile; import net.localizethat.model.jpa.JPAHelperBundle; import net.localizethat.model.jpa.LocaleContainerJPAHelper; import net.localizethat.model.jpa.LocaleContentJPAHelper; import net.localizethat.model.jpa.LocaleFileJPAHelper; import net.localizethat.util.gui.JStatusBar; /** * SwingWorker task that performs an update process in the locale paths passed in the constructor * @author rpalomares */ public class UpdateProductWorker extends SwingWorker<List<LocaleContent>, String> { private final JTextArea feedbackArea; private final JButton editChangesButton; private final JStatusBar statusBar; private final L10n targetLocale; private final Iterator<LocalePath> localePathIterator; private final List<LocaleContent> newAndModifiedList; private final EntityManager em; private final JPAHelperBundle jhb; private int filesAdded; private int filesModified; private int filesDeleted; private int foldersAdded; private int foldersModified; private int foldersDeleted; public UpdateProductWorker(JTextArea feedbackArea, JButton editChangesButton, L10n targetLocale, Iterator<LocalePath> localePathIterator) { this.feedbackArea = feedbackArea; this.editChangesButton = editChangesButton; this.targetLocale = targetLocale; this.localePathIterator = localePathIterator; this.statusBar = Main.mainWindow.getStatusBar(); this.em = Main.emf.createEntityManager(); this.newAndModifiedList = new ArrayList<>(10); this.jhb = JPAHelperBundle.getInstance(em); } @Override protected List<LocaleContent> doInBackground() { int totalFilesAdded = 0; int totalFilesModified = 0; int totalFilesDeleted = 0; int totalFoldersAdded = 0; int totalFoldersModified = 0; int totalFoldersDeleted = 0; em.getTransaction().begin(); while (localePathIterator.hasNext()) { if (isCancelled()) { break; } LocalePath lp = localePathIterator.next(); publish("Processing " + lp.getFilePath()); processPath(lp); if (isCancelled()) { publish("Update process cancelled, work done until now can't be undone"); if (em.isJoinedToTransaction()) { em.getTransaction().rollback(); } break; } else { totalFilesAdded += filesAdded; totalFilesModified += filesModified; totalFilesDeleted += filesDeleted; totalFoldersAdded += foldersAdded; totalFoldersModified += foldersModified; totalFoldersDeleted += foldersDeleted; publish(" Files... Added: " + filesAdded + "; Modified: " + filesModified + "; Deleted: " + filesDeleted); publish(" Folders... Added: " + foldersAdded + "; Modified: " + foldersModified + "; Deleted: " + foldersDeleted); } } if (em.isJoinedToTransaction()) { em.getTransaction().commit(); } em.close(); publish("Total Files... Added: " + totalFilesAdded + "; Modified: " + totalFilesModified + "; Deleted: " + totalFilesDeleted); publish("Total Folders... Added: " + totalFoldersAdded + "; Modified: " + totalFoldersModified + "; Deleted: " + totalFoldersDeleted); return newAndModifiedList; } @Override protected void process(List<String> messages) { for(String message : messages) { feedbackArea.append(message); feedbackArea.append(System.getProperty("line.separator")); } } @Override protected void done() { statusBar.endProgress(); editChangesButton.setEnabled(true); } private void processPath(LocalePath lp) { // Initialize the counters for each path filesAdded = 0; filesModified = 0; filesDeleted = 0; foldersAdded = 0; foldersModified = 0; foldersDeleted = 0; LocaleContainer lc = lp.getLocaleContainer(); processContainer(lp.getFilePath(), lc); } private void processContainer(String currentPath, LocaleContainer lc) { File curDir = new File(currentPath); File[] childFiles = curDir.listFiles(); LocaleContainerJPAHelper lcHelper = jhb.getLocaleContainerJPAHelper(); LocaleFileJPAHelper lfHelper = jhb.getLocaleFileJPAHelper(); if (isCancelled()) { return; } // Take the real files & dirs in the disk and add those missing in the datamodel try { if (!em.isJoinedToTransaction()) { em.getTransaction().begin(); } for (File curFile : childFiles) { if (isCancelled()) { if (em.isJoinedToTransaction()) { em.getTransaction().rollback(); } return; } if (curFile.isDirectory()) { boolean exists = (lc.hasChild(curFile.getName(), true)); if (!exists) { LocaleContainer newLc = new LocaleContainer(curFile.getName(), lc); newLc.setL10nId(lc.getL10nId()); lc.addChild(newLc); foldersAdded++; em.persist(newLc); // Create the twin for the target locale lcHelper.createRecursively(newLc, targetLocale, false); } } else { boolean exists = (lc.hasFileChild(curFile.getName(), true)); if (!exists) { LocaleFile lf = LocaleFile.createFile(curFile.getName(), lc); lc.addFileChild(lf); filesAdded++; em.persist(lf); // Create the twin for the target locale lfHelper.createRecursively(lf, targetLocale, false); } } } if (em.isJoinedToTransaction()) { em.getTransaction().commit(); } } catch (Exception e) { if (em.isJoinedToTransaction()) { em.getTransaction().rollback(); } return; } if (isCancelled()) { if (em.isJoinedToTransaction()) { em.getTransaction().rollback(); } return; } // Remove directories (LocaleContainer items) no longer present in the disk try { em.getTransaction().begin(); for (Iterator<LocaleContainer> iterator = lc.getChildren().iterator(); iterator.hasNext();) { if (isCancelled()) { if (em.isJoinedToTransaction()) { em.getTransaction().rollback(); } return; } LocaleContainer lcChild = iterator.next(); lcChild = em.merge(lcChild); File result = fileExistsInArray(childFiles, lcChild.getName()); boolean exists = (result != null && result.isDirectory()); if (!exists) { lcChild.setParent(null); iterator.remove(); lcHelper.removeRecursively(lcChild); foldersDeleted++; } else { // Remove the entry in the directory entries array to mark it as processed removeFileFromArray(childFiles, result); } } em.getTransaction().commit(); } catch (NullPointerException e) { Logger.getLogger(UpdateProductWorker.class.getName()).log(Level.SEVERE, null, e); } catch (Exception e) { if (em.isJoinedToTransaction()) { em.getTransaction().rollback(); } return; } if (isCancelled()) { if (em.isJoinedToTransaction()) { em.getTransaction().rollback(); } return; } // Remove files (LocaleFiles items) no longer present in the disk try { em.getTransaction().begin(); for(Iterator<? extends LocaleFile> iterator = lc.getFileChildren().iterator(); iterator.hasNext();) { if (isCancelled()) { if (em.isJoinedToTransaction()) { em.getTransaction().rollback(); } return; } LocaleFile lfChild = iterator.next(); em.merge(lfChild); File result = fileExistsInArray(childFiles, lfChild.getName()); boolean exists = (result != null && !result.isDirectory()); if (!exists) { lfChild.setParent(null); iterator.remove(); lfHelper.removeRecursively(lfChild); filesDeleted++; } else { removeFileFromArray(childFiles, result); } } em.getTransaction().commit(); } catch (NullPointerException e) { Logger.getLogger(UpdateProductWorker.class.getName()).log(Level.SEVERE, null, e); } catch (Exception e) { Logger.getLogger(UpdateProductWorker.class.getName()).log(Level.SEVERE, null, e); if (em.isJoinedToTransaction()) { em.getTransaction().rollback(); } return; } if (isCancelled()) { if (em.isJoinedToTransaction()) { em.getTransaction().rollback(); } return; } // At this point, the datamodel for currentPath matches the disk contents // Traverse the datamodel LocaleContainers (folders/dirs) for(LocaleContainer lcChild : lc.getChildren()) { processContainer(currentPath + "/" + lcChild.getName(), lcChild); } // Traverse the datamodel LocaleFiles (files) for(LocaleFile lfChild : lc.getFileChildren()) { if (isCancelled()) { if (em.isJoinedToTransaction()) { em.getTransaction().rollback(); } return; } processFile(currentPath + "/" + lfChild.getName(), lfChild); } } private boolean processFile(String filePath, LocaleFile lf) { LocaleContentJPAHelper lcntHelper = jhb.getLocaleContentJPAHelper(); boolean result = true; try { if (lf instanceof ParseableFile) { ParseableFile pf = (ParseableFile) em.merge(lf); newAndModifiedList.addAll(pf.update(this.em, lcntHelper)); for(LocaleContent lcnt : pf.getChildren()) { // If the original locale content is set to not be exported // we don't want to create sibling for it if ((!lcnt.isDontExport() && lcnt.getTwinByLocale(targetLocale) == null)) { // em.contains(entity) to know whether an entity is managed or not LocaleContent mergedLcnt = em.merge(lcnt); result = lcntHelper.createRecursively(mergedLcnt, targetLocale, false); } } if (em.isJoinedToTransaction()) { em.getTransaction().commit(); em.getTransaction().begin(); } } else if (lf instanceof TextFile) { if (!em.isJoinedToTransaction()) { em.getTransaction().begin(); } TextFile mergedLf = (TextFile) em.merge(lf); newAndModifiedList.addAll(mergedLf.update(this.em)); if (em.isJoinedToTransaction()) { em.getTransaction().commit(); em.getTransaction().begin(); } } filesModified++; return result; } catch (ParseException ex) { return false; } catch (Exception ex) { Logger.getLogger(UpdateProductWorker.class.getName()).log(Level.SEVERE, null, ex); return false; } } private File fileExistsInArray(File[] fileArray, String filename) { File result = null; for(File f : fileArray) { if ((f != null) && (f.getName().equals(filename))) { result = f; break; } } return result; } private boolean removeFileFromArray(File[] fileArray, File fileToRemove) { boolean result = false; for(int i = 0; i < fileArray.length; i++) { if ((fileArray[i] != null) && (fileArray[i].equals(fileToRemove))) { fileArray[i] = null; result = true; break; } } return result; } }
package VASSAL.build.module.noteswindow; import java.awt.Dialog; import java.awt.Dimension; import java.awt.Frame; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.beans.PropertyChangeListener; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.ListSelectionModel; import javax.swing.SwingUtilities; import javax.swing.border.TitledBorder; import javax.swing.table.AbstractTableModel; import javax.swing.table.TableColumn; import VASSAL.build.BadDataReport; import VASSAL.build.GameModule; import VASSAL.build.module.Chatter; import VASSAL.build.module.GameComponent; import VASSAL.build.module.GlobalOptions; import VASSAL.command.Command; import VASSAL.command.CommandEncoder; import VASSAL.configure.StringConfigurer; import VASSAL.configure.TextConfigurer; import VASSAL.i18n.Resources; import VASSAL.tools.ErrorDialog; import VASSAL.tools.ScrollPane; import VASSAL.tools.SequenceEncoder; import VASSAL.tools.WarningDialog; public class SecretNotesController implements GameComponent, CommandEncoder, AddSecretNoteCommand.Interface { public static final String COMMAND_PREFIX = "SNOTE\t"; //$NON-NLS-1$ private Controls controls; private JPanel panel; private final List<SecretNote> notes; private List<SecretNote> lastSavedNotes; // Secret Note display table columns public static final int COL_HANDLE = 0; public static final int COL_DTM = 1; public static final int COL_NAME = 2; public static final int COL_REVEALED = 3; private static final String INTERNAL_DATETIME_FORMAT = "MM/dd/yyyy h:mm a"; //NON-NLS /** * Date formatter to save and restore date/times in the save file. * * Not thread-safe! */ public static final DateFormat INTERNAL_DATE_FORMATTER = new SimpleDateFormat(INTERNAL_DATETIME_FORMAT); /** * Date formatter to display date/time to the player. * * Not thread-safe! */ public static final DateFormat LOCAL_DATE_FORMATTER = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.getDefault()); public SecretNotesController() { notes = new ArrayList<>(); controls = new Controls(); } @Override public Command getRestoreCommand() { Command comm = null; for (final SecretNote note : notes) { final Command c = new AddSecretNoteCommand(this, note); if (comm == null) { comm = c; } else { comm.append(c); } } return comm; } @Override public void setup(boolean gameStarting) { if (!gameStarting) { notes.clear(); rebuildControls(); } } private void rebuildControls() { if (panel != null) { panel.remove(controls); } controls = new Controls(); if (panel != null) { panel.add(controls); } } @Override public Command decode(String command) { if (!command.startsWith(COMMAND_PREFIX)) { return null; } final SequenceEncoder.Decoder st = new SequenceEncoder.Decoder(command.substring(COMMAND_PREFIX.length()), '\t'); final String name = st.nextToken(); final String owner = st.nextToken(); final boolean hidden = "true".equals(st.nextToken()); //$NON-NLS-1$ final String text = TextConfigurer.restoreNewlines(st.nextToken()); String handle = ""; //$NON-NLS-1$ Date date = null; if (st.hasMoreTokens()) { final String formattedDate = st.nextToken(); try { date = new SimpleDateFormat(INTERNAL_DATETIME_FORMAT).parse(formattedDate); } catch (final ParseException e) { ErrorDialog.dataWarning(new BadDataReport("Illegal date format", formattedDate, e)); //NON-NLS } } if (st.hasMoreTokens()) { handle = st.nextToken(); } final SecretNote note = new SecretNote(name, owner, text, hidden, date, handle); return new AddSecretNoteCommand(this, note); } @Override public String encode(Command c) { if (!(c instanceof AddSecretNoteCommand)) { return null; } final SecretNote note = ((AddSecretNoteCommand) c).getNote(); final SequenceEncoder se = new SequenceEncoder('\t'); final String date = note.getDate() == null ? "" : new SimpleDateFormat(INTERNAL_DATETIME_FORMAT).format(note.getDate()); //$NON-NLS-1$ return COMMAND_PREFIX + se .append(note.getName()) .append(note.getOwner()) .append(note.isHidden()) .append(TextConfigurer.escapeNewlines(note.getText())) .append(date) .append(note.getHandle()).getValue(); } @Override public void addSecretNote(SecretNote note) { final int index = notes.indexOf(note); if (index >= 0) { notes.set(index, note); } else { notes.add(note); } rebuildControls(); } public JComponent getControls() { if (panel == null) { panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); final JLabel l = new JLabel(Resources.getString("Notes.visible_once_revealed")); //$NON-NLS-1$ l.setAlignmentX(0.0F); panel.add(l); panel.add(controls); } return panel; } public Command save() { Command comm = null; for (final SecretNote secretNote : notes) { final int index = lastSavedNotes.indexOf(secretNote); if (index < 0 || lastSavedNotes.get(index).isHidden() != secretNote.isHidden()) { Command c = new AddSecretNoteCommand(this, secretNote); if (comm == null) { comm = c; } else { comm.append(c); } final String msg; if (index < 0) { msg = "* " + Resources.getString("Notes.has_created", GlobalOptions.getInstance().getPlayerId(), secretNote.getName()) + " *"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } else { msg = "* " + Resources.getString("Notes.has_revealed", GlobalOptions.getInstance().getPlayerId(), secretNote.getName()) + " *"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } c = new Chatter.DisplayText(GameModule.getGameModule().getChatter(), msg); c.execute(); comm.append(c); } } return comm; } public void captureState() { lastSavedNotes = new ArrayList<>(notes); } public void restoreState() { notes.clear(); notes.addAll(lastSavedNotes); rebuildControls(); } private class Controls extends JPanel implements ItemListener { private static final long serialVersionUID = 1L; private final JTextArea text; private final JTable table; private final JButton revealButton; private final String[] columnNames = { Resources.getString("Notes.player"), //$NON-NLS-1$ Resources.getString("Notes.date_time"), //$NON-NLS-1$ Resources.getString("Notes.note_name"), //$NON-NLS-1$ Resources.getString("Notes.revealed") //$NON-NLS-1$ }; public Controls() { setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); table = new JTable(new MyTableModel()); initColumns(table); table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); final ListSelectionModel rowSM = table.getSelectionModel(); rowSM.addListSelectionListener(e -> { //Ignore extra messages. if (e.getValueIsAdjusting()) return; final ListSelectionModel lsm = (ListSelectionModel) e.getSource(); if (!lsm.isSelectionEmpty()) { displaySelected(); } }); final JScrollPane secretScroll = new ScrollPane(table); table.setPreferredScrollableViewportSize(new Dimension(500, 100)); add(secretScroll); final Box b = Box.createHorizontalBox(); b.setAlignmentX(0.0F); final JButton newButton = new JButton(Resources.getString(Resources.NEW)); newButton.addActionListener(e -> createNewNote()); b.add(newButton); revealButton = new JButton(Resources.getString("Notes.reveal")); //$NON-NLS-1$ revealButton.addActionListener(e -> revealSelectedNote()); revealButton.setEnabled(false); b.add(revealButton); add(b); text = new JTextArea(6, 20); text.setEditable(false); final JScrollPane scroll = new ScrollPane(text); scroll.setBorder(new TitledBorder(Resources.getString("Notes.text"))); //$NON-NLS-1$ add(scroll); } private void initColumns(JTable t) { TableColumn column; for (int i = 0; i < columnNames.length; i++) { column = t.getColumnModel().getColumn(i); final int width; switch (i) { case COL_HANDLE: width = 60; break; case COL_DTM: width = 100; break; case COL_NAME: width = 280; break; case COL_REVEALED: width = 60; break; default: width = 100; break; } column.setPreferredWidth(width); } } public class MyTableModel extends AbstractTableModel { private static final long serialVersionUID = 1L; @Override public String getColumnName(int col) { return columnNames[col]; } @Override public int getRowCount() { return notes.size(); } @Override public int getColumnCount() { return columnNames.length; } @Override public Object getValueAt(int row, int col) { final SecretNote note = notes.get(row); switch (col) { case COL_HANDLE: return note.getHandle(); case COL_DTM: return note.getDate() == null ? "" : LOCAL_DATE_FORMATTER.format(note.getDate()); //$NON-NLS-1$ case COL_NAME: return note.getName(); case COL_REVEALED: return !note.isHidden(); default: return null; } } @Override public Class<?> getColumnClass(int c) { return getValueAt(0, c).getClass(); } @Override public boolean isCellEditable(int row, int col) { return false; } @Override public void setValueAt(Object value, int row, int col) { } } public void refresh() { table.setModel(new MyTableModel()); initColumns(table); displaySelected(); } private void revealSelectedNote() { final int selectedRow = table.getSelectedRow(); if (selectedRow < 0) { return; } final String selectedName = (String) table.getValueAt(selectedRow, COL_NAME); SecretNote note = getNoteForName(selectedName); if (note.getOwner().equals(GameModule.getActiveUserId())) { note = new SecretNote(note.getName(), note.getOwner(), note.getText(), false, note.getDate(), note.getHandle()); if (note != null) { final int i = notes.indexOf(note); notes.set(i, note); refresh(); } } } public void createNewNote() { final Dialog parent = (Dialog) SwingUtilities.getAncestorOfClass(Dialog.class, this); final JDialog d; if (parent != null) { d = new JDialog(parent, true); } else { d = new JDialog( (Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), true ); } d.setTitle(Resources.getString("Notes.delayed_note")); //$NON-NLS-1$ final StringConfigurer name = new StringConfigurer(null, Resources.getString("Notes.name")); //$NON-NLS-1$ final TextConfigurer text = new TextConfigurer(null, Resources.getString("Notes.text")); //$NON-NLS-1$ d.setLayout(new BoxLayout(d.getContentPane(), BoxLayout.Y_AXIS)); d.add(name.getControls()); d.add(text.getControls()); final Box buttonPanel = Box.createHorizontalBox(); final JButton okButton = new JButton(Resources.getString(Resources.OK)); okButton.addActionListener(e -> { final SecretNote note = new SecretNote( name.getValueString(), GameModule.getActiveUserId(), (String) text.getValue(), true ); if (notes.contains(note)) { WarningDialog.show(this, "Notes.note_exists"); //NON-NLS } else { notes.add(0, note); refresh(); d.dispose(); } }); final PropertyChangeListener l = evt -> okButton.setEnabled(name.getValueString() != null && name.getValueString().length() > 0 && text.getValueString() != null && text.getValueString().length() > 0); name.addPropertyChangeListener(l); text.addPropertyChangeListener(l); okButton.setEnabled(false); buttonPanel.add(okButton); final JButton cancelButton = new JButton(Resources.getString(Resources.CANCEL)); cancelButton.addActionListener(e -> d.dispose()); d.add(buttonPanel); d.pack(); d.setLocationRelativeTo(d.getOwner()); d.setVisible(true); } @Override public void itemStateChanged(ItemEvent e) { displaySelected(); } private void displaySelected() { revealButton.setEnabled(false); text.setText(""); //$NON-NLS-1$ final int selectedRow = table.getSelectedRow(); if (selectedRow < 0) { return; } final String selectedName = (String) table.getValueAt(selectedRow, COL_NAME); final SecretNote note = getNoteForName(selectedName); if (note != null) { if (note.getOwner().equals(GameModule.getActiveUserId())) { text.setText(note.getText()); revealButton.setEnabled(note.isHidden()); } else { text.setText(note.isHidden() ? Resources.getString("Notes.message_not_revealed") : note.getText()); //$NON-NLS-1$ } } } } public SecretNote getNoteForName(String s) { for (final SecretNote n : notes) { if (n.getName().equals(s)) { return n; } } return null; } }
package net.lucenews.controller; import java.io.*; import net.lucenews.*; import net.lucenews.model.*; import net.lucenews.model.exception.*; import net.lucenews.view.*; import net.lucenews.atom.*; import java.util.*; import javax.xml.parsers.*; import javax.xml.transform.*; import org.apache.log4j.*; import org.apache.lucene.document.Field; import org.apache.lucene.index.*; import org.apache.lucene.search.*; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.*; public class DocumentController extends Controller { /** * Deletes a document * * @throws IndicesNotFoundException * @throws DocumentsNotFoundException * @throws IOException */ public static void doDelete (LuceneContext c) throws IllegalActionException, IndicesNotFoundException, DocumentsNotFoundException, IOException, InsufficientDataException, TransformerException, ParserConfigurationException { c.getLogger().trace("doDelete(LuceneContext)"); LuceneWebService service = c.getService(); LuceneIndexManager manager = service.getIndexManager(); LuceneRequest request = c.getRequest(); LuceneResponse response = c.getResponse(); String[] indexNames = request.getIndexNames(); LuceneIndex[] indices = manager.getIndices( indexNames ); String[] documentIDs = request.getDocumentIDs(); // Buffers for header location construction StringBuffer indexNamesBuffer = new StringBuffer(); StringBuffer documentIDsBuffer = new StringBuffer(); boolean deleted = false; // For each index... for (int i = 0; i < indices.length; i++) { LuceneIndex index = indices[ i ]; if (i > 0) { indexNamesBuffer.append( "," ); } indexNamesBuffer.append( index.getName() ); // For each document... for (int j = 0; j < documentIDs.length; j++) { String documentID = documentIDs[ j ]; LuceneDocument document = index.removeDocument( documentID ); deleted = true; if (i == 0) { if (j > 0) { documentIDsBuffer.append( "," ); } documentIDsBuffer.append( index.getIdentifier( document ) ); } } } String indexNamesString = indexNamesBuffer.toString(); String documentIDsString = documentIDsBuffer.toString(); if (deleted) { if ( c.isOptimizing() == null || c.isOptimizing() ) { IndexController.doOptimize( c ); } response.addHeader( "Location", service.getDocumentURI( request, indexNamesString, documentIDsString ).toString() ); } else { throw new InsufficientDataException( "No documents to be deleted" ); } XMLController.acknowledge( c ); } /** * Gets a document * * @throws IndicesNotFoundException * @throws DocumentsNotFoundException * @throws ParserConfigurationException * @throws TransformerException * @throws IOException */ public static void doGet (LuceneContext c) throws IndicesNotFoundException, DocumentsNotFoundException, ParserConfigurationException, TransformerException, IOException, InsufficientDataException { c.getLogger().trace("doGet(LuceneContext)"); LuceneWebService service = c.getService(); LuceneIndexManager manager = service.getIndexManager(); LuceneRequest request = c.getRequest(); LuceneResponse response = c.getResponse(); Author firstAuthor = null; List<Entry> entries = new LinkedList<Entry>(); LuceneIndex[] indices = manager.getIndices( request.getIndexNames() ); String[] documentIDs = request.getDocumentIDs(); for (int i = 0; i < documentIDs.length; i++) { String documentID = documentIDs[ i ]; for (int j = 0; j < indices.length; j++) { LuceneIndex index = indices[ j ]; LuceneDocument document = null; try { document = index.getDocument( documentID ); if ( document.getNumber() != null ) { // Attempt to locate similar documents /* IndexReader reader = index.getIndexReader(); IndexSearcher searcher = index.getIndexSearcher(); MoreLikeThis moreLikeThis = new MoreLikeThis( reader ); document.setSimilarDocumentHits( searcher.search( moreLikeThis.like( document.getNumber() ), c.getFilter(), c.getSort() ) ); Logger.getLogger(DocumentController.class).debug("Set the similar documents: "+document.getSimilarDocumentHits().length()); index.putIndexReader( reader ); index.putIndexSearcher( searcher ); */ } else { c.getLogger().debug("Document number is null"); } } catch (DocumentNotFoundException dnfe) { c.getLogger().debug("Failed to set similar documents", dnfe); } if ( document != null ) { if ( entries.size() == 0 ) { String name = index.getAuthor( document ); if ( name == null ) { name = service.getTitle(); } firstAuthor = new Author( name ); } entries.add( asEntry( c, index, document ) ); } } } if ( entries.size() == 1 ) { entries.get( 0 ).addAuthor( firstAuthor ); } //if( documents.length == 1 ) // AtomView.process( c, asEntry( c, documents[ 0 ] ) ); //else // AtomView.process( c, asFeed( c, documents ) ); if ( entries.size() == 0 ) { throw new DocumentsNotFoundException( documentIDs ); } if ( entries.size() == 1 ) { AtomView.process( c, entries.get( 0 ) ); } else { Feed feed = new Feed(); feed.setTitle( "Documents" ); feed.setUpdated( Calendar.getInstance() ); feed.setID( request.getLocation() ); feed.addLink( Link.Self( request.getLocation() ) ); feed.addAuthor( new Author( service.getTitle() ) ); Iterator<Entry> iterator = entries.iterator(); while ( iterator.hasNext() ) { feed.addEntry( iterator.next() ); } AtomView.process( c, feed ); } } /** * Updates particular documents within the index * * @throws InvalidIdentifierException * @throws IndicesNotFoundException * @throws SAXException * @throws TransformerException * @throws ParserConfigurationException * @throws DocumentNotFoundException * @throws IndexNotFoundException * @throws IOException * @throws AtomParseException */ public static void doPut (LuceneContext c) throws IllegalActionException, InvalidIdentifierException, IndicesNotFoundException, SAXException, TransformerException, ParserConfigurationException, DocumentNotFoundException, IndexNotFoundException, IOException, InsufficientDataException, AtomParseException, LuceneParseException { c.getLogger().trace("doPut(LuceneContext)"); LuceneWebService service = c.getService(); LuceneIndexManager manager = service.getIndexManager(); LuceneRequest request = c.getRequest(); LuceneResponse response = c.getResponse(); LuceneIndex[] indices = manager.getIndices( request.getIndexNames() ); LuceneDocument[] documents = request.getLuceneDocuments(); // Buffers for header location construction StringBuffer indexNamesBuffer = new StringBuffer(); StringBuffer documentIDsBuffer = new StringBuffer(); boolean updated = false; for (int i = 0; i < indices.length; i++) { LuceneIndex index = indices[ i ]; if (i > 0) { indexNamesBuffer.append( "," ); } indexNamesBuffer.append( index.getName() ); for (int j = 0; j < documents.length; j++) { LuceneDocument document = documents[ j ]; index.updateDocument( document ); updated = true; if (i == 0) { if (j > 0) { documentIDsBuffer.append( "," ); } documentIDsBuffer.append( index.getIdentifier( document ) ); } } } String indexNames = indexNamesBuffer.toString(); String documentIDs = documentIDsBuffer.toString(); if (updated) { response.addHeader( "Location", service.getDocumentURI( request, indexNames, documentIDs ).toString() ); if ( c.isOptimizing() == null || c.isOptimizing() ) { IndexController.doOptimize( c ); } } else { throw new InsufficientDataException( "No documents to be updated" ); } XMLController.acknowledge( c ); } public static Entry asEntry (LuceneContext c, LuceneIndex index, LuceneDocument document) throws InsufficientDataException, ParserConfigurationException, IOException { c.getLogger().trace("asEntry(LuceneContext,LuceneIndex,LuceneDocument)"); return asEntry( c, index, document, null ); } public static Entry asEntry (LuceneContext c, LuceneDocument document) throws InsufficientDataException, ParserConfigurationException, IOException { c.getLogger().trace("asEntry(LuceneContext,LuceneDocument)"); return asEntry( c, document.getIndex(), document, null ); } /** * Returns an Atom Entry reflecting the standard format chosen for documents. * * @param c The context * @param document The document * @param score The score of the document (if it was a hit) * @return An Atom Entry * @throws ParserConfigurationException * @throws IOException */ public static Entry asEntry (LuceneContext c, LuceneDocument document, Float score) throws InsufficientDataException, ParserConfigurationException, IOException { c.getLogger().trace("asEntry(LuceneContext,LuceneDocument,Float)"); return asEntry( c, document.getIndex(), document, score ); } /** * Returns an Atom Entry reflecting the standard format chosen for documents. * * @param c The context * @param index The index * @param document The document * @param score The score of the document (if it was a hit) * @return An Atom Entry * @throws ParserConfigurationException * @throws IOException */ public static Entry asEntry (LuceneContext c, LuceneIndex index, LuceneDocument document, Float score) throws InsufficientDataException, ParserConfigurationException, IOException { c.getLogger().trace("asEntry(LuceneContext,LuceneIndex,LuceneDocument,Float)"); LuceneWebService service = c.getService(); LuceneRequest request = c.getRequest(); // Entry Entry entry = new Entry(); // Content entry.setContent( asContent( c, index, document ) ); if ( index == null ) { return entry; } // ID and Link may only be added if the document is identified if ( index.isDocumentIdentified( document ) ) { entry.setID( service.getDocumentURI( request, index, document ).toString() ); // Link entry.addLink( Link.Alternate( service.getDocumentURI( request, index, document ).toString() ) ); } // links to similar documents if ( document.getSimilarDocumentHits() != null ) { Hits hits = document.getSimilarDocumentHits(); //Logger.getLogger(DocumentController.class).debug("Found " + hits.length() + " similar documents"); for (int i = 0; i < hits.length(); i++) { try { LuceneDocument similarDocument = index.getDocument( hits.id( i ) ); Link relatedLink = Link.Related( service.getDocumentURI( request, index.getName(), similarDocument.getIdentifier() ).toString() ); entry.addLink( relatedLink ); //Logger.getLogger(DocumentController.class).debug("Successfully added related link"); } catch (DocumentNotFoundException dnfe) { //Logger.getLogger(DocumentController.class).debug("Failed to add related link"); } } } else { //Logger.getLogger(DocumentController.class).debug("No similar documents!"); } // Title entry.setTitle( index.getTitle( document ) ); // Updated try { entry.setUpdated( index.getLastModified( document ) ); } catch (java.text.ParseException pe) { } catch (InsufficientDataException ide) { } // Author if ( index.getAuthor( document ) != null ) { entry.addAuthor( new Author( index.getAuthor( document ) ) ); } // Summary if ( index.getSummary( document ) != null ) { entry.setSummary( new Text( index.getSummary( document ) ) ); } return entry; } /** * Returns a DOM Element (<div>...</div>) containing XOXO-formatted data * * @param c The context * @param index The index * @param document The document * @return A DOM Element * @throws ParserConfigurationException * @throws IOException */ public static Content asContent (LuceneContext c, LuceneIndex index, LuceneDocument document) throws ParserConfigurationException, IOException { c.getLogger().trace("asContent(LuceneContext,LuceneIndex,LuceneDocument)"); Document doc = XMLController.newDocument(); Element div = doc.createElement( "div" ); div.setAttribute( "xmlns", "http: div.appendChild( XOXOController.asElement( c, document, doc ) ); return Content.xhtml( div ); } /** * Retrieves the appropriate CSS class for the given field */ public static String getCSSClass (LuceneContext c, Field field) { c.getLogger().trace("getCSSClass(LuceneContext,Field)"); StringBuffer _class = new StringBuffer(); if ( field.isStored() ) { _class.append( " stored" ); } if ( field.isIndexed() ) { _class.append( " indexed" ); } if ( field.isTokenized() ) { _class.append( " tokenized" ); } if ( field.isTermVectorStored() ) { _class.append( " termvectorstored" ); } return String.valueOf( _class ).trim(); } /** * Transforms an Atom feed into an array of Lucene documents! */ public static LuceneDocument[] asLuceneDocuments (LuceneContext c, Feed feed) throws ParserConfigurationException, TransformerConfigurationException, TransformerException, LuceneParseException { c.getLogger().trace("asLuceneDocuments(LuceneContext,Feed)"); return asLuceneDocuments( c, feed.getEntries().toArray( new Entry[]{} ) ); } /** * Transforms Atom entries into Lucene documents * * @param entries Atom entries * @return Lucene documents */ public static LuceneDocument[] asLuceneDocuments (LuceneContext c, Entry... entries) throws ParserConfigurationException, TransformerConfigurationException, TransformerException, LuceneParseException { c.getLogger().trace("asLuceneDocuments(LuceneContext,Entry...)"); List<LuceneDocument> documents = new LinkedList<LuceneDocument>(); for (int i = 0; i < entries.length; i++) { documents.addAll( Arrays.asList( asLuceneDocuments( c, entries[ i ] ) ) ); } return documents.toArray( new LuceneDocument[]{} ); } /** * Transforms an Atom entry into Lucene documents. * Typically, this will only involve the output of one * Lucene document, however, the door may be open to multiple. * * @param entry * @return LuceneDocument[] */ public static LuceneDocument[] asLuceneDocuments (LuceneContext c, Entry entry) throws ParserConfigurationException, TransformerConfigurationException, TransformerException, LuceneParseException { c.getLogger().trace("asLuceneDocuments(LuceneContext,Entry)"); return asLuceneDocuments( c, entry.getContent() ); } /** * Transforms Atom content into Lucene documents. */ public static LuceneDocument[] asLuceneDocuments (LuceneContext c, Content content) throws ParserConfigurationException, TransformerConfigurationException, TransformerException, LuceneParseException { c.getLogger().trace("asLuceneDocuments(LuceneContext,Content)"); if (content == null) { throw new LuceneParseException("Cannot parse Lucene document: NULL content in entry"); } if (content instanceof TextContent) { return asLuceneDocuments( c, (TextContent) content ); } if (content instanceof NodeContent) { return asLuceneDocuments( c, (NodeContent) content ); } throw new LuceneParseException("Cannot parse Lucene document: Unknown content type in entry"); } /** * Transforms Atom text content into Lucene documents */ public static LuceneDocument[] asLuceneDocuments (LuceneContext c, TextContent content) throws ParserConfigurationException, TransformerConfigurationException, TransformerException, LuceneParseException { c.getLogger().trace("asLuceneDocuments(LuceneContext,TextContent)"); return asLuceneDocuments( c, content.asDocument() ); } /** * Transforms Atom node content into Lucene documents */ public static LuceneDocument[] asLuceneDocuments (LuceneContext c, NodeContent content) throws LuceneParseException { c.getLogger().trace("asLuceneDocuments(LuceneContext,NodeContent)"); return asLuceneDocuments( c, content.getNodes() ); } public static LuceneDocument[] asLuceneDocuments (LuceneContext c, Document document) throws LuceneParseException { c.getLogger().trace("asLuceneDocuments(LuceneContext,Document)"); return asLuceneDocuments( c, document.getDocumentElement() ); } public static LuceneDocument[] asLuceneDocuments (LuceneContext c, NodeList nodeList) throws LuceneParseException { c.getLogger().trace("asLuceneDocuments(LuceneContext,NodeList)"); Node[] nodes = new Node[ nodeList.getLength() ]; for (int i = 0; i < nodes.length; i++) { nodes[ i ] = nodeList.item( i ); } return asLuceneDocuments( c, nodes ); } public static LuceneDocument[] asLuceneDocuments (LuceneContext c, Node[] nodes) throws LuceneParseException { c.getLogger().trace("asLuceneDocuments(LuceneContext,Node[]): " + nodes.length + " nodes"); c.getLogger().trace("Nodes: " + ServletUtils.toString(nodes)); List<LuceneDocument> documents = new LinkedList<LuceneDocument>(); for (int i = 0; i < nodes.length; i++) { if (nodes[ i ].getNodeType() == Node.ELEMENT_NODE) { documents.addAll( Arrays.asList( asLuceneDocuments( c, (Element) nodes[ i ] ) ) ); } } return documents.toArray( new LuceneDocument[]{} ); } public static LuceneDocument[] asLuceneDocuments (LuceneContext c, Element element) throws LuceneParseException { c.getLogger().trace("asLuceneDocuments(LuceneContext,Element)"); List<LuceneDocument> documents = new LinkedList<LuceneDocument>(); if (element.getTagName().equals( "div" )) { documents.addAll( Arrays.asList( asLuceneDocuments( c, (NodeList) element.getChildNodes() ) ) ); } else { LuceneDocument document = new LuceneDocument(); Field[] fields = XOXOController.asFields( c, element ); if (fields.length == 0) { throw new LuceneParseException("No fields in specified document"); } document.add( fields ); documents.add( document ); } return documents.toArray( new LuceneDocument[]{} ); } public static LuceneDocument asLuceneDocument (LuceneContext c, Element element) { c.getLogger().trace("asLuceneDocument(LuceneContext,Element)"); LuceneDocument document = new LuceneDocument(); NodeList fields = element.getElementsByTagName( "field" ); for (int i = 0; i < fields.getLength(); i++) { document.add( asField( c, (Element) fields.item( i ) ) ); } return document; } public static Field asField (LuceneContext c, Element element) { c.getLogger().trace("asField(LuceneContext,Element)"); if (!element.getTagName().equals( "field" )) { throw new RuntimeException( "Must provide a <field> tag" ); } String name = element.getAttribute( "name" ); String value = ServletUtils.toString( element.getChildNodes() ); if (element.getAttribute( "type" ) != null) { String type = element.getAttribute( "type" ).trim().toLowerCase(); if (type.equals( "keyword" )) { return new Field( name, value, Field.Store.YES, Field.Index.UN_TOKENIZED ); } if (type.equals( "text" )) { return new Field( name, value, Field.Store.YES, Field.Index.TOKENIZED ); } if (type.equals( "sort" )) { return new Field( name, value, Field.Store.NO, Field.Index.UN_TOKENIZED ); } if (type.equals( "unindexed" )) { return new Field( name, value, Field.Store.YES, Field.Index.NO ); } if (type.equals( "unstored" )) { return new Field( name, value, Field.Store.NO, Field.Index.TOKENIZED ); } return new Field( name, value, Field.Store.YES, Field.Index.TOKENIZED ); } else { boolean index = ServletUtils.parseBoolean( element.getAttribute( "index" ) ); boolean store = ServletUtils.parseBoolean( element.getAttribute( "store" ) ); boolean token = ServletUtils.parseBoolean( element.getAttribute( "tokenized" ) ); Field.Store stored = store ? Field.Store.YES : Field.Store.NO; Field.Index indexed = Field.Index.NO; if (index) { if (token) { indexed = Field.Index.TOKENIZED; } else { indexed = Field.Index.UN_TOKENIZED; } } return new Field( name, value, stored, indexed ); } } }
package net.ripe.db.whois.api.whois; import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; import net.ripe.db.whois.api.AbstractRestClientTest; import net.ripe.db.whois.api.httpserver.Audience; import net.ripe.db.whois.common.IntegrationTest; import net.ripe.db.whois.common.iptree.IpTreeUpdater; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.springframework.beans.factory.annotation.Autowired; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; @Category(IntegrationTest.class) public class GeolocationTestIntegration extends AbstractRestClientTest { @Autowired private IpTreeUpdater ipTreeUpdater; @Before public void setup() { databaseHelper.addObject( "mntner: OWNER-MNT\n" + "descr: Owner Maintainer\n" + "auth: MD5-PW $1$d9fKeTr2$Si7YudNf4rUGmR71n/cqk/ #test\n" + "changed: dbtest@ripe.net 20120101\n" + "source: TEST"); databaseHelper.addObject( "person: Test Person\n" + "address: Singel 258\n" + "phone: +31 6 12345678\n" + "nic-hdl: TP1-TEST\n" + "mnt-by: OWNER-MNT\n" + "changed: dbtest@ripe.net 20120101\n" + "source: TEST\n"); } @Test public void inetnum_with_geolocation_only() throws Exception { databaseHelper.addObject( "inetnum: 10.0.0.0 - 10.255.255.255\n" + "netname: RIPE-NCC\n" + "descr: Private Network\n" + "geoloc: 52.375599 4.899902\n" + "country: NL\n" + "tech-c: TP1-TEST\n" + "status: ASSIGNED PA\n" + "mnt-by: OWNER-MNT\n" + "mnt-lower: OWNER-MNT\n" + "source: TEST"); ipTreeUpdater.rebuild(); final String response = createResource("whois/geolocation?ipkey=10.0.0.0") .accept(MediaType.APPLICATION_XML) .get(String.class); assertThat(response, containsString("service=\"geolocation-finder\"")); assertThat(response, containsString("<link xlink:type=\"locator\" xlink:href=\"")); assertThat(response, containsString("<geolocation-attributes>")); assertThat(response, containsString("<location value=\"52.375599 4.899902\">")); assertThat(response, containsString("<link xlink:type=\"locator\" xlink:href=\"http://rest.db.ripe.net/lookup/test/inetnum/10.0.0.0 - 10.255.255.255\"/>")); } @Test public void inetnum_with_geolocation_and_language() throws Exception { databaseHelper.addObject( "inetnum: 10.0.0.0 - 10.255.255.255\n" + "netname: RIPE-NCC\n" + "descr: Private Network\n" + "geoloc: 52.375599 4.899902\n" + "language: EN\n" + "country: NL\n" + "tech-c: TP1-TEST\n" + "status: ASSIGNED PA\n" + "mnt-by: OWNER-MNT\n" + "mnt-lower: OWNER-MNT\n" + "source: TEST"); ipTreeUpdater.rebuild(); final String response = createResource("whois/geolocation?ipkey=10.0.0.0") .accept(MediaType.APPLICATION_XML) .get(String.class); assertThat(response, containsString("service=\"geolocation-finder\"")); assertThat(response, containsString("<link xlink:type=\"locator\" xlink:href=\"")); assertThat(response, containsString("<geolocation-attributes>")); assertThat(response, containsString("<location value=\"52.375599 4.899902\">")); assertThat(response, containsString("<language value=\"EN\">")); assertThat(response, containsString("<link xlink:type=\"locator\" xlink:href=\"http://rest.db.ripe.net/lookup/test/inetnum/10.0.0.0 - 10.255.255.255\"/>")); } @Test public void inetnum_with_geolocation_and_language_json_response() throws Exception { databaseHelper.addObject( "inetnum: 10.0.0.0 - 10.255.255.255\n" + "netname: RIPE-NCC\n" + "descr: Private Network\n" + "geoloc: 52.375599 4.899902\n" + "language: EN\n" + "country: NL\n" + "tech-c: TP1-TEST\n" + "status: ASSIGNED PA\n" + "mnt-by: OWNER-MNT\n" + "mnt-lower: OWNER-MNT\n" + "source: TEST"); ipTreeUpdater.rebuild(); final String response = createResource("whois/geolocation?ipkey=10.0.0.0") .accept(MediaType.APPLICATION_JSON) .get(String.class); assertThat(response, not(containsString("\"whois-resources\""))); assertThat(response, containsString("\"service\" : \"geolocation-finder\"")); assertThat(response, containsString("\"geolocation-attributes\"")); assertThat(response, containsString("\"location\"")); assertThat(response, containsString("\"language\"")); } @Test public void inetnum_without_geolocation() throws Exception { databaseHelper.addObject( "inetnum: 10.0.0.0 - 10.255.255.255\n" + "netname: RIPE-NCC\n" + "descr: Private Network\n" + "country: NL\n" + "tech-c: TP1-TEST\n" + "status: ASSIGNED PA\n" + "mnt-by: OWNER-MNT\n" + "mnt-lower: OWNER-MNT\n" + "source: TEST"); ipTreeUpdater.rebuild(); try { createResource("whois/geolocation?ipkey=10.0.0.0") .accept(MediaType.APPLICATION_XML) .get(String.class); fail(); } catch (UniformInterfaceException e) { assertThat(e.getResponse().getStatus(), is(Response.Status.NOT_FOUND.getStatusCode())); assertThat(e.getResponse().getEntity(String.class), is("No geolocation data was found for the given ipkey: 10.0.0.0")); } } @Test public void inetnum_not_found() throws Exception { try { createResource("whois/geolocation?ipkey=127.0.0.1") .accept(MediaType.APPLICATION_XML) .get(String.class); fail(); } catch (UniformInterfaceException e) { assertThat(e.getResponse().getStatus(), is(Response.Status.NOT_FOUND.getStatusCode())); assertThat(e.getResponse().getEntity(String.class), is("No geolocation data was found for the given ipkey: 127.0.0.1")); } } @Test public void organisation_with_geolocation() throws Exception { databaseHelper.addObject( "organisation: ORG-LIR1-TEST\n" + "org-type: LIR\n" + "org-name: Local Internet Registry\n" + "address: RIPE NCC\n" + "geoloc: 52.375599 4.899902\n" + "language: EN\n" + "e-mail: dbtest@ripe.net\n" + "ref-nfy: dbtest-org@ripe.net\n" + "mnt-ref: OWNER-MNT\n" + "mnt-by: OWNER-MNT\n" + "changed: dbtest@ripe.net 20121016\n" + "source: TEST\n"); databaseHelper.addObject( "inetnum: 10.0.0.0 - 10.255.255.255\n" + "netname: RIPE-NCC\n" + "org: ORG-LIR1-TEST\n" + "descr: Private Network\n" + "country: NL\n" + "tech-c: TP1-TEST\n" + "status: ASSIGNED PA\n" + "mnt-by: OWNER-MNT\n" + "mnt-lower: OWNER-MNT\n" + "source: TEST"); ipTreeUpdater.rebuild(); final String response = createResource("whois/geolocation?ipkey=10.0.0.0") .accept(MediaType.APPLICATION_XML) .get(String.class); assertThat(response, containsString("service=\"geolocation-finder\"")); assertThat(response, containsString("<link xlink:type=\"locator\" xlink:href=\"")); assertThat(response, containsString("<geolocation-attributes>")); assertThat(response, containsString("<location value=\"52.375599 4.899902\">")); assertThat(response, containsString("<language value=\"EN\">")); assertThat(response, containsString("<link xlink:type=\"locator\" xlink:href=\"http://rest.db.ripe.net/lookup/test/organisation/ORG-LIR1-TEST\"/>")); } @Test public void parent_inetnum_with_geolocation_and_language() throws Exception { databaseHelper.addObject( "inetnum: 10.0.0.0 - 10.255.255.255\n" + "netname: RIPE-NCC\n" + "geoloc: 52.375599 4.899902\n" + "language: EN\n" + "descr: Private Network\n" + "country: NL\n" + "tech-c: TP1-TEST\n" + "status: ASSIGNED PA\n" + "mnt-by: OWNER-MNT\n" + "mnt-lower: OWNER-MNT\n" + "source: TEST"); databaseHelper.addObject( "inetnum: 10.1.0.0 - 10.1.255.255\n" + "netname: RIPE-NCC\n" + "descr: Private Network\n" + "country: NL\n" + "tech-c: TP1-TEST\n" + "status: ASSIGNED PI\n" + "mnt-by: OWNER-MNT\n" + "mnt-lower: OWNER-MNT\n" + "source: TEST"); ipTreeUpdater.rebuild(); final String response = createResource("whois/geolocation?ipkey=10.1.0.0%20-%2010.1.255.255") .accept(MediaType.APPLICATION_XML) .get(String.class); assertThat(response, containsString("<location value=\"52.375599 4.899902\">")); assertThat(response, containsString("<link xlink:type=\"locator\" xlink:href=\"http://rest.db.ripe.net/lookup/test/inetnum/10.0.0.0 - 10.255.255.255\"/>")); } @Test public void inet6num_with_geolocation_and_language() throws Exception { databaseHelper.addObject( "inet6num: 2001::/20\n" + "netname: RIPE-NCC\n" + "descr: Private Network\n" + "geoloc: 52.375599 4.899902\n" + "language: EN\n" + "country: NL\n" + "tech-c: TP1-TEST\n" + "status: ASSIGNED PA\n" + "mnt-by: OWNER-MNT\n" + "mnt-lower: OWNER-MNT\n" + "source: TEST"); ipTreeUpdater.rebuild(); final String response = createResource("whois/geolocation?ipkey=2001::/20") .accept(MediaType.APPLICATION_XML) .get(String.class); assertThat(response, containsString("service=\"geolocation-finder\"")); assertThat(response, containsString("<link xlink:type=\"locator\" xlink:href=\"")); assertThat(response, containsString("<geolocation-attributes>")); assertThat(response, containsString("<location value=\"52.375599 4.899902\">")); assertThat(response, containsString("<language value=\"EN\">")); assertThat(response, containsString("<link xlink:type=\"locator\" xlink:href=\"http://rest.db.ripe.net/lookup/test/inet6num/2001::/20\"/>")); } @Test public void invalid_inetnum_argument() throws Exception { try { createResource("whois/geolocation?ipkey=invalid") .accept(MediaType.APPLICATION_XML) .get(String.class); fail(); } catch (UniformInterfaceException e) { assertThat(e.getResponse().getStatus(), is(Response.Status.NOT_FOUND.getStatusCode())); assertThat(e.getResponse().getEntity(String.class), is("No inetnum/inet6num resource has been found")); } } @Test public void geolocation_without_query_params() throws Exception { try { createResource("whois/geolocation") .get(String.class); fail(); } catch (UniformInterfaceException e) { assertThat(e.getResponse().getStatus(), is(Response.Status.BAD_REQUEST.getStatusCode())); assertThat(e.getResponse().getEntity(String.class), is("ipkey is required")); } } protected WebResource createResource(final String path) { return client.resource(String.format("http://localhost:%s/%s", getPort(Audience.PUBLIC), path)); } }
package ru.ydn.wicket.wicketorientdb.utils; import org.apache.wicket.util.lang.Objects; import ru.ydn.wicket.wicketorientdb.OrientDbWebSession; import com.orientechnologies.orient.core.db.document.ODatabaseDocument; import com.orientechnologies.orient.core.index.OIndex; import com.orientechnologies.orient.core.metadata.schema.OClass; import com.orientechnologies.orient.core.metadata.schema.OProperty; import com.orientechnologies.orient.core.metadata.schema.OSchema; import com.orientechnologies.orient.core.metadata.schema.OType; import com.orientechnologies.orient.core.metadata.schema.OClass.INDEX_TYPE; public class OSchemaHelper { protected ODatabaseDocument db; protected OSchema schema; protected OClass lastClass; protected OProperty lastProperty; protected OIndex<?> lastIndex; protected OSchemaHelper(ODatabaseDocument db) { this.db = db; this.schema = db.getMetadata().getSchema(); } public static OSchemaHelper bind() { return new OSchemaHelper(OrientDbWebSession.get().getDatabase()); } public static OSchemaHelper bind(ODatabaseDocument db) { return new OSchemaHelper(db); } public OSchemaHelper oClass(String className) { lastClass = schema.getClass(className); if(lastClass==null) { lastClass = schema.createClass(className); } lastProperty = null; lastIndex = null; return this; } public boolean existsClass(String className) { return schema.existsClass(className); } public OSchemaHelper oProperty(String propertyName, OType type) { checkOClass(); lastProperty = lastClass.getProperty(propertyName); if(lastProperty==null) { lastProperty = lastClass.createProperty(propertyName, type); } else { if(!type.equals(lastProperty.getType())) { lastProperty.setType(type); } } return this; } public OSchemaHelper linkedClass(String className) { checkOProperty(); OClass linkedToClass = schema.getClass(className); if(linkedToClass==null) throw new IllegalArgumentException("Target OClass '"+className+"' to link to not found"); if(!Objects.equal(linkedToClass, lastProperty.getLinkedClass())) { lastProperty.setLinkedClass(linkedToClass); } return this; } public OSchemaHelper oIndex(INDEX_TYPE type) { checkOProperty(); return oIndex(lastProperty.getFullName(), type); } public OSchemaHelper oIndex(String name, INDEX_TYPE type) { checkOProperty(); return oIndex(name, type, lastProperty.getName()); } public OSchemaHelper oIndex(String name, INDEX_TYPE type, String... fields) { checkOClass(); lastIndex = lastClass.getClassIndex(name); if(lastIndex==null) { lastIndex = lastClass.createIndex(name, type, fields); } else { //We can't do something to change type and fields if required } return this; } public OClass getOClass() { return lastClass; } public OProperty getOProperty() { return lastProperty; } public OIndex<?> getOIndex() { return lastIndex; } protected void checkOClass() { if(lastClass==null) throw new IllegalStateException("Last OClass should not be null"); } protected void checkOProperty() { if(lastProperty==null) throw new IllegalStateException("Last OProperty should not be null"); } protected void checkOIndex() { if(lastIndex==null) throw new IllegalStateException("Last OIndex should not be null"); } }
package org.apache.xerces.jaxp; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.DOMImplementation; import org.w3c.dom.DocumentType; import org.xml.sax.XMLReader; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.EntityResolver; import org.xml.sax.ErrorHandler; import org.xml.sax.helpers.DefaultHandler; import org.apache.xerces.parsers.DOMParser; import org.apache.xerces.dom.DOMImplementationImpl; /** * @author Rajiv Mordani * @author Edwin Goei * @version $Revision$ */ public class DocumentBuilderImpl extends DocumentBuilder { /** Xerces features */ static final String XERCES_FEATURE_PREFIX = "http://apache.org/xml/features/"; static final String CREATE_ENTITY_REF_NODES_FEATURE = "dom/create-entity-ref-nodes"; static final String INCLUDE_IGNORABLE_WHITESPACE = "dom/include-ignorable-whitespace"; private DocumentBuilderFactory dbf; private EntityResolver er = null; private ErrorHandler eh = null; private DOMParser domParser = null; private boolean namespaceAware = false; private boolean validating = false; DocumentBuilderImpl(DocumentBuilderFactory dbf) throws ParserConfigurationException { this.dbf = dbf; domParser = new DOMParser(); try { // Validation validating = dbf.isValidating(); String validation = "http://xml.org/sax/features/validation"; domParser.setFeature(validation, validating); // If validating, provide a default ErrorHandler that prints // validation errors with a warning telling the user to set an // ErrorHandler if (validating) { setErrorHandler(new DefaultValidationErrorHandler()); } // "namespaceAware" == SAX Namespaces feature namespaceAware = dbf.isNamespaceAware(); domParser.setFeature("http://xml.org/sax/features/namespaces", namespaceAware); // Set various parameters obtained from DocumentBuilderFactory domParser.setFeature(XERCES_FEATURE_PREFIX + INCLUDE_IGNORABLE_WHITESPACE, !dbf.isIgnoringElementContentWhitespace()); domParser.setFeature(XERCES_FEATURE_PREFIX + CREATE_ENTITY_REF_NODES_FEATURE, !dbf.isExpandEntityReferences()); // XXX No way to control dbf.isIgnoringComments() or // dbf.isCoalescing() } catch (SAXException e) { // Handles both SAXNotSupportedException, SAXNotRecognizedException throw new ParserConfigurationException(e.getMessage()); } } /** * Non-preferred: use the getDOMImplementation() method instead of this * one to get a DOM Level 2 DOMImplementation object and then use DOM * Level 2 methods to create a DOM Document object. */ public Document newDocument() { return new org.apache.xerces.dom.DocumentImpl(); } public DOMImplementation getDOMImplementation() { return DOMImplementationImpl.getDOMImplementation(); } public Document parse(InputSource is) throws SAXException, IOException { if (is == null) { throw new IllegalArgumentException("InputSource cannot be null"); } if (er != null) { domParser.setEntityResolver(er); } if (eh != null) { domParser.setErrorHandler(eh); } domParser.parse(is); return domParser.getDocument(); } public boolean isNamespaceAware() { return namespaceAware; } public boolean isValidating() { return validating; } public void setEntityResolver(org.xml.sax.EntityResolver er) { this.er = er; } public void setErrorHandler(org.xml.sax.ErrorHandler eh) { // If app passes in a ErrorHandler of null, then ignore all errors // and warnings this.eh = (eh == null) ? new DefaultHandler() : eh; } }
package org.exist.xquery.functions.text; import org.exist.dom.DocumentSet; import org.exist.dom.NodeSet; import org.exist.dom.QName; import org.exist.security.PermissionDeniedException; import org.exist.util.Occurrences; import org.exist.xquery.BasicFunction; import org.exist.xquery.Cardinality; import org.exist.xquery.FunctionCall; import org.exist.xquery.FunctionSignature; import org.exist.xquery.XPathException; import org.exist.xquery.XQueryContext; import org.exist.xquery.value.FunctionReference; import org.exist.xquery.value.IntegerValue; import org.exist.xquery.value.Sequence; import org.exist.xquery.value.SequenceType; import org.exist.xquery.value.StringValue; import org.exist.xquery.value.Type; import org.exist.xquery.value.ValueSequence; /** * @author wolf */ public class IndexTerms extends BasicFunction { public final static FunctionSignature signature = new FunctionSignature( new QName("index-terms", TextModule.NAMESPACE_URI, TextModule.PREFIX), "This function can be used to collect some information on the distribution " + "of index terms within a set of nodes. The set of nodes is specified in the first " + "argument $a. The function returns term frequencies for all terms in the index found " + "in descendants of the nodes in $a. The second argument $b specifies " + "a start string. Only terms starting with the specified character sequence are returned. " + "$c is a function reference, which points to a callback function that will be called " + "for every term occurrence. $d defines the maximum number of terms that should be " + "reported. The function reference for $c can be created with the util:function " + "function. It can be an arbitrary user-defined function, but it should take exactly 2 arguments: " + "1) the current term as found in the index as xs:string, 2) a sequence containing three int " + "values: a) the overall frequency of the term within the node set, b) the number of distinct " + "documents in the node set the term occurs in, c) the current position of the term in the whole " + "list of terms returned.", new SequenceType[]{ new SequenceType(Type.NODE, Cardinality.ZERO_OR_MORE), new SequenceType(Type.STRING, Cardinality.EXACTLY_ONE), new SequenceType(Type.FUNCTION_REFERENCE, Cardinality.EXACTLY_ONE), new SequenceType(Type.INT, Cardinality.EXACTLY_ONE) }, new SequenceType(Type.ITEM, Cardinality.ZERO_OR_MORE)); public IndexTerms(XQueryContext context) { super(context, signature); } /* (non-Javadoc) * @see org.exist.xquery.BasicFunction#eval(org.exist.xquery.value.Sequence[], org.exist.xquery.value.Sequence) */ public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException { if(args[0].getLength() == 0) return Sequence.EMPTY_SEQUENCE; NodeSet nodes = args[0].toNodeSet(); DocumentSet docs = nodes.getDocumentSet(); String start = args[1].getStringValue(); FunctionReference ref = (FunctionReference) args[2].itemAt(0); int max = ((IntegerValue) args[3].itemAt(0)).getInt(); FunctionCall call = ref.getFunctionCall(); Sequence result = new ValueSequence(); try { Occurrences occur[] = context.getBroker().getTextEngine().scanIndexTerms(docs, nodes, start, null); int len = (occur.length > max ? max : occur.length); Sequence params[] = new Sequence[2]; ValueSequence data = new ValueSequence(); for (int j = 0; j < len; j++) { params[0] = new StringValue(occur[j].getTerm().toString()); data.add(new IntegerValue(occur[j].getOccurrences(), Type.UNSIGNED_INT)); data.add(new IntegerValue(occur[j].getDocuments(), Type.UNSIGNED_INT)); data.add(new IntegerValue(j + 1, Type.UNSIGNED_INT)); params[1] = data; result.addAll(call.evalFunction(contextSequence, null, params)); data.clear(); } LOG.debug("Returning: " + result.getLength()); return result; } catch (PermissionDeniedException e) { throw new XPathException(getASTNode(), e.getMessage(), e); } } }
package imcode.server.parser ; import java.util.Properties ; import java.text.SimpleDateFormat ; import org.apache.oro.text.regex.* ; import org.apache.log4j.Category; /** Stores all info about a menuitem **/ public class MenuItem extends Document implements imcode.server.IMCConstants { private final static String CVS_REV = "$Revision$" ; private final static String CVS_DATE = "$Date$" ; private final static Category log = Category.getInstance( "server" ); private int sortKey ; private Menu parentMenu; private static Pattern HASHTAG_PATTERN = null ; static { Perl5Compiler patComp = new Perl5Compiler() ; try { HASHTAG_PATTERN = patComp.compile("#[^#\"<>\\s]+#",Perl5Compiler.READ_ONLY_MASK) ; } catch (MalformedPatternException ignored) { // I ignore the exception because i know that these patterns work, and that the exception will never be thrown. log.fatal( "Danger, Will Robinson!",ignored ) ; } } public MenuItem (Menu parent) { this.parentMenu = parent ; } /** * Get the value of parentMenu. * @return value of parentMenu. */ public Menu getParentMenu() { return parentMenu; } /** * Get the value of sortKey. * @return value of sortKey. */ public int getSortKey() { return sortKey; } /** * Set the value of sortKey. * @param v Value to assign to sortKey. */ public void setSortKey(int v) { this.sortKey = v; } /** Parse this menuitem into a template with the correct tags. **/ public Substitution getSubstitution(Properties parameters) { String image = getImage() ; image = (image != null && image.length() > 0) ? ("<img src=\""+image+"\" border=\"0\">") : "" ; String headline = getHeadline() ; if ( headline.length() == 0 ) { headline = "&nbsp;" ; } else { if ( !isActive() ) { headline = "<em><i>" + headline ; headline += "</i></em>" ; } if ( isArchived() ) { headline = "<strike>"+headline ; headline += "</strike>" ; } } SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd") ; String createdDate = dateFormat.format(getCreatedDatetime()) ; String modifiedDate = dateFormat.format(getModifiedDatetime()) ; Properties tags = new Properties() ; tags.setProperty("#childMetaId#",""+getMetaId()) ; tags.setProperty("#childMetaHeadline#",headline) ; tags.setProperty("#childMetaText#",getText()) ; tags.setProperty("#childMetaImage#",image) ; tags.setProperty("#childCreatedDate#",createdDate) ; tags.setProperty("#childModifiedDate#",modifiedDate) ; tags.setProperty("#menuitemmetaid#",""+getMetaId()) ; tags.setProperty("#menuitemheadline#",headline) ; tags.setProperty("#menuitemtext#",getText()) ; tags.setProperty("#menuitemimage#",image) ; tags.setProperty("#menuitemdatecreated#",createdDate) ; tags.setProperty("#menuitemdatemodified#",modifiedDate) ; // If this doc is a file, we'll want to put in the filename // as an escaped translated path // For example: /servlet/GetDoc/filename.ext?meta_id=1234 String template = parameters.getProperty("template") ; String href = "GetDoc"+(getFilename() == null || getFilename().length() == 0 ? "" : "/"+java.net.URLEncoder.encode(getFilename()))+"?meta_id="+getMetaId()+(template!=null ? "&template="+java.net.URLEncoder.encode(template) : ""); String a_href = "<a href=\""+href+(!"_self".equals(getTarget()) ? "\" target=\""+getTarget() : "")+"\">" ; if ( getParentMenu().isMenuMode() ) { if (getParentMenu().getSortOrder() == MENU_SORT_BY_MANUAL_ORDER) { a_href = "<input type=\"text\" name=\""+getMetaId()+"\" value=\""+getSortKey()+"\" size=\"4\" maxlength=\"4\">" + a_href ; } a_href = "<input type=\"checkbox\" name=\"archiveDelBox\" value=\""+getMetaId()+"\">" + a_href ; } tags.setProperty("#menuitemlink#", a_href ) ; tags.setProperty("#/menuitemlink#", getParentMenu().isMenuMode() && isEditable() ? "</a>&nbsp;<a href=\"AdminDoc?meta_id="+getMetaId()+"\"><img src=\""+getParentMenu().getImageUrl()+"txt.gif\" border=\"0\"></a>" : "</a>") ; return new MapSubstitution(tags,true) ; } }
package org.jaudiotagger.audio.mp4.atom; import org.jaudiotagger.audio.generic.Utils; import java.nio.ByteBuffer; /** * StsdBox ( sample (frame encoding) description box), holds the Stereo/No of Channels * * <p>4 bytes version/flags = byte hex version + 24-bit hex flags (current = 0) * -> 6 bytes reserved = 48-bit value set to zero -> 2 bytes data reference index = short unsigned index from 'dref' box -> 2 bytes QUICKTIME audio encoding version = short hex version - default = 0 ; audio data size before decompression = 1 -> 2 bytes QUICKTIME audio encoding revision level = byte hex version - default = 0 ; video can revise this value -> 4 bytes QUICKTIME audio encoding vendor = long ASCII text string - default = 0 -> 2 bytes audio channels = short unsigned count (mono = 1 ; stereo = 2) -> 2 bytes audio sample size = short unsigned value (8 or 16) -> 2 bytes QUICKTIME audio compression id = short integer value - default = 0 -> 2 bytes QUICKTIME audio packet size = short value set to zero -> 4 bytes audio sample rate = long unsigned fixed point rate */ public class Mp4Mp4aBox extends AbstractMp4Box { public static final int RESERVED_POS = 0; public static final int REFERENCE_INDEX_POS = 6; public static final int AUDIO_ENCODING_POS = 8; public static final int AUDIO_REVISION_POS = 10; public static final int AUDIO_ENCODING_VENDOR_POS= 12; public static final int CHANNELS_POS = 16; public static final int AUDIO_SAMPLE_SIZE_POS = 18; public static final int AUDIO_COMPRESSION_ID_POS = 20; public static final int AUDIO_PACKET_SIZE_POS = 22; public static final int AUDIO_SAMPLE_RATE_POS = 24; public static final int RESERVED_LENGTH = 6; public static final int REFERENCE_INDEX_LENGTH = 2; public static final int AUDIO_ENCODING_LENGTH = 2; public static final int AUDIO_REVISION_LENGTH = 2; public static final int AUDIO_ENCODING_VENDOR_LENGTH = 4; public static final int CHANNELS_LENGTH = 2; public static final int AUDIO_SAMPLE_SIZE_LENGTH = 2; public static final int AUDIO_COMPRESSION_ID_LENGTH = 2; public static final int AUDIO_PACKET_SIZE_LENGTH = 2; public static final int AUDIO_SAMPLE_RATE_LENGTH = 4; private int numberOfChannels; /** * * @param header header info * @param dataBuffer data of box (doesnt include header data) */ public Mp4Mp4aBox(Mp4BoxHeader header, ByteBuffer dataBuffer) { this.header = header; this.numberOfChannels = Utils.getNumberBigEndian(dataBuffer, CHANNELS_POS, (CHANNELS_POS + CHANNELS_LENGTH - 1)); } public int getNumberOfChannels() { return numberOfChannels; } }
package massim; import massim.config.TeamConfig; import massim.protocol.Message; import massim.protocol.MessageContent; import massim.protocol.messagecontent.*; import massim.util.Log; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import java.io.*; import java.net.Socket; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicLong; /** * Handles agent accounts and network connections to all agents. * @author ta10 */ class AgentManager { private Map<String, AgentProxy> agents = new HashMap<>(); private long agentTimeout; private boolean disconnecting = false; private int maxPacketLength; /** * Creates a new agent manager responsible for sending and receiving messages. * @param teams a list of all teams to configure the manager for * @param agentTimeout the timeout to use for request-action messages (to wait for actions) in milliseconds * @param maxPacketLength the maximum size of packets to <b>process</b> (they are received anyway, just not parsed * in case they are too big) */ AgentManager(List<TeamConfig> teams, long agentTimeout, int maxPacketLength) { teams.forEach(team -> team.getAgentNames().forEach((name) -> { agents.put(name, new AgentProxy(name, team.getName(), team.getPassword(name))); })); this.agentTimeout = agentTimeout; this.maxPacketLength = maxPacketLength; } /** * Stops all related threads and closes all sockets involved. */ void stop(){ disconnecting = true; agents.values().parallelStream().forEach(AgentProxy::close); } /** * Sets a new socket for the given agent that was just authenticated (again or for the first time). * @param s the new socket opened for the agent * @param agentName the name of the agent */ void setSocket(Socket s, String agentName){ if (agents.containsKey(agentName)){ agents.get(agentName).setSocket(s); agents.get(agentName).resendSimStartMessage(); } } /** * Checks if the given credentials are valid. * @param user name of the agent * @param inPass password of the agent * @return true iff the credentials are valid */ boolean auth(String user, String inPass) { return agents.containsKey(user) && agents.get(user).password.equals(inPass); } /** * Sends initial percepts to the agents and stores them for later (possible agent reconnection). * @param initialPercepts mapping from agent names to initial percepts */ void handleInitialPercepts(Map<String, SimStart> initialPercepts) { initialPercepts.forEach((agName, percept) -> { if (agents.containsKey(agName)){ agents.get(agName).handleInitialPercept(percept); } }); } /** * Uses the percepts to send a request-action message and waits for the action answers. * {@link #agentTimeout} is used to limit the waiting time per agent. * @param percepts mapping from agent names to percepts of the current simulation state * @return mapping from agent names to actions received in response */ Map<String, Action> requestActions(Map<String, RequestAction> percepts) { // each thread needs to countdown the latch when it finishes CountDownLatch latch = new CountDownLatch(percepts.keySet().size()); Map<String, Action> resultMap = new ConcurrentHashMap<>(); percepts.forEach((agName, percept) -> { // start a new thread to get each action new Thread(() -> resultMap.put(agName, agents.get(agName).requestAction(percept, latch))).start(); }); try { latch.await(2 * agentTimeout, TimeUnit.MILLISECONDS); // timeout ensured by threads; use this one for safety reasons } catch (InterruptedException e) { Log.log(Log.Level.ERROR, "Latch interrupted. Actions probably incomplete."); } return resultMap; } /** * Sends sim-end percepts to the agents. * @param finalPercepts mapping from agent names to sim-end percepts */ void handleFinalPercepts(Map<String, SimEnd> finalPercepts) { finalPercepts.forEach((agName, percept) -> { if (agents.containsKey(agName)){ agents.get(agName).handleFinalPercept(percept); } }); } /** * Stores account info of an agent. * Receives messages from and sends messages to remote agents. */ private class AgentProxy { // things that do not change private String name; private String teamName; private String password; // networking things private Socket socket; private Thread sendThread; private Thread receiveThread; // concurrency magic private AtomicLong messageCounter = new AtomicLong(); private LinkedBlockingDeque<Document> sendQueue = new LinkedBlockingDeque<>(); private Map<Long, CompletableFuture<Document>> futureActions = new ConcurrentHashMap<>(); private Document lastSimStartMessage; /** * Creates a new instance with the given credentials. * @param name the name of the agent * @param team the name of the agent's team * @param pass the password to authenticate the agent with */ private AgentProxy(String name, String team, String pass) { this.name = name; this.teamName = team; this.password = pass; } /** * Creates a message for the given initial percept and sends it to the remote agent. * @param percept the initial percept to forward */ void handleInitialPercept(SimStart percept) { lastSimStartMessage = new Message(System.currentTimeMillis(), percept).toXML(); sendMessage(lastSimStartMessage); } /** * Creates a request-action message and sends it to the agent. * Should be called within a new thread, as it blocks up to {@link #agentTimeout} milliseconds. * @param percept the step percept to forward * @param latch the latch to count down after the action is acquired (or not) * @return the action that was received by the agent (or {@link Action#STD_NO_ACTION}) */ Action requestAction(RequestAction percept, CountDownLatch latch) { long id = messageCounter.getAndIncrement(); percept.finalize(id, System.currentTimeMillis() + agentTimeout); CompletableFuture<Document> futureAction = new CompletableFuture<>(); futureActions.put(id, futureAction); sendMessage(new Message(System.currentTimeMillis(), percept).toXML()); try { // wait for action to be received Document doc = futureAction.get(agentTimeout, TimeUnit.MILLISECONDS); Message msg = Message.parse(doc, Action.class); if(msg != null){ MessageContent content = msg.getContent(); if(content instanceof Action) { latch.countDown(); return (Action) content; } } } catch (InterruptedException | ExecutionException e) { Log.log(Log.Level.ERROR, "Interrupted while waiting for action."); } catch (TimeoutException e) { Log.log(Log.Level.NORMAL, "No valid action available in time for agent " + name + "."); } return Action.STD_NO_ACTION; } /** * Creates and send a sim-end message to the agent. * @param percept the percept to append to the message. */ void handleFinalPercept(SimEnd percept) { lastSimStartMessage = null; // now we can stop resending it sendMessage(new Message(System.currentTimeMillis(), percept).toXML()); } /** * Sets a new endpoint for sending and receiving messages. If a socket is already present, it is replaced and closed. * @param newSocket the new socket to use for this agent */ private void setSocket(Socket newSocket){ // potentially close old socket if (sendThread != null) sendThread.interrupt(); if (receiveThread != null) receiveThread.interrupt(); if (socket != null){ try { socket.close(); } catch (IOException ignored) {} } // set new socket and open new threads socket = newSocket; sendThread = new Thread(this::send); sendThread.start(); receiveThread = new Thread(this::receive); receiveThread.start(); } /** * Reads XML documents (0-terminated) from the socket. If any "packet" is bigger than * {@link #maxPacketLength}, the read bytes are immediately discarded until the next 0 byte. */ private void receive() { DocumentBuilder docBuilder; InputStream in; try { docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); in = new BufferedInputStream(socket.getInputStream()); ByteArrayOutputStream buffer = new ByteArrayOutputStream(maxPacketLength); int readBytes = 0; boolean skipping = false; while (!disconnecting){ int b = in.read(); if (!skipping && b != 0) buffer.write(b); if(b == -1) break; // stream ended if (b == 0){ if (skipping){ skipping = false; // new packet next up } else { // document complete Document doc = docBuilder.parse(new ByteArrayInputStream(buffer.toByteArray())); handleReceivedDoc(doc); buffer = new ByteArrayOutputStream(); readBytes = 0; } } if (readBytes++ >= maxPacketLength){ buffer = new ByteArrayOutputStream(); readBytes = 0; skipping = true; } } } catch (IOException e) { Log.log(Log.Level.ERROR, "Error receiving document. Stop receiving."); } catch (ParserConfigurationException e) { Log.log(Log.Level.ERROR, "Parser error. Stop receiving."); } catch (SAXException e) { e.printStackTrace(); } } /** * Handles one received document (from the remote agent). * @param doc the document that needs to be processed */ private void handleReceivedDoc(Document doc) { TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer; try { transformer = factory.newTransformer(); transformer.setOutputProperty("indent", "yes"); } catch (TransformerConfigurationException e) { return; } Element root = doc.getDocumentElement(); if (root == null) { Log.log(Log.Level.NORMAL, "Received document with missing root element."); } else if (root.getNodeName().equals("message")) { if (root.getAttribute("type").equals("action")) { long actionID; NodeList actions = root.getElementsByTagName("action"); if (actions.getLength() == 0) { Log.log(Log.Level.ERROR, "No action element inside action message."); return; } try { actionID = Long.parseLong(((Element)actions.item(0)).getAttribute("id")); Log.log(Log.Level.NORMAL, "Received action with id " + actionID + " from " + name); } catch (NumberFormatException e) { Log.log(Log.Level.ERROR, "Received invalid or no action id."); return; } if (futureActions.containsKey(actionID)){ futureActions.get(actionID).complete(doc); } } else { Log.log(Log.Level.NORMAL, "Received unknown message type."); try { transformer.transform(new DOMSource(doc), new StreamResult(System.out)); } catch(Exception ignored) {} } } else { Log.log(Log.Level.NORMAL,"Received invalid message."); try { transformer.transform(new DOMSource(doc), new StreamResult(System.out)); } catch(Exception ignored) {} } } /** * Sends all messages from {@link #sendQueue}, blocks if it is empty. */ private void send() { while (true) { try { if (disconnecting && sendQueue.isEmpty()) { // we can stop when everything is sent (e.g. the bye message) break; } Document sendDoc = sendQueue.take(); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); TransformerFactory.newInstance().newTransformer().transform( new DOMSource(sendDoc), new StreamResult(buffer)); // send packet OutputStream out = socket.getOutputStream(); out.write(buffer.toByteArray()); out.write(0); out.flush(); } catch (InterruptedException | TransformerException | IOException e) { Log.log(Log.Level.DEBUG, "Error writing to socket. Stop sending now."); break; } } } /** * Closes socket and stops threads (if they exist). */ private void close() { sendMessage(new Message(System.currentTimeMillis(), new Bye()).toXML()); try { sendThread.join(5000); // give bye-message some time to be sent (but not too much) } catch (InterruptedException e) { Log.log(Log.Level.ERROR, "Interrupted while waiting for disconnection."); } if (sendThread != null) sendThread.interrupt(); if (receiveThread != null) receiveThread.interrupt(); if (socket != null) { try { socket.close(); } catch (IOException ignored) {} } } /** * Puts the given message into the send queue as soon as possible. * @param message the message document to send */ private void sendMessage(Document message){ try { sendQueue.put(message); } catch (InterruptedException e) { Log.log(Log.Level.ERROR, "Interrupted while trying to put message into queue."); } } /** * If there already exists a sim start message, it is added to the front of the {@link #sendQueue}. */ void resendSimStartMessage() { Document message = lastSimStartMessage; if (message != null && !sendQueue.contains(message)){ sendQueue.addFirst(message); } } } }
// $Id: ClientGmsImpl.java,v 1.14 2004/09/14 13:00:33 belaban Exp $ package org.jgroups.protocols.pbcast; import org.jgroups.*; import org.jgroups.protocols.PingRsp; import org.jgroups.util.Promise; import org.jgroups.util.Util; import java.util.Enumeration; import java.util.Hashtable; import java.util.Vector; /** * Client part of GMS. Whenever a new member wants to join a group, it starts in the CLIENT role. * No multicasts to the group will be received and processed until the member has been joined and * turned into a SERVER (either coordinator or participant, mostly just participant). This class * only implements <code>Join</code> (called by clients who want to join a certain group, and * <code>ViewChange</code> which is called by the coordinator that was contacted by this client, to * tell the client what its initial membership is. * @author Bela Ban * @version $Revision: 1.14 $ */ public class ClientGmsImpl extends GmsImpl { Vector initial_mbrs=new Vector(11); boolean initial_mbrs_received=false; Promise join_promise=new Promise(); public ClientGmsImpl(GMS g) { gms=g; } public void init() throws Exception { super.init(); synchronized(initial_mbrs) { initial_mbrs.clear(); initial_mbrs_received=false; } join_promise.reset(); } /** * Joins this process to a group. Determines the coordinator and sends a unicast * handleJoin() message to it. The coordinator returns a JoinRsp and then broadcasts the new view, which * contains a message digest and the current membership (including the joiner). The joiner is then * supposed to install the new view and the digest and starts accepting mcast messages. Previous * mcast messages were discarded (this is done in PBCAST).<p> * If successful, impl is changed to an instance of ParticipantGmsImpl. * Otherwise, we continue trying to send join() messages to the coordinator, * until we succeed (or there is no member in the group. In this case, we create our own singleton group). * <p>When GMS.disable_initial_coord is set to true, then we won't become coordinator on receiving an initial * membership of 0, but instead will retry (forever) until we get an initial membership of > 0. * @param mbr Our own address (assigned through SET_LOCAL_ADDRESS) */ public void join(Address mbr) { Address coord=null; JoinRsp rsp=null; Digest tmp_digest=null; leaving=false; join_promise.reset(); while(!leaving) { findInitialMembers(); if(log.isDebugEnabled()) log.debug("initial_mbrs are " + initial_mbrs); if(initial_mbrs.size() == 0) { if(gms.disable_initial_coord) { if(log.isDebugEnabled()) log.debug("received an initial membership of 0, but cannot become coordinator (disable_initial_coord=" + gms.disable_initial_coord + "), will retry fetching the initial membership"); continue; } if(log.isDebugEnabled()) log.debug("no initial members discovered: creating group as first member"); becomeSingletonMember(mbr); return; } coord=determineCoord(initial_mbrs); if(coord == null) { if(log.isErrorEnabled()) log.error("could not determine coordinator from responses " + initial_mbrs); continue; } try { if(log.isDebugEnabled()) log.debug("sending handleJoin(" + mbr + ") to " + coord); sendJoinMessage(coord, mbr); rsp=(JoinRsp)join_promise.getResult(gms.join_timeout); if(rsp == null) { if(log.isWarnEnabled()) log.warn("handleJoin(" + mbr + ") failed, retrying"); } else { // 1. Install digest tmp_digest=rsp.getDigest(); if(tmp_digest != null) { tmp_digest.incrementHighSeqno(coord); // see DESIGN for an explanantion if(log.isDebugEnabled()) log.debug("digest is " + tmp_digest); gms.setDigest(tmp_digest); } else if(log.isErrorEnabled()) log.error("digest of JOIN response is null"); // 2. Install view if(log.isDebugEnabled()) log.debug("[" + gms.local_addr + "]: JoinRsp=" + rsp.getView() + " [size=" + rsp.getView().size() + "]\n\n"); if(rsp.getView() != null) { if(!installView(rsp.getView())) { if(log.isErrorEnabled()) log.error("view installation failed, retrying to join group"); continue; } gms.passUp(new Event(Event.BECOME_SERVER)); gms.passDown(new Event(Event.BECOME_SERVER)); return; } else if(log.isErrorEnabled()) log.error("view of JOIN response is null"); } } catch(Exception e) { if(log.isDebugEnabled()) log.debug("exception=" + e.toString() + ", retrying"); } Util.sleep(gms.join_retry_timeout); } } public void leave(Address mbr) { leaving=true; wrongMethod("leave"); } public void handleJoinResponse(JoinRsp join_rsp) { join_promise.setResult(join_rsp); // will wake up join() method } public void handleLeaveResponse() { ; // safely ignore this } public void suspect(Address mbr) { ; } public void unsuspect(Address mbr) { wrongMethod("unsuspect"); } public JoinRsp handleJoin(Address mbr) { wrongMethod("handleJoin"); return null; } /** Returns false. Clients don't handle leave() requests */ public void handleLeave(Address mbr, boolean suspected) { wrongMethod("handleLeave"); } /** * Does nothing. Discards all views while still client. */ public synchronized void handleViewChange(View new_view, Digest digest) { if(log.isDebugEnabled()) log.debug("view " + new_view.getMembers() + " is discarded as we are not a participant"); } /** * Called by join(). Installs the view returned by calling Coord.handleJoin() and * becomes coordinator. */ private boolean installView(View new_view) { Vector mems=new_view.getMembers(); if(log.isDebugEnabled()) log.debug("new_view=" + new_view); if(gms.local_addr == null || mems == null || !mems.contains(gms.local_addr)) { if(log.isErrorEnabled()) log.error("I (" + gms.local_addr + ") am not member of " + mems + ", will not install view"); return false; } gms.installView(new_view); gms.becomeParticipant(); gms.passUp(new Event(Event.BECOME_SERVER)); gms.passDown(new Event(Event.BECOME_SERVER)); return true; } /** Returns immediately. Clients don't handle suspect() requests */ public void handleSuspect(Address mbr) { wrongMethod("handleSuspect"); return; } public boolean handleUpEvent(Event evt) { Vector tmp; switch(evt.getType()) { case Event.FIND_INITIAL_MBRS_OK: tmp=(Vector)evt.getArg(); synchronized(initial_mbrs) { if(tmp != null && tmp.size() > 0) for(int i=0; i < tmp.size(); i++) initial_mbrs.addElement(tmp.elementAt(i)); initial_mbrs_received=true; initial_mbrs.notify(); } return false; // don't pass up the stack } return true; } void sendJoinMessage(Address coord, Address mbr) { Message msg; GMS.GmsHeader hdr; msg=new Message(coord, null, null); hdr=new GMS.GmsHeader(GMS.GmsHeader.JOIN_REQ, mbr); msg.putHeader(gms.getName(), hdr); gms.passDown(new Event(Event.MSG, msg)); } /** * Pings initial members. Removes self before returning vector of initial members. * Uses IP multicast or gossiping, depending on parameters. */ void findInitialMembers() { PingRsp ping_rsp; synchronized(initial_mbrs) { initial_mbrs.removeAllElements(); initial_mbrs_received=false; gms.passDown(new Event(Event.FIND_INITIAL_MBRS)); // the initial_mbrs_received flag is needed when passDown() is executed on the same thread, so when // it returns, a response might actually have been received (even though the initial_mbrs might still be empty) if(initial_mbrs_received == false) { try { initial_mbrs.wait(); } catch(Exception e) { } } for(int i=0; i < initial_mbrs.size(); i++) { ping_rsp=(PingRsp)initial_mbrs.elementAt(i); if(ping_rsp.own_addr != null && gms.local_addr != null && ping_rsp.own_addr.equals(gms.local_addr)) { initial_mbrs.removeElementAt(i); break; } } } } /** The coordinator is determined by a majority vote. If there are an equal number of votes for more than 1 candidate, we determine the winner randomly. */ Address determineCoord(Vector mbrs) { PingRsp mbr; Hashtable votes; int count, most_votes; Address winner=null, tmp; if(mbrs == null || mbrs.size() < 1) return null; votes=new Hashtable(5); // count *all* the votes (unlike the 2000 election) for(int i=0; i < mbrs.size(); i++) { mbr=(PingRsp)mbrs.elementAt(i); if(mbr.coord_addr != null) { if(!votes.containsKey(mbr.coord_addr)) votes.put(mbr.coord_addr, new Integer(1)); else { count=((Integer)votes.get(mbr.coord_addr)).intValue(); votes.put(mbr.coord_addr, new Integer(count + 1)); } } } if(log.isDebugEnabled()) { if(votes.size() > 1) if(log.isWarnEnabled()) log.warn("there was more than 1 candidate for coordinator: " + votes); else if(log.isDebugEnabled()) log.debug("election results: " + votes); } // determine who got the most votes most_votes=0; for(Enumeration e=votes.keys(); e.hasMoreElements();) { tmp=(Address)e.nextElement(); count=((Integer)votes.get(tmp)).intValue(); if(count > most_votes) { winner=tmp; // fixed July 15 2003 (patch submitted by Darren Hobbs, patch-id=771418) most_votes=count; } } votes.clear(); return winner; } void becomeSingletonMember(Address mbr) { Digest initial_digest; ViewId view_id=null; Vector mbrs=new Vector(1); // set the initial digest (since I'm the first member) initial_digest=new Digest(1); // 1 member (it's only me) initial_digest.add(gms.local_addr, 0, 0); // initial seqno mcast by me will be 1 (highest seen +1) gms.setDigest(initial_digest); view_id=new ViewId(mbr); // create singleton view with mbr as only member mbrs.addElement(mbr); gms.installView(new View(view_id, mbrs)); gms.becomeCoordinator(); // not really necessary - installView() should do it gms.passUp(new Event(Event.BECOME_SERVER)); gms.passDown(new Event(Event.BECOME_SERVER)); if(log.isDebugEnabled()) log.debug("created group (first member). My view is " + gms.view_id + ", impl is " + gms.getImpl().getClass().getName()); } }
package test.dr.distibutions; import dr.math.distributions.GammaDistribution; import dr.math.functionEval.GammaFunction; import junit.framework.TestCase; public class GammaDistributionTest extends TestCase{ GammaDistribution gamma; public void setUp(){ gamma = new GammaDistribution(1.0,1.0); } public void testPdf(){ for(int i = 0; i < 200.0; i++){ double j = i/500.0 + 1.0; double shape = 1.0/j; double scale = j; gamma.setShape(shape); gamma.setScale(scale); double value = gamma.nextGamma(); double mypdf = Math.pow(value, shape-1)/GammaFunction.gamma(shape) *Math.exp(-value/scale)/Math.pow(scale, shape); assertEquals(mypdf,gamma.pdf(value),1e-10); } gamma.setScale(1.0); gamma.setShape(1.0); } }
package org.jmist.framework.measurement; import org.jmist.framework.Material; import org.jmist.framework.Medium; import org.jmist.framework.ScatterRecord; import org.jmist.framework.SurfacePoint; import org.jmist.framework.reporting.DummyProgressMonitor; import org.jmist.framework.reporting.ProgressMonitor; import org.jmist.toolkit.Point2; import org.jmist.toolkit.Point3; import org.jmist.toolkit.SphericalCoordinates; import org.jmist.toolkit.Tuple; import org.jmist.toolkit.Vector3; /** * @author bkimmel * */ public final class Photometer { public Photometer(CollectorSphere collectorSphere) { this.collectorSphere = collectorSphere; } public void reset() { this.collectorSphere.reset(); } public void setSpecimen(Material specimen) { this.specimen = specimen; } public void setIncidentAngle(SphericalCoordinates incident) { this.incident = incident; this.in = incident.unit().opposite().toCartesian(); } public void setWavelength(double wavelength) { this.wavelengths = new Tuple(wavelength); } public Material getSpecimen() { return this.specimen; } public SphericalCoordinates getIncidentAngle() { return this.incident; } public double getWavelength() { return this.wavelengths.at(0); } public CollectorSphere getCollectorSphere() { return this.collectorSphere; } public void castPhoton() { this.castPhotons(1); } public void castPhotons(long n) { this.castPhotons(n, DummyProgressMonitor.getInstance()); } public void castPhotons(long n, ProgressMonitor monitor) { this.castPhotons(n, monitor, DEFAULT_PROGRESS_INTERVAL); } public void castPhotons(long n, ProgressMonitor monitor, long progressInterval) { long untilCallback = progressInterval; if (!monitor.notifyProgress(0.0)) { monitor.notifyCancelled(); return; } for (int i = 0; i < n; i++) { if (--untilCallback <= 0) { double progress = (double) i / (double) n; if (!monitor.notifyProgress(progress)) { monitor.notifyCancelled(); return; } untilCallback = progressInterval; } ScatterRecord rec = this.specimen.scatter(this.x, this.in, this.wavelengths); if (random.nextDouble() < rec.weightAt(0)) { this.collectorSphere.record(rec.scatteredRay().direction()); } } monitor.notifyComplete(); } private final CollectorSphere collectorSphere; private Material specimen; private SphericalCoordinates incident; private Vector3 in; private Tuple wavelengths; private final SurfacePoint x = new SurfacePoint() { @Override public Point3 location() { return Point3.ORIGIN; } @Override public Material material() { return specimen; } @Override public Medium ambientMedium() { return Medium.VACUUM; } @Override public Vector3 microfacetNormal() { return Vector3.K; } @Override public Vector3 normal() { return Vector3.K; } @Override public Vector3 tangent() { return Vector3.I; } @Override public Point2 textureCoordinates() { return Point2.ORIGIN; } }; private static final java.util.Random random = new java.util.Random(); private static final long DEFAULT_PROGRESS_INTERVAL = 1000; }
package org.mtransit.android.commons; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.ListIterator; import java.util.Locale; import java.util.concurrent.TimeUnit; import org.mtransit.android.commons.data.Route; import org.mtransit.android.commons.data.RouteTripStop; import org.mtransit.android.commons.task.MTAsyncTask; import android.content.Context; import android.database.Cursor; import android.database.MatrixCursor; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.text.TextUtils; public class LocationUtils implements MTLog.Loggable { private static final String TAG = LocationUtils.class.getSimpleName(); @Override public String getLogTag() { return TAG; } public static final long UPDATE_INTERVAL_IN_MS = TimeUnit.SECONDS.toMillis(5); public static final long FASTEST_INTERVAL_IN_MS = TimeUnit.SECONDS.toMillis(1); public static final long MIN_TIME = TimeUnit.SECONDS.toMillis(2); public static final float MIN_DISTANCE = 5; // 5 meters public static final long PREFER_ACCURACY_OVER_TIME_IN_MS = TimeUnit.SECONDS.toMillis(30); public static final int SIGNIFICANT_ACCURACY_IN_METERS = 200; // 200 meters public static final int SIGNIFICANT_DISTANCE_MOVED_IN_METERS = 5; // 5 meters public static final int LOCATION_CHANGED_ALLOW_REFRESH_IN_METERS = 10; public static final int LOCATION_CHANGED_NOTIFY_USER_IN_METERS = 100; public static final double MIN_AROUND_DIFF = 0.01; public static final double INC_AROUND_DIFF = 0.01; private static final String AROUND_TRUNC = "%.4g"; public static float FEET_PER_M = 3.2808399f; public static float FEET_PER_MILE = 5280; public static float METER_PER_KM = 1000f; public static final int MIN_NEARBY_LIST = 10; // 10; // 0; public static final int MAX_NEARBY_LIST = 20; // 20; // 100; // 25; public static final int MAX_POI_NEARBY_POIS_LIST = 10; public static final int MIN_NEARBY_LIST_COVERAGE_IN_METERS = 500; public static final int MIN_POI_NEARBY_POIS_LIST_COVERAGE_IN_METERS = 100; public static AroundDiff getNewDefaultAroundDiff() { return new AroundDiff(LocationUtils.MIN_AROUND_DIFF, LocationUtils.INC_AROUND_DIFF); } private LocationUtils() { } /** * @param location the location * @return a nice readable location string */ public static String locationToString(Location location) { if (location == null) { return null; } return String.format("%s > %s,%s (%s) %s seconds ago", location.getProvider(), location.getLatitude(), location.getLongitude(), location.getAccuracy(), TimeUtils.millisToSec(TimeUtils.currentTimeMillis() - location.getTime())); } public static Location getNewLocation(double lat, double lng) { return getNewLocation(lat, lng, null); } public static Location getNewLocation(double lat, double lng, Float optAccuracy) { Location newLocation = new Location("MT"); newLocation.setLatitude(lat); newLocation.setLongitude(lng); if (optAccuracy != null) { newLocation.setAccuracy(optAccuracy); } return newLocation; } public static float bearTo(double startLatitude, double startLongitude, double endLatitude, double endLongitude) { float[] results = new float[2]; Location.distanceBetween(startLatitude, startLongitude, endLatitude, endLongitude, results); return results[1]; } public static float distanceToInMeters(Location start, Location end) { if (start == null || end == null) { return -1f; } return distanceToInMeters(start.getLatitude(), start.getLongitude(), end.getLatitude(), end.getLongitude()); } public static float distanceToInMeters(double startLatitude, double startLongitude, double endLatitude, double endLongitude) { float[] results = new float[2]; Location.distanceBetween(startLatitude, startLongitude, endLatitude, endLongitude, results); return results[0]; } public static boolean isMoreRelevant(String tag, Location currentLocation, Location newLocation) { return isMoreRelevant(tag, currentLocation, newLocation, SIGNIFICANT_ACCURACY_IN_METERS, SIGNIFICANT_DISTANCE_MOVED_IN_METERS, PREFER_ACCURACY_OVER_TIME_IN_MS); } public static boolean isMoreRelevant(String tag, Location currentLocation, Location newLocation, int significantAccuracyInMeters, int significantDistanceMovedInMeters, long preferAccuracyOverTimeInMS) { if (newLocation == null) { return false; } if (currentLocation == null) { return true; } if (areTheSame(currentLocation, newLocation)) { return false; } long timeDelta = newLocation.getTime() - currentLocation.getTime(); boolean isSignificantlyNewer = timeDelta > preferAccuracyOverTimeInMS; boolean isSignificantlyOlder = timeDelta < -preferAccuracyOverTimeInMS; boolean isNewer = timeDelta > 0; if (isSignificantlyNewer) { return true; } else if (isSignificantlyOlder) { return false; } int accuracyDelta = (int) (newLocation.getAccuracy() - currentLocation.getAccuracy()); boolean isLessAccurate = accuracyDelta > 0; boolean isMoreAccurate = accuracyDelta < 0; boolean isSignificantlyLessAccurate = accuracyDelta > significantAccuracyInMeters; boolean isSignificantlyMoreAccurate = isMoreAccurate && accuracyDelta < -significantAccuracyInMeters; if (isSignificantlyMoreAccurate) { return true; } int distanceTo = (int) distanceToInMeters(currentLocation, newLocation); if (distanceTo < significantDistanceMovedInMeters) { return false; } boolean isFromSameProvider = isSameProvider(newLocation, currentLocation); if (isMoreAccurate) { return true; } else if (isNewer && !isLessAccurate) { return true; } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) { return true; } return false; } private static boolean isSameProvider(Location loc1, Location loc2) { if (loc1.getProvider() == null) { return loc2.getProvider() == null; } return loc1.getProvider().equals(loc2.getProvider()); } public static Address getLocationAddress(Context context, Location location) { if (!Geocoder.isPresent()) { return null; // not present } Geocoder geocoder = new Geocoder(context); try { int maxResults = 1; java.util.List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), maxResults); if (addresses == null || addresses.size() == 0) { return null; // no address found } return addresses.get(0); } catch (IOException ioe) { if (MTLog.isLoggable(android.util.Log.DEBUG)) { MTLog.w(TAG, ioe, "Can't find the address of the current location!"); } else { MTLog.w(TAG, "Can't find the address of the current location!"); } return null; } } public static String getLocationString(Context context, String initialString, Address locationAddress, Float accuracy) { StringBuilder sb = new StringBuilder(); if (context == null) { return sb.toString(); } boolean hasInitialString = !TextUtils.isEmpty(initialString); if (hasInitialString) { sb.append(initialString); } if (hasInitialString) { sb.append(" ("); } if (locationAddress != null) { if (locationAddress.getMaxAddressLineIndex() > 0) { sb.append(locationAddress.getAddressLine(0)); } else if (locationAddress.getThoroughfare() != null) { sb.append(locationAddress.getThoroughfare()); } else if (locationAddress.getLocality() != null) { sb.append(locationAddress.getLocality()); } else { sb.append(context.getString(R.string.unknown_address)); } } else { sb.append(context.getString(R.string.unknown_address)); } if (accuracy != null && accuracy > 0.0f) { sb.append(" ± ").append(getDistanceStringUsingPref(context, accuracy, accuracy)); } if (hasInitialString) { sb.append(")"); } return sb.toString(); } public static double truncAround(String loc) { return Double.parseDouble(truncAround(Double.parseDouble(loc))); } public static String truncAround(double loc) { return String.format(Locale.US, AROUND_TRUNC, loc); } public static String getDistanceStringUsingPref(Context context, float distanceInMeters, float accuracyInMeters) { String distanceUnit = PreferenceUtils.getPrefDefault(context, PreferenceUtils.PREFS_UNITS, PreferenceUtils.PREFS_UNITS_DEFAULT); return getDistanceString(distanceInMeters, accuracyInMeters, distanceUnit); } private static String getDistanceString(float distanceInMeters, float accuracyInMeters, String distanceUnit) { if (distanceUnit.equals(PreferenceUtils.PREFS_UNITS_IMPERIAL)) { float distanceInSmall = distanceInMeters * FEET_PER_M; float accuracyInSmall = accuracyInMeters * FEET_PER_M; return getDistance(distanceInSmall, accuracyInSmall, FEET_PER_MILE, 10, "ft", "mi"); } else { return getDistance(distanceInMeters, accuracyInMeters, METER_PER_KM, 1, "m", "km"); } } private static String getDistance(float distance, float accuracy, float smallPerBig, int threshold, String smallUnit, String bigUnit) { StringBuilder sb = new StringBuilder(); if (accuracy > distance) { if (accuracy > (smallPerBig / threshold)) { float accuracyInBigUnit = accuracy / smallPerBig; float niceAccuracyInBigUnit = Integer.valueOf(Math.round(accuracyInBigUnit * 10)).floatValue() / 10; sb.append("< ").append(niceAccuracyInBigUnit).append(" ").append(bigUnit); } else { int niceAccuracyInSmallUnit = Math.round(accuracy); sb.append("< ").append(getSimplerDistance(niceAccuracyInSmallUnit, accuracy)).append(" ").append(smallUnit); } } else { if (distance > (smallPerBig / threshold)) { float distanceInBigUnit = distance / smallPerBig; float niceDistanceInBigUnit = Integer.valueOf(Math.round(distanceInBigUnit * 10)).floatValue() / 10; sb.append(niceDistanceInBigUnit).append(" ").append(bigUnit); } else { int niceDistanceInSmallUnit = Math.round(distance); sb.append(getSimplerDistance(niceDistanceInSmallUnit, accuracy)).append(" ").append(smallUnit); } } return sb.toString(); } public static int getSimplerDistance(int distance, float accuracyF) { int accuracy = Math.round(accuracyF); int simplerDistance = Math.round(distance / 10f) * 10; if (Math.abs(simplerDistance - distance) < accuracy) { return simplerDistance; } else { return distance; // accuracy too good, have to keep real data } } private static final float MAX_DISTANCE_ON_EARTH_IN_METERS = 40075017f / 2f; public static float getAroundCoveredDistanceInMeters(double lat, double lng, double aroundDiff) { Area area = getArea(lat, lng, aroundDiff); float distanceToSouth = area.minLat > MIN_LAT ? distanceToInMeters(lat, lng, area.minLat, lng) : MAX_DISTANCE_ON_EARTH_IN_METERS; float distanceToNorth = area.maxLat < MAX_LAT ? distanceToInMeters(lat, lng, area.maxLat, lng) : MAX_DISTANCE_ON_EARTH_IN_METERS; float distanceToWest = area.minLng > MIN_LNG ? distanceToInMeters(lat, lng, lat, area.minLng) : MAX_DISTANCE_ON_EARTH_IN_METERS; float distanceToEast = area.maxLng < MAX_LNG ? distanceToInMeters(lat, lng, lat, area.maxLng) : MAX_DISTANCE_ON_EARTH_IN_METERS; float[] distances = new float[] { distanceToNorth, distanceToSouth, distanceToWest, distanceToEast }; Arrays.sort(distances); return distances[0]; // return the closest } public static Area getArea(double lat, double lng, double aroundDiff) { // latitude double latTrunc = Math.abs(lat); double latBefore = Math.signum(lat) * Double.parseDouble(truncAround(latTrunc - aroundDiff)); double latAfter = Math.signum(lat) * Double.parseDouble(truncAround(latTrunc + aroundDiff)); // longitude double lngTrunc = Math.abs(lng); double lngBefore = Math.signum(lng) * Double.parseDouble(truncAround(lngTrunc - aroundDiff)); double lngAfter = Math.signum(lng) * Double.parseDouble(truncAround(lngTrunc + aroundDiff)); double minLat = Math.min(latBefore, latAfter); if (minLat < MIN_LAT) { minLat = MIN_LAT; } double maxLat = Math.max(latBefore, latAfter); if (maxLat > MAX_LAT) { maxLat = MAX_LAT; } double minLng = Math.min(lngBefore, lngAfter); if (minLng < MIN_LNG) { minLng = MIN_LNG; } double maxLng = Math.max(lngBefore, lngAfter); if (maxLng > MAX_LNG) { maxLng = MAX_LNG; } return new Area(minLat, maxLat, minLng, maxLng); } private static final double MAX_LAT = 90.0f; private static final double MIN_LAT = -90.0f; private static final double MAX_LNG = 180.0f; private static final double MIN_LNG = -180.0f; public static String genAroundWhere(String lat, String lng, String latTableColumn, String lngTableColumn, double aroundDiff) { StringBuilder qb = new StringBuilder(); Area area = getArea(truncAround(lat), truncAround(lng), aroundDiff); qb.append(latTableColumn).append(" BETWEEN ").append(area.minLat).append(" AND ").append(area.maxLat); qb.append(" AND "); qb.append(lngTableColumn).append(" BETWEEN ").append(area.minLng).append(" AND ").append(area.maxLng); return qb.toString(); } public static String genAroundWhere(double lat, double lng, String latTableColumn, String lngTableColumn, double aroundDiff) { return genAroundWhere(String.valueOf(lat), String.valueOf(lng), latTableColumn, lngTableColumn, aroundDiff); } public static String genAroundWhere(Location location, String latTableColumn, String lngTableColumn, double aroundDiff) { return genAroundWhere(String.valueOf(location.getLatitude()), String.valueOf(location.getLongitude()), latTableColumn, lngTableColumn, aroundDiff); } public static void updateDistance(HashMap<?, ? extends LocationPOI> pois, Location location) { if (location == null) { return; } updateDistance(pois, location.getLatitude(), location.getLongitude()); } public static void updateDistance(HashMap<?, ? extends LocationPOI> pois, double lat, double lng) { if (pois == null) { return; } for (LocationPOI poi : pois.values()) { if (!poi.hasLocation()) { continue; } poi.setDistance(distanceToInMeters(lat, lng, poi.getLat(), poi.getLng())); } } public static void updateDistanceWithString(Context context, Collection<? extends LocationPOI> pois, Location currentLocation, MTAsyncTask<?, ?, ?> task) { if (pois == null || currentLocation == null) { return; } String distanceUnit = PreferenceUtils.getPrefDefault(context, PreferenceUtils.PREFS_UNITS, PreferenceUtils.PREFS_UNITS_DEFAULT); float accuracyInMeters = currentLocation.getAccuracy(); for (LocationPOI poi : pois) { if (!poi.hasLocation()) { continue; } float newDistance = distanceToInMeters(currentLocation.getLatitude(), currentLocation.getLongitude(), poi.getLat(), poi.getLng()); if (poi.getDistance() > 1 && newDistance == poi.getDistance() && poi.getDistanceString() != null) { continue; } poi.setDistance(newDistance); poi.setDistanceString(getDistanceString(poi.getDistance(), accuracyInMeters, distanceUnit)); if (task != null && task.isCancelled()) { break; } } } public static void updateDistance(ArrayList<? extends LocationPOI> pois, Location location) { if (location == null) { return; } updateDistance(pois, location.getLatitude(), location.getLongitude()); } public static void updateDistance(ArrayList<? extends LocationPOI> pois, double lat, double lng) { if (pois == null) { return; } for (LocationPOI poi : pois) { if (!poi.hasLocation()) { continue; } poi.setDistance(distanceToInMeters(lat, lng, poi.getLat(), poi.getLng())); } } public static void updateDistanceWithString(Context context, LocationPOI poi, Location currentLocation) { if (poi == null || currentLocation == null) { return; } String distanceUnit = PreferenceUtils.getPrefDefault(context, PreferenceUtils.PREFS_UNITS, PreferenceUtils.PREFS_UNITS_DEFAULT); float accuracyInMeters = currentLocation.getAccuracy(); if (!poi.hasLocation()) { return; } float newDistance = distanceToInMeters(currentLocation.getLatitude(), currentLocation.getLongitude(), poi.getLat(), poi.getLng()); if (poi.getDistance() > 1 && newDistance == poi.getDistance() && poi.getDistanceString() != null) { return; } poi.setDistance(newDistance); poi.setDistanceString(getDistanceString(poi.getDistance(), accuracyInMeters, distanceUnit)); } public static boolean areAlmostTheSame(Location loc1, Location loc2, int distanceInMeters) { if (loc1 == null | loc2 == null) { return false; } return distanceToInMeters(loc1, loc2) < distanceInMeters; } public static boolean areTheSame(Location loc1, Location loc2) { if (loc1 == null) { return loc2 == null; } if (loc2 == null) { return false; } return areTheSame(loc1.getLatitude(), loc1.getLongitude(), loc2.getLatitude(), loc2.getLongitude()); } public static boolean areTheSame(Location loc1, double lat2, double lng2) { if (loc1 == null) { return false; } return areTheSame(loc1.getLatitude(), loc1.getLongitude(), lat2, lng2); } public static boolean areTheSame(double lat1, double lng1, double lat2, double lng2) { return lat1 == lat2 && lng1 == lng2; } public static void removeTooFar(ArrayList<? extends LocationPOI> pois, float maxDistance) { if (pois != null) { ListIterator<? extends LocationPOI> it = pois.listIterator(); while (it.hasNext()) { LocationPOI poi = it.next(); if (poi.getDistance() > maxDistance) { it.remove(); } } } } public static void removeTooMuchWhenNotInCoverage(ArrayList<? extends LocationPOI> pois, float minCoverageInDistance, int maxSize) { if (pois != null) { CollectionUtils.sort(pois, POI_DISTANCE_COMPARATOR); int nbKeptInList = 0; ListIterator<? extends LocationPOI> it = pois.listIterator(); while (it.hasNext()) { LocationPOI poi = it.next(); if (poi.getDistance() > minCoverageInDistance && nbKeptInList >= maxSize) { it.remove(); } else { nbKeptInList++; } } } } public static boolean searchComplete(double lat, double lng, double aroundDiff) { Area area = getArea(lat, lng, aroundDiff); return searchComplete(area); } public static boolean searchComplete(Area area) { if (area.minLat > MIN_LAT) { return false; // more places to explore in the south } if (area.maxLat < MAX_LAT) { return false; // more places to explore in the north } if (area.minLng > MIN_LNG) { return false; // more places to explore to the west } if (area.maxLng < MAX_LNG) { return false; // more places to explore to the east } return true; // planet search completed! } public static void incAroundDiff(AroundDiff ad) { ad.aroundDiff += ad.incAroundDiff; ad.incAroundDiff *= 2; // warning, might return huge chunk of data if far away (all POIs or none) } public static boolean isInside(double lat, double lng, Area area) { if (area == null) { return false; } return lat > area.minLat && lat < area.maxLat && lng > area.minLng && lng < area.maxLng; } public static boolean areCompletelyOverlapping(Area area1, Area area2) { if (area1.minLat > area2.minLat && area1.maxLat < area2.maxLat) { if (area2.minLng > area1.minLng && area2.maxLng < area1.maxLng) { return true; // area 1 wider than area 2 but area 2 higher than area 1 } } if (area2.minLat > area1.minLat && area2.maxLat < area1.maxLat) { if (area1.minLng > area2.minLng && area1.maxLng < area2.maxLng) { return true; // area 2 wider than area 1 but area 1 higher than area 2 } } return false; } public static class AroundDiff { public double aroundDiff = LocationUtils.MIN_AROUND_DIFF; public double incAroundDiff = LocationUtils.INC_AROUND_DIFF; public AroundDiff() { } public AroundDiff(double aroundDiff, double incAroundDiff) { this.aroundDiff = aroundDiff; this.incAroundDiff = incAroundDiff; } @Override public String toString() { return new StringBuilder(AroundDiff.class.getSimpleName()).append('[') .append(this.aroundDiff) .append(',') .append(this.incAroundDiff) .append(']').toString(); } } public static class Area { public double minLat; public double maxLat; public double minLng; public double maxLng; public Area(double minLat, double maxLat, double minLng, double maxLng) { this.minLat = minLat; this.maxLat = maxLat; this.minLng = minLng; this.maxLng = maxLng; } @Override public String toString() { return new StringBuilder(Area.class.getSimpleName()).append('[') .append(this.minLat) .append(',') .append(this.maxLat) .append(',') .append(this.minLng) .append(',') .append(this.maxLng) .append(']').toString(); } public boolean isEntirelyInside(Area otherArea) { if (otherArea == null) { return false; } if (!isInside(this.minLat, this.minLng, otherArea)) { return false; // min lat, min lng } if (!isInside(this.minLat, this.maxLng, otherArea)) { return false; // min lat, max lng } if (!isInside(this.maxLat, this.minLng, otherArea)) { return false; // max lat, min lng } if (!isInside(this.maxLat, this.maxLng, otherArea)) { return false; // max lat, max lng } return true; } public static boolean areOverlapping(Area area1, Area area2) { if (area1 == null || area2 == null) { return false; // no data to compare } // AREA1 (at least partially) INSIDE AREA2 if (isInside(area1.minLat, area1.minLng, area2)) { return true; // min lat, min lng } if (isInside(area1.minLat, area1.maxLng, area2)) { return true; // min lat, max lng } if (isInside(area1.maxLat, area1.minLng, area2)) { return true; // max lat, min lng } if (isInside(area1.maxLat, area1.maxLng, area2)) { return true; // max lat, max lng } // AREA2 (at least partially) INSIDE AREA1 if (isInside(area2.minLat, area2.minLng, area1)) { return true; // min lat, min lng } if (isInside(area2.minLat, area2.maxLng, area1)) { return true; // min lat, max lng } if (isInside(area2.maxLat, area2.minLng, area1)) { return true; // max lat, min lng } if (isInside(area2.maxLat, area2.maxLng, area1)) { return true; // max lat, max lng } // OVERLAPPING return areCompletelyOverlapping(area1, area2); } public static Area fromCursor(Cursor cursor) { if (cursor == null) { return null; } try { double minLat = cursor.getDouble(0); double maxLat = cursor.getDouble(1); double minLng = cursor.getDouble(2); double maxLng = cursor.getDouble(3); return new Area(minLat, maxLat, minLng, maxLng); } catch (Exception e) { MTLog.w(TAG, e, "Error while reading cursor!"); return null; } } public static Cursor toCursor(Area area) { if (area == null) { return null; } try { MatrixCursor matrixCursor = new MatrixCursor(new String[] { "areaminlat", "areamaxlat", "areaminlng", "areamaxlng" }); matrixCursor.addRow(new Object[] { area.minLat, area.maxLat, area.minLng, area.maxLng }); return matrixCursor; } catch (Exception e) { MTLog.w(TAG, "Error while creating cursor!"); return null; } } } public static final POIDistanceComparator POI_DISTANCE_COMPARATOR = new POIDistanceComparator(); public static class POIDistanceComparator implements Comparator<LocationPOI> { @Override public int compare(LocationPOI lhs, LocationPOI rhs) { if (lhs instanceof RouteTripStop && rhs instanceof RouteTripStop) { RouteTripStop alhs = (RouteTripStop) lhs; RouteTripStop arhs = (RouteTripStop) rhs; // IF same stop DO if (alhs.stop.id == arhs.stop.id) { // compare route shortName as integer String lShortName = alhs.route.shortName; String rShortName = arhs.route.shortName; if (!TextUtils.isEmpty(lShortName) || !TextUtils.isEmpty(rShortName)) { return Route.SHORT_NAME_COMPATOR.compare(alhs.route, arhs.route); } } } float d1 = lhs.getDistance(); float d2 = rhs.getDistance(); if (d1 > d2) { return ComparatorUtils.AFTER; } else if (d1 < d2) { return ComparatorUtils.BEFORE; } else { return ComparatorUtils.SAME; } } } public static interface LocationPOI { public Double getLat(); public void setLat(Double lat); public Double getLng(); public void setLng(Double lng); public boolean hasLocation(); public void setDistanceString(CharSequence distanceString); public CharSequence getDistanceString(); public void setDistance(float distance); public float getDistance(); } }
package com.jme3.input; import com.jme3.export.InputCapsule; import com.jme3.export.JmeExporter; import com.jme3.export.JmeImporter; import com.jme3.export.OutputCapsule; import com.jme3.input.controls.ActionListener; import com.jme3.input.controls.AnalogListener; import com.jme3.input.controls.MouseAxisTrigger; import com.jme3.input.controls.MouseButtonTrigger; import com.jme3.input.controls.Trigger; import com.jme3.math.FastMath; import com.jme3.math.Vector3f; import com.jme3.renderer.Camera; import com.jme3.renderer.RenderManager; import com.jme3.renderer.ViewPort; import com.jme3.scene.Spatial; import com.jme3.scene.control.Control; import java.io.IOException; /** * A camera that follows a spatial and can turn around it by dragging the mouse * @author nehon */ public class ChaseCamera implements ActionListener, AnalogListener, Control { private Spatial target = null; private float minVerticalRotation = 0.00f; private float maxVerticalRotation = FastMath.PI / 2; private float minDistance = 1.0f; private float maxDistance = 40.0f; private float distance = 20; private float zoomSpeed = 2f; private float rotationSpeed = 1.0f; private float rotation = 0; private float trailingRotationInertia = 0.05f; private float zoomSensitivity = 5f; private float rotationSensitivity = 5f; private float chasingSensitivity = 5f; private float trailingSensitivity = 0.5f; private float vRotation = FastMath.PI / 6; private boolean smoothMotion = false; private boolean trailingEnabled = true; private float rotationLerpFactor = 0; private float trailingLerpFactor = 0; private boolean rotating = false; private boolean vRotating = false; private float targetRotation = rotation; private InputManager inputManager; private Vector3f initialUpVec; private float targetVRotation = vRotation; private float vRotationLerpFactor = 0; private float targetDistance = distance; private float distanceLerpFactor = 0; private boolean zooming = false; private boolean trailing = false; private boolean chasing = false; private boolean canRotate; private float offsetDistance = 0.002f; private Vector3f prevPos; private boolean targetMoves = false; private boolean enabled = true; private Camera cam = null; private final Vector3f targetDir = new Vector3f(); private float previousTargetRotation; private final Vector3f pos = new Vector3f(); protected Vector3f targetLocation = new Vector3f(0, 0, 0); protected boolean dragToRotate = true; protected Vector3f lookAtOffset = new Vector3f(0, 0, 0); protected boolean leftClickRotate = true; protected boolean rightClickRotate = true; private Vector3f temp = new Vector3f(0, 0, 0); protected boolean invertYaxis = false; protected boolean invertXaxis = false; private final static String ChaseCamDown = "ChaseCamDown"; private final static String ChaseCamUp = "ChaseCamUp"; private final static String ChaseCamZoomIn = "ChaseCamZoomIn"; private final static String ChaseCamZoomOut = "ChaseCamZoomOut"; private final static String ChaseCamMoveLeft = "ChaseCamMoveLeft"; private final static String ChaseCamMoveRight = "ChaseCamMoveRight"; private final static String ChaseCamToggleRotate = "ChaseCamToggleRotate"; /** * Constructs the chase camera * @param cam the application camera * @param target the spatial to follow */ public ChaseCamera(Camera cam, final Spatial target) { this(cam); target.addControl(this); } /** * Constructs the chase camera * if you use this constructor you have to attach the cam later to a spatial * doing spatial.addControl(chaseCamera); * @param cam the application camera */ public ChaseCamera(Camera cam) { this.cam = cam; initialUpVec = cam.getUp().clone(); } /** * Constructs the chase camera, and registers inputs * if you use this constructor you have to attach the cam later to a spatial * doing spatial.addControl(chaseCamera); * @param cam the application camera * @param inputManager the inputManager of the application to register inputs */ public ChaseCamera(Camera cam, InputManager inputManager) { this(cam); registerWithInput(inputManager); } /** * Constructs the chase camera, and registers inputs * @param cam the application camera * @param target the spatial to follow * @param inputManager the inputManager of the application to register inputs */ public ChaseCamera(Camera cam, final Spatial target, InputManager inputManager) { this(cam, target); registerWithInput(inputManager); } public void onAction(String name, boolean keyPressed, float tpf) { if (dragToRotate) { if (name.equals(ChaseCamToggleRotate) && enabled) { if (keyPressed) { canRotate = true; inputManager.setCursorVisible(false); } else { canRotate = false; inputManager.setCursorVisible(true); } } } } private boolean zoomin; public void onAnalog(String name, float value, float tpf) { if (name.equals(ChaseCamMoveLeft)) { rotateCamera(-value); } else if (name.equals(ChaseCamMoveRight)) { rotateCamera(value); } else if (name.equals(ChaseCamUp)) { vRotateCamera(value); } else if (name.equals(ChaseCamDown)) { vRotateCamera(-value); } else if (name.equals(ChaseCamZoomIn)) { zoomCamera(-value); if (zoomin == false) { distanceLerpFactor = 0; } zoomin = true; } else if (name.equals(ChaseCamZoomOut)) { zoomCamera(+value); if (zoomin == true) { distanceLerpFactor = 0; } zoomin = false; } } /** * Registers inputs with the input manager * @param inputManager */ public final void registerWithInput(InputManager inputManager) { String[] inputs = {ChaseCamToggleRotate, ChaseCamDown, ChaseCamUp, ChaseCamMoveLeft, ChaseCamMoveRight, ChaseCamZoomIn, ChaseCamZoomOut}; this.inputManager = inputManager; if (!invertYaxis) { inputManager.addMapping(ChaseCamDown, new MouseAxisTrigger(MouseInput.AXIS_Y, true)); inputManager.addMapping(ChaseCamUp, new MouseAxisTrigger(MouseInput.AXIS_Y, false)); } else { inputManager.addMapping(ChaseCamDown, new MouseAxisTrigger(MouseInput.AXIS_Y, false)); inputManager.addMapping(ChaseCamUp, new MouseAxisTrigger(MouseInput.AXIS_Y, true)); } inputManager.addMapping(ChaseCamZoomIn, new MouseAxisTrigger(MouseInput.AXIS_WHEEL, false)); inputManager.addMapping(ChaseCamZoomOut, new MouseAxisTrigger(MouseInput.AXIS_WHEEL, true)); if(!invertXaxis){ inputManager.addMapping(ChaseCamMoveLeft, new MouseAxisTrigger(MouseInput.AXIS_X, true)); inputManager.addMapping(ChaseCamMoveRight, new MouseAxisTrigger(MouseInput.AXIS_X, false)); }else{ inputManager.addMapping(ChaseCamMoveLeft, new MouseAxisTrigger(MouseInput.AXIS_X, false)); inputManager.addMapping(ChaseCamMoveRight, new MouseAxisTrigger(MouseInput.AXIS_X, true)); } inputManager.addMapping(ChaseCamToggleRotate, new MouseButtonTrigger(MouseInput.BUTTON_LEFT)); inputManager.addMapping(ChaseCamToggleRotate, new MouseButtonTrigger(MouseInput.BUTTON_RIGHT)); inputManager.addListener(this, inputs); } /** * Sets custom triggers for toggleing the rotation of the cam * deafult are * new MouseButtonTrigger(MouseInput.BUTTON_LEFT) left mouse button * new MouseButtonTrigger(MouseInput.BUTTON_RIGHT) right mouse button * @param triggers */ public void setToggleRotationTrigger(Trigger... triggers) { inputManager.deleteMapping(ChaseCamToggleRotate); inputManager.addMapping(ChaseCamToggleRotate, triggers); inputManager.addListener(this, ChaseCamToggleRotate); } /** * Sets custom triggers for zomming in the cam * default is * new MouseAxisTrigger(MouseInput.AXIS_WHEEL, true) mouse wheel up * @param triggers */ public void setZoomInTrigger(Trigger... triggers) { inputManager.deleteMapping(ChaseCamZoomIn); inputManager.addMapping(ChaseCamZoomIn, triggers); inputManager.addListener(this, ChaseCamZoomIn); } /** * Sets custom triggers for zomming out the cam * default is * new MouseAxisTrigger(MouseInput.AXIS_WHEEL, false) mouse wheel down * @param triggers */ public void setZoomOutTrigger(Trigger... triggers) { inputManager.deleteMapping(ChaseCamZoomOut); inputManager.addMapping(ChaseCamZoomOut, triggers); inputManager.addListener(this, ChaseCamZoomOut); } private void computePosition() { float hDistance = (distance) * FastMath.sin((FastMath.PI / 2) - vRotation); pos.set(hDistance * FastMath.cos(rotation), (distance) * FastMath.sin(vRotation), hDistance * FastMath.sin(rotation)); pos.addLocal(target.getWorldTranslation()); } //rotate the camera around the target on the horizontal plane private void rotateCamera(float value) { if (!canRotate || !enabled) { return; } rotating = true; targetRotation += value * rotationSpeed; } //move the camera toward or away the target private void zoomCamera(float value) { if (!enabled) { return; } zooming = true; targetDistance += value * zoomSpeed; if (targetDistance > maxDistance) { targetDistance = maxDistance; } if (targetDistance < minDistance) { targetDistance = minDistance; } if ((targetVRotation < minVerticalRotation) && (targetDistance > (minDistance + 1.0f))) { targetVRotation = minVerticalRotation; } } //rotate the camera around the target on the vertical plane private void vRotateCamera(float value) { if (!canRotate || !enabled) { return; } vRotating = true; targetVRotation += value * rotationSpeed; if (targetVRotation > maxVerticalRotation) { targetVRotation = maxVerticalRotation; } if ((targetVRotation < minVerticalRotation) && (targetDistance > (minDistance + 1.0f))) { targetVRotation = minVerticalRotation; } } /** * Updates the camera, should only be called internally */ protected void updateCamera(float tpf) { if (enabled) { targetLocation.set(target.getWorldTranslation()).addLocal(lookAtOffset); if (smoothMotion) { //computation of target direction targetDir.set(targetLocation).subtractLocal(prevPos); float dist = targetDir.length(); //Low pass filtering on the target postition to avoid shaking when physics are enabled. if (offsetDistance < dist) { //target moves, start chasing. chasing = true; //target moves, start trailing if it has to. if (trailingEnabled) { trailing = true; } //target moves... targetMoves = true; } else { //if target was moving, we compute a slight offset in rotation to avoid a rought stop of the cam //We do not if the player is rotationg the cam if (targetMoves && !canRotate) { if (targetRotation - rotation > trailingRotationInertia) { targetRotation = rotation + trailingRotationInertia; } else if (targetRotation - rotation < -trailingRotationInertia) { targetRotation = rotation - trailingRotationInertia; } } //Target stops targetMoves = false; } //the user is rotating the cam by dragging the mouse if (canRotate) { //reseting the trailing lerp factor trailingLerpFactor = 0; //stop trailing user has the control trailing = false; } if (trailingEnabled && trailing) { if (targetMoves) { //computation if the inverted direction of the target Vector3f a = targetDir.negate().normalizeLocal(); //the x unit vector Vector3f b = Vector3f.UNIT_X; //2d is good enough a.y = 0; //computation of the rotation angle between the x axis and the trail if (targetDir.z > 0) { targetRotation = FastMath.TWO_PI - FastMath.acos(a.dot(b)); } else { targetRotation = FastMath.acos(a.dot(b)); } if (targetRotation - rotation > FastMath.PI || targetRotation - rotation < -FastMath.PI) { targetRotation -= FastMath.TWO_PI; } //if there is an important change in the direction while trailing reset of the lerp factor to avoid jumpy movements if (targetRotation != previousTargetRotation && FastMath.abs(targetRotation - previousTargetRotation) > FastMath.PI / 8) { trailingLerpFactor = 0; } previousTargetRotation = targetRotation; } //computing lerp factor trailingLerpFactor = Math.min(trailingLerpFactor + tpf * tpf * trailingSensitivity, 1); //computing rotation by linear interpolation rotation = FastMath.interpolateLinear(trailingLerpFactor, rotation, targetRotation); //if the rotation is near the target rotation we're good, that's over if (targetRotation + 0.01f >= rotation && targetRotation - 0.01f <= rotation) { trailing = false; trailingLerpFactor = 0; } } //linear interpolation of the distance while chasing if (chasing) { distance = temp.set(targetLocation).subtractLocal(cam.getLocation()).length(); distanceLerpFactor = Math.min(distanceLerpFactor + (tpf * tpf * chasingSensitivity * 0.05f), 1); distance = FastMath.interpolateLinear(distanceLerpFactor, distance, targetDistance); if (targetDistance + 0.01f >= distance && targetDistance - 0.01f <= distance) { distanceLerpFactor = 0; chasing = false; } } //linear interpolation of the distance while zooming if (zooming) { distanceLerpFactor = Math.min(distanceLerpFactor + (tpf * tpf * zoomSensitivity), 1); distance = FastMath.interpolateLinear(distanceLerpFactor, distance, targetDistance); if (targetDistance + 0.1f >= distance && targetDistance - 0.1f <= distance) { zooming = false; distanceLerpFactor = 0; } } //linear interpolation of the rotation while rotating horizontally if (rotating) { rotationLerpFactor = Math.min(rotationLerpFactor + tpf * tpf * rotationSensitivity, 1); rotation = FastMath.interpolateLinear(rotationLerpFactor, rotation, targetRotation); if (targetRotation + 0.01f >= rotation && targetRotation - 0.01f <= rotation) { rotating = false; rotationLerpFactor = 0; } } //linear interpolation of the rotation while rotating vertically if (vRotating) { vRotationLerpFactor = Math.min(vRotationLerpFactor + tpf * tpf * rotationSensitivity, 1); vRotation = FastMath.interpolateLinear(vRotationLerpFactor, vRotation, targetVRotation); if (targetVRotation + 0.01f >= vRotation && targetVRotation - 0.01f <= vRotation) { vRotating = false; vRotationLerpFactor = 0; } } //computing the position computePosition(); //setting the position at last cam.setLocation(pos.addLocal(lookAtOffset)); } else { //easy no smooth motion vRotation = targetVRotation; rotation = targetRotation; distance = targetDistance; computePosition(); cam.setLocation(pos.addLocal(lookAtOffset)); } //keeping track on the previous position of the target prevPos.set(targetLocation); //the cam looks at the target cam.lookAt(targetLocation, initialUpVec); } } /** * Return the enabled/disabled state of the camera * @return true if the camera is enabled */ public boolean isEnabled() { return enabled; } /** * Enable or disable the camera * @param enabled true to enable */ public void setEnabled(boolean enabled) { this.enabled = enabled; if (!enabled) { canRotate = false; // reset this flag in-case it was on before } } /** * Returns the max zoom distance of the camera (default is 40) * @return maxDistance */ public float getMaxDistance() { return maxDistance; } /** * Sets the max zoom distance of the camera (default is 40) * @param maxDistance */ public void setMaxDistance(float maxDistance) { this.maxDistance = maxDistance; } /** * Returns the min zoom distance of the camera (default is 1) * @return minDistance */ public float getMinDistance() { return minDistance; } /** * Sets the min zoom distance of the camera (default is 1) * @return minDistance */ public void setMinDistance(float minDistance) { this.minDistance = minDistance; } /** * clone this camera for a spatial * @param spatial * @return */ public Control cloneForSpatial(Spatial spatial) { ChaseCamera cc = new ChaseCamera(cam, spatial, inputManager); cc.setMaxDistance(getMaxDistance()); cc.setMinDistance(getMinDistance()); return cc; } /** * Sets the spacial for the camera control, should only be used internally * @param spatial */ public void setSpatial(Spatial spatial) { target = spatial; if (spatial == null) { return; } computePosition(); prevPos = new Vector3f(target.getWorldTranslation()); cam.setLocation(pos); } /** * update the camera control, should on ly be used internally * @param tpf */ public void update(float tpf) { updateCamera(tpf); } /** * renders the camera control, should on ly be used internally * @param rm * @param vp */ public void render(RenderManager rm, ViewPort vp) { //nothing to render } /** * Write the camera * @param ex the exporter * @throws IOException */ public void write(JmeExporter ex) throws IOException { OutputCapsule capsule = ex.getCapsule(this); capsule.write(maxDistance, "maxDistance", 40); capsule.write(minDistance, "minDistance", 1); } /** * Read the camera * @param im * @throws IOException */ public void read(JmeImporter im) throws IOException { InputCapsule ic = im.getCapsule(this); maxDistance = ic.readFloat("maxDistance", 40); minDistance = ic.readFloat("minDistance", 1); } /** * * @deprecated use getMaxVerticalRotation() */ @Deprecated public float getMaxHeight() { return getMaxVerticalRotation(); } /** * * @deprecated use setMaxVerticalRotation() */ @Deprecated public void setMaxHeight(float maxHeight) { setMaxVerticalRotation(maxHeight); } /** * * @deprecated use getMinVerticalRotation() */ @Deprecated public float getMinHeight() { return getMinVerticalRotation(); } /** * * @deprecated use setMinVerticalRotation() */ @Deprecated public void setMinHeight(float minHeight) { setMinVerticalRotation(minHeight); } /** * returns the maximal vertical rotation angle of the camera around the target * @return */ public float getMaxVerticalRotation() { return maxVerticalRotation; } /** * sets the maximal vertical rotation angle of the camera around the target default is Pi/2; * @param maxVerticalRotation */ public void setMaxVerticalRotation(float maxVerticalRotation) { this.maxVerticalRotation = maxVerticalRotation; } /** * returns the minimal vertical rotation angle of the camera around the target * @return */ public float getMinVerticalRotation() { return minVerticalRotation; } /** * sets the minimal vertical rotation angle of the camera around the target default is 0; * @param minHeight */ public void setMinVerticalRotation(float minHeight) { this.minVerticalRotation = minHeight; } /** * returns true is smmoth motion is enabled for this chase camera * @return */ public boolean isSmoothMotion() { return smoothMotion; } /** * Enables smooth motion for this chase camera * @param smoothMotion */ public void setSmoothMotion(boolean smoothMotion) { this.smoothMotion = smoothMotion; } /** * returns the chasing sensitivity * @return */ public float getChasingSensitivity() { return chasingSensitivity; } /** * Sets the chasing sensitivity, the lower the value the slower the camera will follow the target when it moves * @param chasingSensitivity */ public void setChasingSensitivity(float chasingSensitivity) { this.chasingSensitivity = chasingSensitivity; } /** * Returns the rotation sensitivity * @return */ public float getRotationSensitivity() { return rotationSensitivity; } /** * Sets the rotation sensitivity, the lower the value the slower the camera will rotates around the target when draging with the mouse * default is 5 * @param rotationSensitivity */ public void setRotationSensitivity(float rotationSensitivity) { this.rotationSensitivity = rotationSensitivity; } /** * returns true if the trailing is enabled * @return */ public boolean isTrailingEnabled() { return trailingEnabled; } /** * Enable the camera trailing : The camera smoothly go in the targets trail when it moves. * @param trailingEnabled */ public void setTrailingEnabled(boolean trailingEnabled) { this.trailingEnabled = trailingEnabled; } /** * returns the trailing rotation inertia * @return */ public float getTrailingRotationInertia() { return trailingRotationInertia; } /** * Sets the trailing rotation inertia : default is 0.1. This prevent the camera to roughtly stop when the target stops moving * before the camera reached the trail position. * @param trailingRotationInertia */ public void setTrailingRotationInertia(float trailingRotationInertia) { this.trailingRotationInertia = trailingRotationInertia; } /** * returns the trailing sensitivity * @return */ public float getTrailingSensitivity() { return trailingSensitivity; } /** * Sets the trailing sensitivity, the lower the value, the slower the camera will go in the target trail when it moves. * default is 0.5; * @param trailingSensitivity */ public void setTrailingSensitivity(float trailingSensitivity) { this.trailingSensitivity = trailingSensitivity; } /** * returns the zoom sensitivity * @return */ public float getZoomSensitivity() { return zoomSensitivity; } /** * Sets the zoom sensitivity, the lower the value, the slower the camera will zoom in and out. * default is 5. * @param zoomSensitivity */ public void setZoomSensitivity(float zoomSensitivity) { this.zoomSensitivity = zoomSensitivity; } /** * Sets the default distance at start of applicaiton * @param defaultDistance */ public void setDefaultDistance(float defaultDistance) { distance = defaultDistance; targetDistance = distance; } /** * sets the default horizontal rotation of the camera at start of the application * @param angle */ public void setDefaultHorizontalRotation(float angle) { rotation = angle; targetRotation = angle; } /** * sets the default vertical rotation of the camera at start of the application * @param angle */ public void setDefaultVerticalRotation(float angle) { vRotation = angle; targetVRotation = angle; } /** * @return If drag to rotate feature is enabled. * * @see FlyByCamera#setDragToRotate(boolean) */ public boolean isDragToRotate() { return dragToRotate; } /** * @param dragToRotate When true, the user must hold the mouse button * and drag over the screen to rotate the camera, and the cursor is * visible until dragged. Otherwise, the cursor is invisible at all times * and holding the mouse button is not needed to rotate the camera. * This feature is disabled by default. */ public void setDragToRotate(boolean dragToRotate) { this.dragToRotate = dragToRotate; this.canRotate = !dragToRotate; inputManager.setCursorVisible(dragToRotate); } /** * return the current distance from the camera to the target * @return */ public float getDistanceToTarget() { return distance; } /** * returns the current horizontal rotation around the target in radians * @return */ public float getHorizontalRotation() { return rotation; } /** * returns the current vertical rotation around the target in radians. * @return */ public float getVerticalRotation() { return vRotation; } /** * returns the offset from the target's position where the camera looks at * @return */ public Vector3f getLookAtOffset() { return lookAtOffset; } /** * Sets the offset from the target's position where the camera looks at * @param lookAtOffset */ public void setLookAtOffset(Vector3f lookAtOffset) { this.lookAtOffset = lookAtOffset; } /** * Sets the up vector of the camera used for the lookAt on the target * @param up */ public void setUpVector(Vector3f up){ initialUpVec=up; } /** * Returns the up vector of the camera used for the lookAt on the target * @return */ public Vector3f getUpVector(){ return initialUpVec; } /** * * @param invertYaxis * @deprecated use setInvertVerticalAxis */ @Deprecated public void setInvertYaxis(boolean invertYaxis) { setInvertVerticalAxis(invertYaxis); } /** * invert the vertical axis movement of the mouse * @param invertYaxis */ public void setInvertVerticalAxis(boolean invertYaxis) { this.invertYaxis = invertYaxis; inputManager.deleteMapping(ChaseCamDown); inputManager.deleteMapping(ChaseCamUp); if (!invertYaxis) { inputManager.addMapping(ChaseCamDown, new MouseAxisTrigger(MouseInput.AXIS_Y, true)); inputManager.addMapping(ChaseCamUp, new MouseAxisTrigger(MouseInput.AXIS_Y, false)); } else { inputManager.addMapping(ChaseCamDown, new MouseAxisTrigger(MouseInput.AXIS_Y, false)); inputManager.addMapping(ChaseCamUp, new MouseAxisTrigger(MouseInput.AXIS_Y, true)); } inputManager.addListener(this, ChaseCamDown, ChaseCamUp); } /** * invert the Horizontal axis movement of the mouse * @param invertYaxis */ public void setInvertHorizontalAxis(boolean invertXaxis) { this.invertXaxis = invertXaxis; inputManager.deleteMapping(ChaseCamMoveLeft); inputManager.deleteMapping(ChaseCamMoveRight); if(!invertXaxis){ inputManager.addMapping(ChaseCamMoveLeft, new MouseAxisTrigger(MouseInput.AXIS_X, true)); inputManager.addMapping(ChaseCamMoveRight, new MouseAxisTrigger(MouseInput.AXIS_X, false)); }else{ inputManager.addMapping(ChaseCamMoveLeft, new MouseAxisTrigger(MouseInput.AXIS_X, false)); inputManager.addMapping(ChaseCamMoveRight, new MouseAxisTrigger(MouseInput.AXIS_X, true)); } inputManager.addListener(this, ChaseCamMoveLeft, ChaseCamMoveRight); } }
package org.myrobotlab.service; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Stack; import org.apache.commons.codec.digest.DigestUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.myrobotlab.framework.ServiceType; import org.myrobotlab.io.FileIO; import org.myrobotlab.logging.Level; import org.myrobotlab.logging.LoggerFactory; import org.myrobotlab.logging.Logging; import org.myrobotlab.logging.LoggingFactory; import org.myrobotlab.service.abstracts.AbstractSpeechSynthesis; import org.myrobotlab.service.data.AudioData; import org.myrobotlab.service.interfaces.AudioListener; import org.myrobotlab.service.interfaces.SpeechRecognizer; import org.myrobotlab.service.interfaces.SpeechSynthesis; import org.myrobotlab.service.interfaces.TextListener; import org.slf4j.Logger; /** * Natural Reader speech to text service based on naturalreaders.com * This code is basically all the same as AcapelaSpeech... */ public class NaturalReaderSpeech extends AbstractSpeechSynthesis implements TextListener, AudioListener { private static final long serialVersionUID = 1L; transient public final static Logger log = LoggerFactory.getLogger(NaturalReaderSpeech.class); // default voice // TODO: natural reader has this voice.. there are others // but for now.. only Ryan is wired in.. it maps to voice id "33" String voice = "Ryan"; HashMap<String, Integer> voiceMap = new HashMap<String,Integer>(); ArrayList<String> voices = new ArrayList<String>(); transient AudioFile audioFile = null; // private float volume = 1.0f; transient CloseableHttpClient client; transient Stack<String> audioFiles = new Stack<String>(); // audioData to utterance map TODO: revisit the design of this transient HashMap<AudioData, String> utterances = new HashMap<AudioData, String>(); public NaturalReaderSpeech(String reservedKey) { super(reservedKey); } public void startService() { super.startService(); if (client == null) { // new MultiThreadedHttpConnectionManager() client = HttpClients.createDefault(); } audioFile = (AudioFile) startPeer("audioFile"); audioFile.startService(); subscribe(audioFile.getName(), "publishAudioStart"); subscribe(audioFile.getName(), "publishAudioEnd"); // attach a listener when the audio file ends playing. audioFile.addListener("finishedPlaying", this.getName(), "publishEndSpeaking"); // needed because of an ssl error on the natural reader site System.setProperty("jsse.enableSNIExtension", "false"); voiceMap.put("Mike",1); voiceMap.put("Crystal",11); voiceMap.put("Rich",13); voiceMap.put("Ray",14); voiceMap.put("Heather",26); voiceMap.put("Laura",17); voiceMap.put("Lauren",17); voiceMap.put("Ryan",33); voiceMap.put("Peter",31); voiceMap.put("Rachel",32); voiceMap.put("Charles",2); voiceMap.put("Audrey",3); voiceMap.put("Graham",25); voiceMap.put("Bruno",22); voiceMap.put("Alice",21); voiceMap.put("Alain",7); voiceMap.put("Juliette",8); voiceMap.put("Klaus",28); voiceMap.put("Sarah",35); voiceMap.put("Reiner",5); voiceMap.put("Klara",6); voiceMap.put("Rose",20); voiceMap.put("Alberto",19); voiceMap.put("Vittorio",36); voiceMap.put("Chiara",23); voiceMap.put("Anjali",4); voiceMap.put("Arnaud",9); voiceMap.put("Giovanni",10); voiceMap.put("Crystal",11); voiceMap.put("Francesca",12); voiceMap.put("Claire",15); voiceMap.put("Julia",16); voiceMap.put("Mel",18); voiceMap.put("Juli",27); voiceMap.put("Laura",29); voiceMap.put("Lucy",30); voiceMap.put("Salma",34); voiceMap.put("Tracy",37); voiceMap.put("Lulu",38); voiceMap.put("Sakura",39); voiceMap.put("Mehdi",40); voices.addAll(voiceMap.keySet()); } public AudioFile getAudioFile() { return audioFile; } @Override public ArrayList<String> getVoices() { return voices; } @Override public String getVoice() { return voice; } public String getMp3Url(String toSpeak) { // TODO: url encode this. String encoded = toSpeak; try { encoded = URLEncoder.encode(toSpeak, "UTF-8"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } int voiceId = voiceMap.get(voice); // TODO: expose thge "r=33" as the selection for Ryans voice. // TOOD: also the speed setting is passed in as s= String url = "https://api.naturalreaders.com/v2/tts/?t=" + encoded + "&r="+voiceId+"&s=0"; log.info("URL FOR AUDIO:{}",url); return url; } public byte[] getRemoteFile(String toSpeak) { String mp3Url = getMp3Url(toSpeak); HttpGet get = null; byte[] b = null; try { HttpResponse response = null; // fetch file get = new HttpGet(mp3Url); log.info("mp3Url {}", mp3Url); // get mp3 file & save to cache response = client.execute(get); log.info("got {}", response.getStatusLine()); HttpEntity entity = response.getEntity(); // cache the mp3 content b = FileIO.toByteArray(entity.getContent()); if (b == null || b.length == 0){ error("%s returned 0 byte file !!! - it may block you", getName()); } EntityUtils.consume(entity); } catch (Exception e) { Logging.logError(e); } finally { if (get != null) { get.releaseConnection(); } } return b; } @Override public boolean speakBlocking(String toSpeak) throws IOException { log.info("speak blocking {}", toSpeak); if (voice == null) { log.warn("voice is null! setting to default: Ryan"); voice = "Ryan"; } String localFileName = getLocalFileName(this, toSpeak, "mp3"); String filename = AudioFile.globalFileCacheDir + File.separator + localFileName; if (!audioFile.cacheContains(localFileName)) { byte[] b = getRemoteFile(toSpeak); audioFile.cache(localFileName, b, toSpeak); } invoke("publishStartSpeaking", toSpeak); audioFile.playBlocking(filename); invoke("publishEndSpeaking", toSpeak); log.info("Finished waiting for completion."); return false; } @Override public void setVolume(float volume) { // TODO: fix the volume control log.warn("Volume control not implemented in Natural Reader Speech yet."); } @Override public float getVolume() { return 0; } @Override public void interrupt() { // TODO: Implement me! } @Override public void onText(String text) { log.info("ON Text Called: {}", text); try { speak(text); } catch (Exception e) { Logging.logError(e); } } @Override public String getLanguage() { return null; } public AudioData speak(String toSpeak) throws IOException { // this will flip to true on the audio file end playing. AudioData ret = null; log.info("speak {}", toSpeak); if (voice == null) { log.warn("voice is null! setting to default: Ryan"); voice = "Ryan"; } String filename = this.getLocalFileName(this, toSpeak, "mp3"); if (audioFile.cacheContains(filename)) { ret = audioFile.playCachedFile(filename); utterances.put(ret, toSpeak); return ret; } audioFiles.push(filename); byte[] b = getRemoteFile(toSpeak); audioFile.cache(filename, b, toSpeak); ret = audioFile.playCachedFile(filename); utterances.put(ret, toSpeak); return ret; } public AudioData speak(String voice, String toSpeak) throws IOException { setVoice(voice); return speak(toSpeak); } @Override public String getLocalFileName(SpeechSynthesis provider, String toSpeak, String audioFileType) throws UnsupportedEncodingException { // TODO: make this a base class sort of thing. return provider.getClass().getSimpleName() + File.separator + URLEncoder.encode(provider.getVoice(), "UTF-8") + File.separator + DigestUtils.md5Hex(toSpeak) + "." + audioFileType; } @Override public void addEar(SpeechRecognizer ear) { // TODO: move this to a base class. it's basically the same for all // mouths/ speech synth stuff. // when we add the ear, we need to listen for request confirmation addListener("publishStartSpeaking", ear.getName(), "onStartSpeaking"); addListener("publishEndSpeaking", ear.getName(), "onEndSpeaking"); } public void onRequestConfirmation(String text) { try { speakBlocking(String.format("did you say. %s", text)); } catch (Exception e) { Logging.logError(e); } } @Override public List<String> getLanguages() { // TODO Auto-generated method stub ArrayList<String> ret = new ArrayList<String>(); // FIXME - add iso language codes currently supported e.g. en en_gb de // etc.. return ret; } @Override public String publishStartSpeaking(String utterance) { log.info("publishStartSpeaking {}", utterance); return utterance; } @Override public String publishEndSpeaking(String utterance) { log.info("publishEndSpeaking {}", utterance); return utterance; } @Override public void onAudioStart(AudioData data) { log.info("onAudioStart {} {}", getName(), data.toString()); // filters on only our speech if (utterances.containsKey(data)) { String utterance = utterances.get(data); invoke("publishStartSpeaking", utterance); } } @Override public void onAudioEnd(AudioData data) { log.info("onAudioEnd {} {}", getName(), data.toString()); // filters on only our speech if (utterances.containsKey(data)) { String utterance = utterances.get(data); invoke("publishEndSpeaking", utterance); utterances.remove(data); } } @Override public boolean setVoice(String voice) { if (voiceMap.containsKey(voice)) { this.voice = voice; return true; } return false; } @Override public void setLanguage(String l) { // TODO this is ignored.. only Ryan voice currently enabled. } static public ServiceType getMetaData() { ServiceType meta = new ServiceType(NaturalReaderSpeech.class.getCanonicalName()); meta.addDescription("Natural Reader based speech service."); meta.addCategory("speech"); meta.setSponsor("kwatters"); meta.addPeer("audioFile", "AudioFile", "audioFile"); // meta.addTodo("test speak blocking - also what is the return type and AudioFile audio track id ?"); meta.addDependency("org.apache.commons.httpclient", "4.5.2"); return meta; } public static void main(String[] args) throws Exception { LoggingFactory.init(Level.INFO); //try { // Runtime.start("webgui", "WebGui"); NaturalReaderSpeech speech = (NaturalReaderSpeech) Runtime.start("speech", "NaturalReaderSpeech"); // speech.setVoice("Ryan"); // TODO: fix the volume control // speech.setVolume(0); // speech.speakBlocking("does this work"); // speech.getMP3ForSpeech("hello world"); speech.speakBlocking("does this work"); speech.setVoice("Lauren"); speech.speakBlocking("horray for worky!"); } }
package com.jcabi.github.mock; import com.google.common.collect.Lists; import com.jcabi.github.Coordinates; import com.jcabi.github.Language; import com.jcabi.github.Milestones; import com.jcabi.github.Repo; import com.jcabi.github.Repos; import java.io.IOException; import javax.json.Json; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.Test; /** * Test case for {@link Repo}. * @author Yegor Bugayenko (yegor@tpc2.com) * @version $Id$ * @checkstyle MultipleStringLiterals (500 lines) */ public final class MkRepoTest { /** * Repo can work. * @throws Exception If some problem inside */ @Test public void works() throws Exception { final Repos repos = new MkRepos(new MkStorage.InFile(), "jeff"); final Repo repo = repos.create( Json.createObjectBuilder().add("name", "test").build() ); MatcherAssert.assertThat( repo.coordinates(), Matchers.hasToString("jeff/test") ); } /** * This tests that the milestones() method in MkRepo is working fine. * @throws Exception - if anything goes wrong. */ @Test public void returnsMkMilestones() throws Exception { final Repos repos = new MkRepos(new MkStorage.InFile(), "jeff"); final Repo repo = repos.create( Json.createObjectBuilder().add("name", "test1").build() ); final Milestones milestones = repo.milestones(); MatcherAssert.assertThat(milestones, Matchers.notNullValue()); } /** * Repo can fetch its commits. * * @throws IOException if some problem inside */ @Test public void fetchCommits() throws IOException { final String user = "testuser"; final Repo repo = new MkRepo( new MkStorage.InFile(), user, new Coordinates.Simple(user, "testrepo") ); MatcherAssert.assertThat(repo.commits(), Matchers.notNullValue()); } /** * Repo can exponse attributes. * @throws Exception If some problem inside */ @Test public void exposesAttributes() throws Exception { final Repo repo = new MkGithub().randomRepo(); MatcherAssert.assertThat( new Repo.Smart(repo).description(), Matchers.notNullValue() ); MatcherAssert.assertThat( new Repo.Smart(repo).isPrivate(), Matchers.is(false) ); } /** * Repo can return Stars API. * @throws IOException if some problem inside */ @Test public void fetchStars() throws IOException { final String user = "testuser2"; final Repo repo = new MkRepo( new MkStorage.InFile(), user, new Coordinates.Simple(user, "testrepo2") ); MatcherAssert.assertThat(repo.stars(), Matchers.notNullValue()); } /** * Repo can return Notifications API. * @throws IOException if some problem inside */ @Test public void fetchNotifications() throws IOException { final String user = "testuser3"; final Repo repo = new MkRepo( new MkStorage.InFile(), user, new Coordinates.Simple(user, "testrepo3") ); MatcherAssert.assertThat(repo.notifications(), Matchers.notNullValue()); } /** * Repo can return Languages iterable. * @throws IOException if some problem inside */ @Test public void fetchLanguages() throws IOException { final String user = "testuser4"; final Repo repo = new MkRepo( new MkStorage.InFile(), user, new Coordinates.Simple(user, "testrepo4") ); final Iterable<Language> languages = repo.languages(); MatcherAssert.assertThat(languages, Matchers.notNullValue()); final int size = 3; MatcherAssert.assertThat( Lists.newArrayList(languages), Matchers.hasSize(size) ); } }
package org.objectweb.proactive.ic2d.gui; import org.objectweb.proactive.ic2d.IC2D; import org.objectweb.proactive.ic2d.util.IC2DMessageLogger; import org.objectweb.proactive.ic2d.util.ActiveObjectFilter; import org.objectweb.proactive.ic2d.gui.ActiveObjectCommunicationRecorder; import org.objectweb.proactive.ic2d.gui.EventListsPanel; import org.objectweb.proactive.ic2d.gui.IC2DGUIController; import org.objectweb.proactive.ic2d.gui.Legend; import org.objectweb.proactive.ic2d.gui.data.IC2DPanel; import org.objectweb.proactive.ic2d.data.IC2DObject; import org.objectweb.proactive.ic2d.data.HostObject; import org.objectweb.proactive.ic2d.data.ActiveObject; import org.objectweb.proactive.ic2d.event.IC2DObjectListener; import org.objectweb.proactive.ic2d.spy.SpyEvent; import org.objectweb.proactive.ic2d.gui.process.FileChooser; import org.objectweb.proactive.ic2d.gui.process.ProcessControlFrame; import org.objectweb.proactive.ic2d.gui.process.GlobusProcessControlFrame; import org.objectweb.proactive.ic2d.gui.util.MessagePanel; import org.objectweb.proactive.ic2d.gui.util.DialogUtils; import org.objectweb.proactive.core.process.ExternalProcess; public class IC2DFrame extends javax.swing.JFrame implements IC2DObjectListener { private static final int DEFAULT_WIDTH = 850; private static final int DEFAULT_HEIGHT = 600; private int options; private IC2DPanel ic2dPanel; private IC2DObject ic2dObject; private IC2DMessageLogger logger; private IC2DGUIController controller; private ActiveObjectFilter activeObjectFilter; private ActiveObjectCommunicationRecorder communicationRecorder; private EventListsPanel eventListsPanel; private javax.swing.JFrame eventListsFrame; private javax.swing.JFrame processesFrame; private javax.swing.JFrame globusProcessFrame; private javax.swing.JFrame fileChooserFrame; private ExternalProcess externalProcess; public IC2DFrame(IC2DObject ic2dObject) { this(ic2dObject, IC2D.NOTHING); } public IC2DFrame(IC2DObject object, int options) { super("IC2D"); this.options = options; this.setSize(new java.awt.Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT)); this.ic2dObject = object; setJMenuBar(createMenuBar()); activeObjectFilter = new ActiveObjectFilter(); controller = new MyController(); communicationRecorder = new ActiveObjectCommunicationRecorder(); MessagePanel messagePanel = new MessagePanel("Messages"); logger = messagePanel.getMessageLogger(); ic2dObject.registerLogger(logger); ic2dObject.registerListener(this); eventListsPanel = new EventListsPanel(ic2dObject, controller); ic2dPanel = new IC2DPanel(this, ic2dObject, controller, communicationRecorder, activeObjectFilter, eventListsPanel); java.awt.Container c = getContentPane(); c.setLayout(new java.awt.BorderLayout()); //Create the split pane javax.swing.JSplitPane splitPanel = new javax.swing.JSplitPane(javax.swing.JSplitPane.VERTICAL_SPLIT, false, ic2dPanel, messagePanel); splitPanel.setDividerLocation(DEFAULT_HEIGHT-200); splitPanel.setOneTouchExpandable(true); c.add(splitPanel, java.awt.BorderLayout.CENTER); // Listeners addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); setVisible(true); eventListsFrame = createEventListFrame(eventListsPanel); processesFrame = createProcessesFrame(); fileChooserFrame = createFileChooserFrame(); logger.log("IC2D ready !"); } public void activeObjectAdded(ActiveObject activeObject) { } public void activeObjectRemoved(ActiveObject activeObject) { communicationRecorder.removeActiveObject(activeObject); } public void objectWaitingForRequest(ActiveObject object, SpyEvent spyEvent) { ic2dPanel.objectWaitingForRequest(object, spyEvent); eventListsPanel.objectWaitingForRequest(object, spyEvent); } public void objectWaitingByNecessity(ActiveObject object, SpyEvent spyEvent) { ic2dPanel.objectWaitingByNecessity(object, spyEvent); eventListsPanel.objectWaitingByNecessity(object, spyEvent); } public void requestMessageSent(ActiveObject object, SpyEvent spyEvent) { ic2dPanel.requestMessageSent(object, spyEvent); eventListsPanel.requestMessageSent(object, spyEvent); } public void replyMessageSent(ActiveObject object, SpyEvent spyEvent) { ic2dPanel.replyMessageSent(object, spyEvent); eventListsPanel.replyMessageSent(object, spyEvent); } public void requestMessageReceived(ActiveObject object, SpyEvent spyEvent) { ic2dPanel.requestMessageReceived(object, spyEvent); eventListsPanel.requestMessageReceived(object, spyEvent); } public void replyMessageReceived(ActiveObject object, SpyEvent spyEvent) { ic2dPanel.replyMessageReceived(object, spyEvent); eventListsPanel.replyMessageReceived(object, spyEvent); } public void allEventsProcessed() { ic2dPanel.allEventsProcessed(); eventListsPanel.allEventsProcessed(); } private javax.swing.JFrame createEventListFrame(javax.swing.JPanel panel) { // Create the timeLine panel final javax.swing.JFrame frame = new javax.swing.JFrame("Events lists"); frame.setLocation(new java.awt.Point(0, DEFAULT_HEIGHT)); frame.setSize(new java.awt.Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT/2)); java.awt.Container c = frame.getContentPane(); c.setLayout(new java.awt.GridLayout(1,1)); javax.swing.JScrollPane scrollingEventListsPanel = new javax.swing.JScrollPane(panel); scrollingEventListsPanel.setVerticalScrollBarPolicy(javax.swing.JScrollPane.VERTICAL_SCROLLBAR_NEVER); c.add(scrollingEventListsPanel); frame.addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent e) { frame.setVisible(! frame.isVisible()); } }); frame.setVisible(true); return frame; } private javax.swing.JFrame createProcessesFrame() { final javax.swing.JFrame frame = new ProcessControlFrame(); frame.setLocation(new java.awt.Point(DEFAULT_WIDTH, 0)); // Listeners frame.addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent e) { frame.setVisible(! frame.isVisible()); } }); return frame; } private javax.swing.JFrame createFileChooserFrame() { final javax.swing.JFrame frame = new FileChooser(externalProcess); //frame.setLocation(new java.awt.Point(DEFAULT_WIDTH, 0)); // Listeners frame.addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent e) { frame.setVisible(! frame.isVisible()); } }); return frame; } private javax.swing.JFrame createGlobusProcessFrame() { final javax.swing.JFrame frame = new GlobusProcessControlFrame(externalProcess); //frame.setLocation(new java.awt.Point(DEFAULT_WIDTH, 0)); // Listeners frame.addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent e) { frame.setVisible(! frame.isVisible()); } }); return frame; } private javax.swing.JMenuBar createMenuBar() { javax.swing.JMenuBar menuBar = new javax.swing.JMenuBar(); // monitoring menu javax.swing.JMenu monitoringMenu = new javax.swing.JMenu("Monitoring"); // Add new RMI host { javax.swing.JMenuItem b = new javax.swing.JMenuItem("Monitor a new RMI host"); b.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { DialogUtils.openNewRMIHostDialog(IC2DFrame.this, ic2dObject.getWorldObject(), logger); } }); monitoringMenu.add(b); } // Add new RMI Node { javax.swing.JMenuItem b = new javax.swing.JMenuItem("Monitor a new RMI Node"); b.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { DialogUtils.openNewNodeDialog(IC2DFrame.this, ic2dObject.getWorldObject(), logger); } }); monitoringMenu.add(b); } { javax.swing.JMenuItem b = new javax.swing.JMenuItem("Monitor all JINI Hosts"); b.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { ic2dObject.getWorldObject().addHosts(); } }); monitoringMenu.add(b); } { javax.swing.JMenuItem b = new javax.swing.JMenuItem("Monitor a new JINI Hosts"); b.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { DialogUtils.openNewJINIHostDialog(IC2DFrame.this, ic2dObject.getWorldObject(), logger); } }); monitoringMenu.add(b); } monitoringMenu.addSeparator(); // Add new GLOBUS host { javax.swing.JMenuItem b = new javax.swing.JMenuItem("Monitor new GLOBUS host"); b.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { DialogUtils.openNewGlobusHostDialog((java.awt.Component) IC2DFrame.this, ic2dObject.getWorldObject(), logger); } }); //b.setEnabled((options & IC2D.GLOBUS) != 0); monitoringMenu.add(b); } monitoringMenu.addSeparator(); // Edit the filter list { javax.swing.JMenuItem b = new javax.swing.JMenuItem("Show filtered classes"); b.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { DialogUtils.openFilteredClassesDialog(IC2DFrame.this, ic2dPanel, activeObjectFilter); } }); b.setToolTipText("Filter active objects"); monitoringMenu.add(b); } monitoringMenu.addSeparator(); // Display the legend { javax.swing.JMenuItem b = new javax.swing.JMenuItem("Legend"); b.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { doLegend(); } }); b.setToolTipText("Display the legend"); monitoringMenu.add(b); } monitoringMenu.addSeparator(); // exit { javax.swing.JMenuItem b = new javax.swing.JMenuItem("Quit"); b.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { System.exit(0); } }); monitoringMenu.add(b); } menuBar.add(monitoringMenu); // look and feel { javax.swing.JMenu lookMenu = new javax.swing.JMenu("Look & feel"); javax.swing.UIManager.LookAndFeelInfo[] infos = javax.swing.UIManager.getInstalledLookAndFeels(); for (int i = 0; i < infos.length; i++) { javax.swing.AbstractAction a = new javax.swing.AbstractAction(infos[i].getName(), null) { public void actionPerformed(java.awt.event.ActionEvent e) { try { String classname = (String)getValue("class"); //javax.swing.JFrame frame = (javax.swing.JFrame)getValue("frame"); javax.swing.UIManager.setLookAndFeel(classname); javax.swing.SwingUtilities.updateComponentTreeUI(IC2DFrame.this); javax.swing.SwingUtilities.updateComponentTreeUI(eventListsFrame); javax.swing.SwingUtilities.updateComponentTreeUI(processesFrame); } catch (Exception ex) { } } }; a.putValue("frame", this); a.putValue("class", infos[i].getClassName()); lookMenu.add(a); } menuBar.add(lookMenu); } // Window javax.swing.JMenu windowMenu = new javax.swing.JMenu("Window"); { javax.swing.JMenuItem b = new javax.swing.JMenuItem("Hide/Show EventsList windows"); b.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { if (eventListsFrame.isVisible()) { eventListsFrame.hide(); } else { eventListsFrame.show(); } } }); windowMenu.add(b); } { javax.swing.JMenuItem b = new javax.swing.JMenuItem("Hide/Show Processes windows"); b.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { if (processesFrame.isVisible()) { processesFrame.hide(); } else { processesFrame.show(); } } }); windowMenu.add(b); } menuBar.add(windowMenu); // Globus javax.swing.JMenu globusMenu = new javax.swing.JMenu("Globus"); { javax.swing.JMenuItem b = new javax.swing.JMenuItem("Start a new Node with Globus"); b.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { if (fileChooserFrame.isVisible()) { fileChooserFrame.hide(); } else { fileChooserFrame.show(); } } }); globusMenu.add(b); } { javax.swing.JMenuItem b = new javax.swing.JMenuItem("Hide/Show Globus Process Frame"); b.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { if (((FileChooser)fileChooserFrame).ready()){ ((FileChooser)fileChooserFrame).changeVisibilityGlobusProcessFrame(); } else { logger.log("Please select the deployment file with the file chooser in the window menu!"); } } }); globusMenu.add(b); } menuBar.add(globusMenu); return menuBar; } private void doLegend() { Legend legend = Legend.uniqueInstance(); legend.setVisible(! legend.isVisible()); } private class MyController implements IC2DGUIController { private boolean isLayoutAutomatic = true; public MyController() { } public boolean isLayoutAutomatic() { return isLayoutAutomatic; } public void setAutomaticLayout(boolean b) { isLayoutAutomatic = b; } public void warn(String message) { logger.warn(message); } public void log(String message) { logger.log(message); } public void log(String message, Throwable e) { logger.log(message, e); } public void log(Throwable e) { logger.log(e); } } }
package com.tagmycode.sdk; import org.junit.Test; import java.text.DateFormat; import java.text.ParseException; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import static org.junit.Assert.assertEquals; public class DateParserTest { @Test public void parseDate() throws ParseException { Date date = DateParser.parseDate("2010-11-22T01:11:25+02:00"); assertEquals(1290381085000L, date.getTime()); } @Test public void dateToJson() throws ParseException { Date date = DateParser.parseDate("2010-11-22T01:11:25+02:00"); assertEquals("2010-11-21T23:11:25Z", new DateParser(date).toISO8601()); date = DateParser.parseDate("2010-11-22T01:11:25Z"); assertEquals("2010-11-22T01:11:25Z", new DateParser(date).toISO8601()); } @Test public void toDateLocale() throws ParseException { Date date = DateParser.parseDate("2010-11-22T01:11:25+02:00"); DateParser dateParser = new DateParser(date); dateParser.setTimezone(TimeZone.getTimeZone("gmt")); assertEquals("Sunday, November 21, 2010", dateParser.toDateLocale(DateFormat.FULL, Locale.US)); } @Test public void toTimeLocale() throws ParseException { Date date = DateParser.parseDate("2010-11-22T01:11:25+02:00"); DateParser dateParser = new DateParser(date); dateParser.setTimezone(TimeZone.getTimeZone("gmt")); assertEquals("11:11:25 PM", dateParser.toTimeLocale(DateFormat.MEDIUM, Locale.US)); } @Test public void toDateTimeLocale() throws ParseException { Date date = DateParser.parseDate("2010-11-22T01:11:25+02:00"); DateParser dateParser = new DateParser(date); dateParser.setTimezone(TimeZone.getTimeZone("gmt")); assertEquals("Nov 21, 2010 11:11:25 PM", dateParser.toDateTimeLocale(DateFormat.MEDIUM, DateFormat.MEDIUM, Locale.US)); } }
package org.pentaho.di.job.entries.ftp; import static org.pentaho.di.job.entry.validator.AndValidator.putValidators; import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.andValidator; import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.fileExistsValidator; import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.notBlankValidator; import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.notNullValidator; import java.io.File; import java.net.InetAddress; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.vfs.FileObject; import org.apache.log4j.Logger; import org.pentaho.di.cluster.SlaveServer; import org.pentaho.di.core.CheckResultInterface; import org.pentaho.di.core.Const; import org.pentaho.di.core.Result; import org.pentaho.di.core.ResultFile; import org.pentaho.di.core.database.DatabaseMeta; import org.pentaho.di.core.exception.KettleDatabaseException; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleXMLException; import org.pentaho.di.core.logging.LogWriter; import org.pentaho.di.core.vfs.KettleVFS; import org.pentaho.di.core.xml.XMLHandler; import org.pentaho.di.job.Job; import org.pentaho.di.job.JobEntryType; import org.pentaho.di.job.JobMeta; import org.pentaho.di.job.entry.JobEntryBase; import org.pentaho.di.job.entry.JobEntryInterface; import org.pentaho.di.repository.Repository; import org.pentaho.di.resource.ResourceEntry; import org.pentaho.di.resource.ResourceReference; import org.pentaho.di.resource.ResourceEntry.ResourceType; import org.pentaho.di.core.util.StringUtil; import org.w3c.dom.Node; import com.enterprisedt.net.ftp.FTPClient; import com.enterprisedt.net.ftp.FTPConnectMode; import com.enterprisedt.net.ftp.FTPException; import com.enterprisedt.net.ftp.FTPTransferType; /** * This defines an FTP job entry. * * @author Matt * @since 05-11-2003 * */ public class JobEntryFTP extends JobEntryBase implements Cloneable, JobEntryInterface { private static Logger log4j = Logger.getLogger(JobEntryFTP.class); private String serverName; private String userName; private String password; private String ftpDirectory; private String targetDirectory; private String wildcard; private boolean binaryMode; private int timeout; private boolean remove; private boolean onlyGettingNewFiles; /* Don't overwrite files */ private boolean activeConnection; private String controlEncoding; /* how to convert list of filenames e.g. */ /** * Implicit encoding used before PDI v2.4.1 */ static private String LEGACY_CONTROL_ENCODING = "US-ASCII"; /** * Default encoding when making a new ftp job entry instance. */ static private String DEFAULT_CONTROL_ENCODING = "ISO-8859-1"; private boolean movefiles; private String movetodirectory; private boolean adddate; private boolean addtime; private boolean SpecifyFormat; private String date_time_format; private boolean AddDateBeforeExtension; private boolean isaddresult; private boolean createmovefolder; private String port; private String proxyHost; private String proxyPort; /* string to allow variable substitution */ private String proxyUsername; private String proxyPassword; public int ifFileExistsSkip=0; public String SifFileExistsSkip="ifFileExistsSkip"; public int ifFileExistsCreateUniq=1; public String SifFileExistsCreateUniq="ifFileExistsCreateUniq"; public int ifFileExistsFail=2; public String SifFileExistsFail="ifFileExistsFail"; public int ifFileExists; public String SifFileExists; public String SUCCESS_IF_AT_LEAST_X_FILES_DOWNLOADED="success_when_at_least"; public String SUCCESS_IF_ERRORS_LESS="success_if_errors_less"; public String SUCCESS_IF_NO_ERRORS="success_if_no_errors"; private String nr_limit; private String success_condition; long NrErrors=0; long NrfilesRetrieved=0; boolean successConditionBroken=false; int limitFiles=0; String targetFilename =null; public JobEntryFTP(String n) { super(n, ""); nr_limit="10"; port="21"; success_condition=SUCCESS_IF_NO_ERRORS; ifFileExists=ifFileExistsSkip; SifFileExists=SifFileExistsSkip; serverName=null; movefiles=false; movetodirectory=null; adddate=false; addtime=false; SpecifyFormat=false; AddDateBeforeExtension=false; isaddresult=true; createmovefolder=false; setID(-1L); setJobEntryType(JobEntryType.FTP); setControlEncoding(DEFAULT_CONTROL_ENCODING); } public JobEntryFTP() { this(""); } public JobEntryFTP(JobEntryBase jeb) { super(jeb); } public Object clone() { JobEntryFTP je = (JobEntryFTP) super.clone(); return je; } public String getXML() { StringBuffer retval = new StringBuffer(128); retval.append(super.getXML()); retval.append(" ").append(XMLHandler.addTagValue("port", port)); retval.append(" ").append(XMLHandler.addTagValue("servername", serverName)); retval.append(" ").append(XMLHandler.addTagValue("username", userName)); retval.append(" ").append(XMLHandler.addTagValue("password", password)); retval.append(" ").append(XMLHandler.addTagValue("ftpdirectory", ftpDirectory)); retval.append(" ").append(XMLHandler.addTagValue("targetdirectory", targetDirectory)); retval.append(" ").append(XMLHandler.addTagValue("wildcard", wildcard)); retval.append(" ").append(XMLHandler.addTagValue("binary", binaryMode)); retval.append(" ").append(XMLHandler.addTagValue("timeout", timeout)); retval.append(" ").append(XMLHandler.addTagValue("remove", remove)); retval.append(" ").append(XMLHandler.addTagValue("only_new", onlyGettingNewFiles)); retval.append(" ").append(XMLHandler.addTagValue("active", activeConnection)); retval.append(" ").append(XMLHandler.addTagValue("control_encoding", controlEncoding)); retval.append(" ").append(XMLHandler.addTagValue("movefiles", movefiles)); retval.append(" ").append(XMLHandler.addTagValue("movetodirectory", movetodirectory)); retval.append(" ").append(XMLHandler.addTagValue("adddate", adddate)); retval.append(" ").append(XMLHandler.addTagValue("addtime", addtime)); retval.append(" ").append(XMLHandler.addTagValue("SpecifyFormat", SpecifyFormat)); retval.append(" ").append(XMLHandler.addTagValue("date_time_format", date_time_format)); retval.append(" ").append(XMLHandler.addTagValue("AddDateBeforeExtension", AddDateBeforeExtension)); retval.append(" ").append(XMLHandler.addTagValue("isaddresult", isaddresult)); retval.append(" ").append(XMLHandler.addTagValue("createmovefolder", createmovefolder)); retval.append(" ").append(XMLHandler.addTagValue("proxy_host", proxyHost)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" ").append(XMLHandler.addTagValue("proxy_port", proxyPort)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" ").append(XMLHandler.addTagValue("proxy_username", proxyUsername)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" ").append(XMLHandler.addTagValue("proxy_password", proxyPassword)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" ").append(XMLHandler.addTagValue("ifFileExists", SifFileExists)); retval.append(" ").append(XMLHandler.addTagValue("nr_limit", nr_limit)); retval.append(" ").append(XMLHandler.addTagValue("success_condition", success_condition)); return retval.toString(); } public void loadXML(Node entrynode, List<DatabaseMeta> databases, List<SlaveServer> slaveServers, Repository rep) throws KettleXMLException { try { super.loadXML(entrynode, databases, slaveServers); port = XMLHandler.getTagValue(entrynode, "port"); serverName = XMLHandler.getTagValue(entrynode, "servername"); userName = XMLHandler.getTagValue(entrynode, "username"); password = XMLHandler.getTagValue(entrynode, "password"); ftpDirectory = XMLHandler.getTagValue(entrynode, "ftpdirectory"); targetDirectory = XMLHandler.getTagValue(entrynode, "targetdirectory"); wildcard = XMLHandler.getTagValue(entrynode, "wildcard"); binaryMode = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "binary") ); timeout = Const.toInt(XMLHandler.getTagValue(entrynode, "timeout"), 10000); remove = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "remove") ); onlyGettingNewFiles = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "only_new") ); activeConnection = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "active") ); controlEncoding = XMLHandler.getTagValue(entrynode, "control_encoding"); if ( controlEncoding == null ) { // if we couldn't retrieve an encoding, assume it's an old instance and // put in the the encoding used before v 2.4.0 controlEncoding = LEGACY_CONTROL_ENCODING; } movefiles = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "movefiles") ); movetodirectory = XMLHandler.getTagValue(entrynode, "movetodirectory"); adddate = "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "adddate")); addtime = "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "addtime")); SpecifyFormat = "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "SpecifyFormat")); date_time_format = XMLHandler.getTagValue(entrynode, "date_time_format"); AddDateBeforeExtension = "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "AddDateBeforeExtension")); String addresult = XMLHandler.getTagValue(entrynode, "isaddresult"); if(Const.isEmpty(addresult)) isaddresult = true; else isaddresult = "Y".equalsIgnoreCase(addresult); createmovefolder = "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "createmovefolder")); proxyHost = XMLHandler.getTagValue(entrynode, "proxy_host"); //$NON-NLS-1$ proxyPort = XMLHandler.getTagValue(entrynode, "proxy_port"); //$NON-NLS-1$ proxyUsername = XMLHandler.getTagValue(entrynode, "proxy_username"); //$NON-NLS-1$ proxyPassword = XMLHandler.getTagValue(entrynode, "proxy_password"); //$NON-NLS-1$ SifFileExists=XMLHandler.getTagValue(entrynode, "ifFileExists"); if(Const.isEmpty(SifFileExists)) { ifFileExists=ifFileExistsSkip; }else { if(SifFileExists.equals(SifFileExistsCreateUniq)) ifFileExists=ifFileExistsCreateUniq; else if(SifFileExists.equals(SifFileExistsFail)) ifFileExists=ifFileExistsFail; else ifFileExists=ifFileExistsSkip; } nr_limit = XMLHandler.getTagValue(entrynode, "nr_limit"); success_condition = XMLHandler.getTagValue(entrynode, "success_condition"); } catch(KettleXMLException xe) { throw new KettleXMLException("Unable to load job entry of type 'ftp' from XML node", xe); } } public void loadRep(Repository rep, long id_jobentry, List<DatabaseMeta> databases, List<SlaveServer> slaveServers) throws KettleException { try { super.loadRep(rep, id_jobentry, databases, slaveServers); port = rep.getJobEntryAttributeString(id_jobentry, "port"); serverName = rep.getJobEntryAttributeString(id_jobentry, "servername"); userName = rep.getJobEntryAttributeString(id_jobentry, "username"); password = rep.getJobEntryAttributeString(id_jobentry, "password"); ftpDirectory = rep.getJobEntryAttributeString(id_jobentry, "ftpdirectory"); targetDirectory = rep.getJobEntryAttributeString(id_jobentry, "targetdirectory"); wildcard = rep.getJobEntryAttributeString(id_jobentry, "wildcard"); binaryMode = rep.getJobEntryAttributeBoolean(id_jobentry, "binary"); timeout = (int)rep.getJobEntryAttributeInteger(id_jobentry, "timeout"); remove = rep.getJobEntryAttributeBoolean(id_jobentry, "remove"); onlyGettingNewFiles = rep.getJobEntryAttributeBoolean(id_jobentry, "only_new"); activeConnection = rep.getJobEntryAttributeBoolean(id_jobentry, "active"); controlEncoding = rep.getJobEntryAttributeString(id_jobentry, "control_encoding"); if ( controlEncoding == null ) { // if we couldn't retrieve an encoding, assume it's an old instance and // put in the the encoding used before v 2.4.0 controlEncoding = LEGACY_CONTROL_ENCODING; } movefiles = rep.getJobEntryAttributeBoolean(id_jobentry, "movefiles"); movetodirectory = rep.getJobEntryAttributeString(id_jobentry, "movetodirectory"); adddate=rep.getJobEntryAttributeBoolean(id_jobentry, "adddate"); addtime=rep.getJobEntryAttributeBoolean(id_jobentry, "adddate"); SpecifyFormat=rep.getJobEntryAttributeBoolean(id_jobentry, "SpecifyFormat"); date_time_format = rep.getJobEntryAttributeString(id_jobentry, "date_time_format"); AddDateBeforeExtension=rep.getJobEntryAttributeBoolean(id_jobentry, "AddDateBeforeExtension"); String addToResult=rep.getStepAttributeString (id_jobentry, "add_to_result_filenames"); if(Const.isEmpty(addToResult)) isaddresult = true; else isaddresult = rep.getStepAttributeBoolean(id_jobentry, "add_to_result_filenames"); createmovefolder=rep.getJobEntryAttributeBoolean(id_jobentry, "createmovefolder"); proxyHost = rep.getJobEntryAttributeString(id_jobentry, "proxy_host"); //$NON-NLS-1$ proxyPort = rep.getJobEntryAttributeString(id_jobentry, "proxy_port"); //$NON-NLS-1$ proxyUsername = rep.getJobEntryAttributeString(id_jobentry, "proxy_username"); //$NON-NLS-1$ proxyPassword = rep.getJobEntryAttributeString(id_jobentry, "proxy_password"); //$NON-NLS-1$ SifFileExists = rep.getJobEntryAttributeString(id_jobentry, "ifFileExists"); if(Const.isEmpty(SifFileExists)) { ifFileExists=ifFileExistsSkip; }else { if(SifFileExists.equals(SifFileExistsCreateUniq)) ifFileExists=ifFileExistsCreateUniq; else if(SifFileExists.equals(SifFileExistsFail)) ifFileExists=ifFileExistsFail; else ifFileExists=ifFileExistsSkip; } nr_limit = rep.getJobEntryAttributeString(id_jobentry, "nr_limit"); success_condition = rep.getJobEntryAttributeString(id_jobentry, "success_condition"); } catch(KettleException dbe) { throw new KettleException("Unable to load job entry of type 'ftp' from the repository for id_jobentry="+id_jobentry, dbe); } } public void saveRep(Repository rep, long id_job) throws KettleException { try { super.saveRep(rep, id_job); rep.saveJobEntryAttribute(id_job, getID(), "port", port); rep.saveJobEntryAttribute(id_job, getID(), "servername", serverName); rep.saveJobEntryAttribute(id_job, getID(), "username", userName); rep.saveJobEntryAttribute(id_job, getID(), "password", password); rep.saveJobEntryAttribute(id_job, getID(), "ftpdirectory", ftpDirectory); rep.saveJobEntryAttribute(id_job, getID(), "targetdirectory", targetDirectory); rep.saveJobEntryAttribute(id_job, getID(), "wildcard", wildcard); rep.saveJobEntryAttribute(id_job, getID(), "binary", binaryMode); rep.saveJobEntryAttribute(id_job, getID(), "timeout", timeout); rep.saveJobEntryAttribute(id_job, getID(), "remove", remove); rep.saveJobEntryAttribute(id_job, getID(), "only_new", onlyGettingNewFiles); rep.saveJobEntryAttribute(id_job, getID(), "active", activeConnection); rep.saveJobEntryAttribute(id_job, getID(), "control_encoding",controlEncoding); rep.saveJobEntryAttribute(id_job, getID(), "movefiles", movefiles); rep.saveJobEntryAttribute(id_job, getID(), "movetodirectory", movetodirectory); rep.saveJobEntryAttribute(id_job, getID(), "addtime", addtime); rep.saveJobEntryAttribute(id_job, getID(), "adddate", adddate); rep.saveJobEntryAttribute(id_job, getID(), "SpecifyFormat", SpecifyFormat); rep.saveJobEntryAttribute(id_job, getID(), "date_time_format", date_time_format); rep.saveJobEntryAttribute(id_job, getID(), "AddDateBeforeExtension", AddDateBeforeExtension); rep.saveJobEntryAttribute(id_job, getID(), "isaddresult", isaddresult); rep.saveJobEntryAttribute(id_job, getID(), "createmovefolder", createmovefolder); rep.saveJobEntryAttribute(id_job, getID(), "proxy_host", proxyHost); //$NON-NLS-1$ rep.saveJobEntryAttribute(id_job, getID(), "proxy_port", proxyPort); //$NON-NLS-1$ rep.saveJobEntryAttribute(id_job, getID(), "proxy_username", proxyUsername); //$NON-NLS-1$ rep.saveJobEntryAttribute(id_job, getID(), "proxy_password", proxyPassword); //$NON-NLS-1$ rep.saveJobEntryAttribute(id_job, getID(), "ifFileExists", SifFileExists); rep.saveJobEntryAttribute(id_job, getID(), "nr_limit", nr_limit); rep.saveJobEntryAttribute(id_job, getID(), "success_condition", success_condition); } catch(KettleDatabaseException dbe) { throw new KettleException("Unable to save job entry of type 'ftp' to the repository for id_job="+id_job, dbe); } } public void setLimit(String nr_limitin) { this.nr_limit=nr_limitin; } public String getLimit() { return nr_limit; } public void setSuccessCondition(String success_condition) { this.success_condition=success_condition; } public String getSuccessCondition() { return success_condition; } public void setCreateMoveFolder(boolean createmovefolderin) { this.createmovefolder=createmovefolderin; } public boolean isCreateMoveFolder() { return createmovefolder; } public void setAddDateBeforeExtension(boolean AddDateBeforeExtension) { this.AddDateBeforeExtension=AddDateBeforeExtension; } public boolean isAddDateBeforeExtension() { return AddDateBeforeExtension; } public void setAddToResult(boolean isaddresultin) { this.isaddresult=isaddresultin; } public boolean isAddToResult() { return isaddresult; } public void setDateInFilename(boolean adddate) { this.adddate= adddate; } public boolean isDateInFilename() { return adddate; } public void setTimeInFilename(boolean addtime) { this.addtime= addtime; } public boolean isTimeInFilename() { return addtime; } public boolean isSpecifyFormat() { return SpecifyFormat; } public void setSpecifyFormat(boolean SpecifyFormat) { this.SpecifyFormat=SpecifyFormat; } public String getDateTimeFormat() { return date_time_format; } public void setDateTimeFormat(String date_time_format) { this.date_time_format=date_time_format; } /** * @return Returns the movefiles. */ public boolean isMoveFiles() { return movefiles; } /** * @param movefilesin The movefiles to set. */ public void setMoveFiles(boolean movefilesin) { this.movefiles=movefilesin; } /** * @return Returns the movetodirectory. */ public String getMoveToDirectory() { return movetodirectory; } /** * @param movetoin The movetodirectory to set. */ public void setMoveToDirectory(String movetoin) { this.movetodirectory=movetoin; } /** * @return Returns the binaryMode. */ public boolean isBinaryMode() { return binaryMode; } /** * @param binaryMode The binaryMode to set. */ public void setBinaryMode(boolean binaryMode) { this.binaryMode = binaryMode; } /** * @return Returns the directory. */ public String getFtpDirectory() { return ftpDirectory; } /** * @param directory The directory to set. */ public void setFtpDirectory(String directory) { this.ftpDirectory = directory; } /** * @return Returns the password. */ public String getPassword() { return password; } /** * @param password The password to set. */ public void setPassword(String password) { this.password = password; } /** * @return Returns the serverName. */ public String getServerName() { return serverName; } /** * @param serverName The serverName to set. */ public void setServerName(String serverName) { this.serverName = serverName; } /** * @return Returns the port. */ public String getPort() { return port; } /** * @param port The port to set. */ public void setPort(String port) { this.port = port; } /** * @return Returns the userName. */ public String getUserName() { return userName; } /** * @param userName The userName to set. */ public void setUserName(String userName) { this.userName = userName; } /** * @return Returns the wildcard. */ public String getWildcard() { return wildcard; } /** * @param wildcard The wildcard to set. */ public void setWildcard(String wildcard) { this.wildcard = wildcard; } /** * @return Returns the targetDirectory. */ public String getTargetDirectory() { return targetDirectory; } /** * @param targetDirectory The targetDirectory to set. */ public void setTargetDirectory(String targetDirectory) { this.targetDirectory = targetDirectory; } /** * @param timeout The timeout to set. */ public void setTimeout(int timeout) { this.timeout = timeout; } /** * @return Returns the timeout. */ public int getTimeout() { return timeout; } /** * @param remove The remove to set. */ public void setRemove(boolean remove) { this.remove = remove; } /** * @return Returns the remove. */ public boolean getRemove() { return remove; } /** * @return Returns the onlyGettingNewFiles. */ public boolean isOnlyGettingNewFiles() { return onlyGettingNewFiles; } /** * @param onlyGettingNewFiles The onlyGettingNewFiles to set. */ public void setOnlyGettingNewFiles(boolean onlyGettingNewFilesin) { this.onlyGettingNewFiles = onlyGettingNewFilesin; } /** * Get the control encoding to be used for ftp'ing * * @return the used encoding */ public String getControlEncoding() { return controlEncoding; } /** * Set the encoding to be used for ftp'ing. This determines how * names are translated in dir e.g. It does impact the contents * of the files being ftp'ed. * * @param encoding The encoding to be used. */ public void setControlEncoding(String encoding) { this.controlEncoding = encoding; } /** * @return Returns the hostname of the ftp-proxy. */ public String getProxyHost() { return proxyHost; } /** * @param proxyHost The hostname of the proxy. */ public void setProxyHost(String proxyHost) { this.proxyHost = proxyHost; } /** * @return Returns the password which is used to authenticate at the proxy. */ public String getProxyPassword() { return proxyPassword; } /** * @param proxyPassword The password which is used to authenticate at the proxy. */ public void setProxyPassword(String proxyPassword) { this.proxyPassword = proxyPassword; } /** * @return Returns the port of the ftp-proxy. */ public String getProxyPort() { return proxyPort; } /** * @param proxyPort The port of the ftp-proxy. */ public void setProxyPort(String proxyPort) { this.proxyPort = proxyPort; } /** * @return Returns the username which is used to authenticate at the proxy. */ public String getProxyUsername() { return proxyUsername; } /** * @param proxyUsername The username which is used to authenticate at the proxy. */ public void setProxyUsername(String proxyUsername) { this.proxyUsername = proxyUsername; } public Result execute(Result previousResult, int nr, Repository rep, Job parentJob) { LogWriter log = LogWriter.getInstance(); log4j.info(Messages.getString("JobEntryFTP.Started", serverName)); //$NON-NLS-1$ Result result = previousResult; result.setNrErrors(1); result.setResult( false ); NrErrors = 0; NrfilesRetrieved=0; successConditionBroken=false; limitFiles=Const.toInt(environmentSubstitute(getLimit()),10); // Here let's put some controls before stating the job if(movefiles) { if(Const.isEmpty(movetodirectory)) { log.logError(toString(), Messages.getString("JobEntryFTP.MoveToFolderEmpty")); result.setNrErrors(1); return result; } } if(log.isDetailed()) log.logDetailed(toString(), Messages.getString("JobEntryFTP.Start")); //$NON-NLS-1$ FTPClient ftpclient=null; String realMoveToFolder=null; try { // Create ftp client to host:port ... ftpclient = new FTPClient(); String realServername = environmentSubstitute(serverName); String realServerPort = environmentSubstitute(port); ftpclient.setRemoteAddr(InetAddress.getByName(realServername)); if(Const.isEmpty(realServerPort)) { ftpclient.setRemotePort(Const.toInt(realServerPort, 21)); } if (!Const.isEmpty(proxyHost)) { String realProxy_host = environmentSubstitute(proxyHost); ftpclient.setRemoteAddr(InetAddress.getByName(realProxy_host)); if ( log.isDetailed() ) log.logDetailed(toString(), Messages.getString("JobEntryFTP.OpenedProxyConnectionOn",realProxy_host)); // FIXME: Proper default port for proxy int port = Const.toInt(environmentSubstitute(proxyPort), 21); if (port != 0) { ftpclient.setRemotePort(port); } } else { ftpclient.setRemoteAddr(InetAddress.getByName(realServername)); if ( log.isDetailed() ) log.logDetailed(toString(), Messages.getString("JobEntryFTP.OpenedConnectionTo",realServername)); } // set activeConnection connectmode ... if (activeConnection) { ftpclient.setConnectMode(FTPConnectMode.ACTIVE); if(log.isDetailed()) log.logDetailed(toString(), Messages.getString("JobEntryFTP.SetActive")); //$NON-NLS-1$ } else { ftpclient.setConnectMode(FTPConnectMode.PASV); if(log.isDetailed()) log.logDetailed(toString(), Messages.getString("JobEntryFTP.SetPassive")); //$NON-NLS-1$ } // Set the timeout ftpclient.setTimeout(timeout); if(log.isDetailed()) log.logDetailed(toString(), Messages.getString("JobEntryFTP.SetTimeout", String.valueOf(timeout))); //$NON-NLS-1$ ftpclient.setControlEncoding(controlEncoding); if(log.isDetailed()) log.logDetailed(toString(), Messages.getString("JobEntryFTP.SetEncoding", controlEncoding)); //$NON-NLS-1$ // login to ftp host ... ftpclient.connect(); String realUsername = environmentSubstitute(userName) + (!Const.isEmpty(proxyHost) ? "@" + realServername : "") + (!Const.isEmpty(proxyUsername) ? " " + environmentSubstitute(proxyUsername) : ""); String realPassword = environmentSubstitute(password) + (!Const.isEmpty(proxyPassword) ? " " + environmentSubstitute(proxyPassword) : "" ); ftpclient.login(realUsername, realPassword); // Remove password from logging, you don't know where it ends up. if(log.isDetailed()) log.logDetailed(toString(), Messages.getString("JobEntryFTP.LoggedIn", realUsername)); //$NON-NLS-1$ // move to spool dir ... if (!Const.isEmpty(ftpDirectory)) { String realFtpDirectory = environmentSubstitute(ftpDirectory); ftpclient.chdir(realFtpDirectory); if(log.isDetailed()) log.logDetailed(toString(), Messages.getString("JobEntryFTP.ChangedDir", realFtpDirectory)); //$NON-NLS-1$ } //Create move to folder if necessary if(movefiles && !Const.isEmpty(movetodirectory)) { realMoveToFolder=environmentSubstitute(movetodirectory); if(!ftpclient.exists(realMoveToFolder)) { if(createmovefolder) { ftpclient.mkdir(realMoveToFolder); if(log.isDetailed()) log.logDetailed(toString(), Messages.getString("JobEntryFTP.MoveToFolderCreated",realMoveToFolder)); }else { log.logError(toString(),Messages.getString("JobEntryFTP.MoveToFolderNotExist")); result.setNrErrors(1); return result; } } } // Get all the files in the current directory... String[] filelist = ftpclient.dir(); if(log.isDetailed()) log.logDetailed(toString(), Messages.getString("JobEntryFTP.FoundNFiles", String.valueOf(filelist.length))); //$NON-NLS-1$ // set transfertype ... if (binaryMode) { ftpclient.setType(FTPTransferType.BINARY); if(log.isDetailed()) log.logDetailed(toString(), Messages.getString("JobEntryFTP.SetBinary")); //$NON-NLS-1$ } else { ftpclient.setType(FTPTransferType.ASCII); if(log.isDetailed()) log.logDetailed(toString(), Messages.getString("JobEntryFTP.SetAscii")); //$NON-NLS-1$ } // Some FTP servers return a message saying no files found as a string in the filenlist // e.g. Solaris 8 // CHECK THIS !!! if (filelist.length == 1) { String translatedWildcard = environmentSubstitute(wildcard); if(!Const.isEmpty(translatedWildcard)){ if (filelist[0].startsWith(translatedWildcard)) { throw new FTPException(filelist[0]); } } } Pattern pattern = null; if (!Const.isEmpty(wildcard)) { String realWildcard = environmentSubstitute(wildcard); pattern = Pattern.compile(realWildcard); } if(!getSuccessCondition().equals(SUCCESS_IF_NO_ERRORS)) limitFiles=Const.toInt(environmentSubstitute(getLimit()),10); // Get the files in the list... for (int i=0;i<filelist.length && !parentJob.isStopped();i++) { if(successConditionBroken) { log.logError(toString(), Messages.getString("JobEntryFTP.Error.SuccessConditionbroken",""+NrErrors)); throw new Exception(Messages.getString("JobEntryFTP.SuccesConditionBroken",""+NrErrors)); } boolean getIt = true; if(log.isDebug()) log.logDebug(toString(), Messages.getString("JobEntryFTP.AnalysingFile",filelist[i])); try { // First see if the file matches the regular expression! if (pattern!=null) { Matcher matcher = pattern.matcher(filelist[i]); getIt = matcher.matches(); } if (getIt) { targetFilename = getTargetFilename(filelist[i]); if ((!onlyGettingNewFiles) || (onlyGettingNewFiles && needsDownload(targetFilename))) { if(log.isDetailed()) log.logDetailed(toString(), Messages.getString("JobEntryFTP.GettingFile", filelist[i], environmentSubstitute(targetDirectory))); //$NON-NLS-1$ ftpclient.get(targetFilename, filelist[i]); // Update retrieved files updateRetrievedFiles(); if(log.isDetailed()) log.logDetailed(toString(), Messages.getString("JobEntryFTP.GotFile", filelist[i])); //$NON-NLS-1$ if(isaddresult) { FileObject targetFile = null; try { targetFile = KettleVFS.getFileObject(targetFilename); // Add to the result files... ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL, targetFile, parentJob.getJobname(), toString()); resultFile.setComment(Messages.getString("JobEntryFTP.Downloaded", serverName)); //$NON-NLS-1$ result.getResultFiles().put(resultFile.getFile().toString(), resultFile); if(log.isDetailed()) log.logDetailed(toString(), Messages.getString("JobEntryFTP.FileAddedToResult", filelist[i])); //$NON-NLS-1$ } finally { try{ targetFile.close(); targetFile=null; }catch(Exception e){} } } } // Delete the file if this is needed! if (remove) { ftpclient.delete(filelist[i]); if(log.isDetailed()) if(log.isDetailed()) log.logDetailed(toString(), Messages.getString("JobEntryFTP.DeletedFile", filelist[i])); //$NON-NLS-1$ }else { if(movefiles) { // Try to move file to destination folder ... ftpclient.rename(filelist[i], realMoveToFolder+'/'+filelist[i]); if(log.isDetailed()) log.logDetailed(toString(), Messages.getString("JobEntryFTP.MovedFile",filelist[i],realMoveToFolder)); } } } }catch (Exception e) { // Update errors number updateErrors(); log.logError(toString(),Messages.getString("JobFTP.UnexpectedError",e.getMessage())); if(successConditionBroken) throw new Exception(Messages.getString("JobEntryFTP.SuccesConditionBroken")); } } // end for } catch(Exception e) { updateErrors(); log.logError(toString(), Messages.getString("JobEntryFTP.ErrorGetting", e.getMessage())); //$NON-NLS-1$ log.logError(toString(), Const.getStackTracker(e)); } finally { if (ftpclient!=null && ftpclient.connected()) { try { ftpclient.quit(); } catch(Exception e) { log.logError(toString(), Messages.getString("JobEntryFTP.ErrorQuitting", e.getMessage())); //$NON-NLS-1$ } } } result.setNrErrors(NrErrors); result.setNrFilesRetrieved(NrfilesRetrieved); if(getSuccessStatus()) result.setResult(true); return result; } private boolean getSuccessStatus() { boolean retval=false; if ((NrErrors==0 && getSuccessCondition().equals(SUCCESS_IF_NO_ERRORS)) || (NrfilesRetrieved>=limitFiles && getSuccessCondition().equals(SUCCESS_IF_AT_LEAST_X_FILES_DOWNLOADED)) || (NrErrors<=limitFiles && getSuccessCondition().equals(SUCCESS_IF_ERRORS_LESS))) { retval=true; } return retval; } private void updateErrors() { NrErrors++; if(checkIfSuccessConditionBroken()) { // Success condition was broken successConditionBroken=true; } } private boolean checkIfSuccessConditionBroken() { boolean retval=false; if ((NrErrors>0 && getSuccessCondition().equals(SUCCESS_IF_NO_ERRORS)) || (NrErrors>=limitFiles && getSuccessCondition().equals(SUCCESS_IF_ERRORS_LESS))) { retval=true; } return retval; } private void updateRetrievedFiles() { NrfilesRetrieved++; } /** * @param string the filename from the FTP server * * @return the calculated target filename */ protected String getTargetFilename(String filename) { String retval=""; // Replace possible environment variables... if(filename!=null) retval=filename; int lenstring=retval.length(); int lastindexOfDot=retval.lastIndexOf('.'); if(lastindexOfDot==-1) lastindexOfDot=lenstring; if(isAddDateBeforeExtension()) retval=retval.substring(0, lastindexOfDot); SimpleDateFormat daf = new SimpleDateFormat(); Date now = new Date(); if(SpecifyFormat && !Const.isEmpty(date_time_format)) { daf.applyPattern(date_time_format); String dt = daf.format(now); retval+=dt; }else { if (adddate) { daf.applyPattern("yyyyMMdd"); String d = daf.format(now); retval+="_"+d; } if (addtime) { daf.applyPattern("HHmmssSSS"); String t = daf.format(now); retval+="_"+t; } } if(isAddDateBeforeExtension()) retval+=retval.substring(lastindexOfDot, lenstring); // Add foldername to filename retval= environmentSubstitute(targetDirectory)+Const.FILE_SEPARATOR+retval; return retval; } public boolean evaluates() { return true; } /** * See if the filename on the FTP server needs downloading. * The default is to check the presence of the file in the target directory. * If you need other functionality, extend this class and build it into a plugin. * * @param filename The local filename to check * @param remoteFileSize The size of the remote file * @return true if the file needs downloading */ protected boolean needsDownload(String filename) { boolean retval=false; File file = new File(filename); //return !file.exists(); if(!file.exists()) { // Local file not exists! return true; }else { // Local file exists! if(ifFileExists==ifFileExistsCreateUniq) { // Create file with unique name int lenstring=targetFilename.length(); int lastindexOfDot=targetFilename.lastIndexOf('.'); if(lastindexOfDot==-1) lastindexOfDot=lenstring; targetFilename=targetFilename.substring(0, lastindexOfDot) + StringUtil.getFormattedDateTimeNow(true) + targetFilename.substring(lastindexOfDot, lenstring); return true; } else if(ifFileExists==ifFileExistsFail) { updateErrors(); } } return retval; } /** * @return the activeConnection */ public boolean isActiveConnection() { return activeConnection; } /** * @param activeConnection the activeConnection to set */ public void setActiveConnection(boolean passive) { this.activeConnection = passive; } public void check(List<CheckResultInterface> remarks, JobMeta jobMeta) { andValidator().validate(this, "serverName", remarks, putValidators(notBlankValidator())); //$NON-NLS-1$ andValidator() .validate(this, "targetDirectory", remarks, putValidators(notBlankValidator(), fileExistsValidator())); //$NON-NLS-1$ andValidator().validate(this, "userName", remarks, putValidators(notBlankValidator())); //$NON-NLS-1$ andValidator().validate(this, "password", remarks, putValidators(notNullValidator())); //$NON-NLS-1$ } public List<ResourceReference> getResourceDependencies(JobMeta jobMeta) { List<ResourceReference> references = super.getResourceDependencies(jobMeta); if (!Const.isEmpty(serverName)) { String realServername = jobMeta.environmentSubstitute(serverName); ResourceReference reference = new ResourceReference(this); reference.getEntries().add(new ResourceEntry(realServername, ResourceType.SERVER)); references.add(reference); } return references; } }
package dk.itu.kelvin.util; // General utilities import dk.itu.kelvin.model.Node; import java.util.Iterator; // JUnit annotations import org.junit.Before; import org.junit.Test; // JUnit assertions import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertEquals; /** * Test of the ArrayList class. */ public final class ArrayListTest { /** * Instance variable of ArrayList. */ private ArrayList a1; /** * Instance variable of Nodes. */ private Node n1; /** * Instance variable of Nodes. */ private Node n2; /** * Instance variable of Nodes. */ private Node n3; /** * Initialize an array list with the default initial capacity and 3 nodes. */ @Before public void before() { this.a1 = new ArrayList(); this.n1 = new Node(10, 10, 10); this.n2 = new Node(10, 12, 12); this.n3 = new Node(13, 12, 12); } /** * Test boolean add element to array list. */ @Test public void testAddToArray() { // add element to index 0 assertTrue(this.a1.add(10)); // add null to array assertFalse(this.a1.add(null)); // the size of the array equals 1. assertEquals(1, this.a1.size()); } /** * Test remove node from index 0 * and return the removed element * and update index position. */ @Test public void testRemoveIndexFromArray() { // add element to index 0. this.a1.add(this.n1); // the size of the array equals 1. assertEquals(1, this.a1.size()); // removes element at index 0. assertEquals(this.n1, this.a1.remove(0)); // the size of the array equals 0. assertEquals(0, this.a1.size()); // removes index that does not exist. assertEquals(null, this.a1.remove(-1)); assertEquals(null, this.a1.remove(20)); // add 3 values this.a1.add(this.n1); this.a1.add(this.n2); this.a1.add(this.n3); // gets access to element at index 0. assertEquals(this.n1, this.a1.get(0)); // remove index 0. this.a1.remove(0); // gets to the new element at index 0. assertEquals(this.n2, this.a1.get(0)); } /** * Test remove a specific node. */ @Test public void testRemoveElementFromArray() { // add element to index 0. this.a1.add(this.n1); // remove element n1 from array. assertTrue(this.a1.remove(this.n1)); // remove non-existing element from array. assertFalse(this.a1.remove(this.n2)); // does the array contain a non-existing element. assertFalse(this.a1.contains(this.n1)); assertFalse(this.a1.contains(this.n2)); // size of array equals 0. assertEquals(0, this.a1.size()); // add element to index 0. this.a1.add(this.n2); // get access to element using index 0. assertEquals(this.n2, this.a1.get(0)); } /** * Test get element by index. */ @Test public void testGetElementFromIndex() { // add element to index 0. this.a1.add(this.n1); // get access to element at index 0. assertEquals(this.n1, this.a1.get(0)); // get access to element by a non-existing index. assertEquals(null, this.a1.get(-1)); assertEquals(null, this.a1.get(100000)); } /** * Tests if array list contains a specific node. */ @Test public void testArrayContainsElement() { // add element to index 0. this.a1.add(this.n1); // does array contain element n1. assertTrue(this.a1.contains(this.n1)); // does array contain non-existing element. assertFalse(this.a1.contains(this.n2)); // does array contain null. assertFalse(this.a1.contains(null)); } /** * Tests if the iterator return an iterator over the elements of the list. */ @Test public void testIterator() { // add element to index 0 and 1. this.a1.add(this.n1); this.a1.add(this.n2); // creates an iterator Iterator<Node> i = this.a1.iterator(); int count = 0; while (i.hasNext()) { Node n = i.next(); // while iteratoring over array it must come by n1 and n2. assertTrue(n.equals(this.n1) || n.equals(this.n2)); // count the number of elements count++; } // does local variable count eqauls the size of the array. assertEquals(count, this.a1.size()); } }
package org.pentaho.di.job.entries.job; import static org.pentaho.di.job.entry.validator.AndValidator.putValidators; import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.andValidator; import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.notBlankValidator; import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.notNullValidator; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.Map; import org.pentaho.di.cluster.SlaveServer; import org.pentaho.di.core.CheckResultInterface; import org.pentaho.di.core.Const; import org.pentaho.di.core.Result; import org.pentaho.di.core.ResultFile; import org.pentaho.di.core.RowMetaAndData; import org.pentaho.di.core.SQLStatement; import org.pentaho.di.core.database.DatabaseMeta; import org.pentaho.di.core.exception.KettleDatabaseException; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleXMLException; import org.pentaho.di.core.logging.Log4jFileAppender; import org.pentaho.di.core.logging.LogWriter; import org.pentaho.di.core.variables.VariableSpace; import org.pentaho.di.core.xml.XMLHandler; import org.pentaho.di.job.Job; import org.pentaho.di.job.JobEntryType; import org.pentaho.di.job.JobExecutionConfiguration; import org.pentaho.di.job.JobMeta; import org.pentaho.di.job.entry.JobEntryBase; import org.pentaho.di.job.entry.JobEntryInterface; import org.pentaho.di.repository.Repository; import org.pentaho.di.repository.RepositoryDirectory; import org.pentaho.di.resource.ResourceDefinition; import org.pentaho.di.resource.ResourceEntry; import org.pentaho.di.resource.ResourceNamingInterface; import org.pentaho.di.resource.ResourceReference; import org.pentaho.di.resource.ResourceEntry.ResourceType; import org.pentaho.di.trans.StepLoader; import org.pentaho.di.www.SlaveServerJobStatus; import org.w3c.dom.Node; /** * Recursive definition of a Job. This step means that an entire Job has to be executed. * It can be the same Job, but just make sure that you don't get an endless loop. * Provide an escape routine using JobEval. * * @author Matt * @since 01-10-2003, Rewritten on 18-06-2004 * */ public class JobEntryJob extends JobEntryBase implements Cloneable, JobEntryInterface { private static final LogWriter log = LogWriter.getInstance(); private String jobname; private String filename; private RepositoryDirectory directory; public String arguments[]; public boolean argFromPrevious; public boolean execPerRow; public boolean setLogfile; public String logfile, logext; public boolean addDate, addTime; public int loglevel; public boolean parallel; private String directoryPath; private SlaveServer remoteSlaveServer; public JobEntryJob(String name) { super(name, ""); setJobEntryType(JobEntryType.JOB); } public JobEntryJob() { this(""); clear(); } public Object clone() { JobEntryJob je = (JobEntryJob) super.clone(); return je; } public JobEntryJob(JobEntryBase jeb) { super(jeb); } public void setFileName(String n) { filename=n; } /** * @deprecated use getFilename() instead. * @return the filename */ public String getFileName() { return filename; } public String getFilename() { return filename; } public String getRealFilename() { return environmentSubstitute(getFilename()); } public void setJobName(String jobname) { this.jobname=jobname; } public String getJobName() { return jobname; } public RepositoryDirectory getDirectory() { return directory; } public void setDirectory(RepositoryDirectory directory) { this.directory = directory; } public String getLogFilename() { String retval=""; if (setLogfile) { retval+=logfile; Calendar cal = Calendar.getInstance(); if (addDate) { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); retval+="_"+sdf.format(cal.getTime()); } if (addTime) { SimpleDateFormat sdf = new SimpleDateFormat("HHmmss"); retval+="_"+sdf.format(cal.getTime()); } if (logext!=null && logext.length()>0) { retval+="."+logext; } } return retval; } public String getXML() { StringBuffer retval = new StringBuffer(200); retval.append(super.getXML()); retval.append(" ").append(XMLHandler.addTagValue("filename", filename)); retval.append(" ").append(XMLHandler.addTagValue("jobname", jobname)); if (directory!=null) { retval.append(" ").append(XMLHandler.addTagValue("directory", directory.getPath())); } else if (directoryPath!=null) { retval.append(" ").append(XMLHandler.addTagValue("directory", directoryPath)); // don't loose this info (backup/recovery) } retval.append(" ").append(XMLHandler.addTagValue("arg_from_previous", argFromPrevious)); retval.append(" ").append(XMLHandler.addTagValue("exec_per_row", execPerRow)); retval.append(" ").append(XMLHandler.addTagValue("set_logfile", setLogfile)); retval.append(" ").append(XMLHandler.addTagValue("logfile", logfile)); retval.append(" ").append(XMLHandler.addTagValue("logext", logext)); retval.append(" ").append(XMLHandler.addTagValue("add_date", addDate)); retval.append(" ").append(XMLHandler.addTagValue("add_time", addTime)); retval.append(" ").append(XMLHandler.addTagValue("loglevel", LogWriter.getLogLevelDesc(loglevel))); retval.append(" ").append(XMLHandler.addTagValue("slave_server_name", remoteSlaveServer!=null ? remoteSlaveServer.getName() : null)); if (arguments!=null) for (int i=0;i<arguments.length;i++) { retval.append(" ").append(XMLHandler.addTagValue("argument"+i, arguments[i])); } return retval.toString(); } public void loadXML(Node entrynode, List<DatabaseMeta> databases, List<SlaveServer> slaveServers, Repository rep) throws KettleXMLException { try { super.loadXML(entrynode, databases, slaveServers); setFileName( XMLHandler.getTagValue(entrynode, "filename") ); setJobName( XMLHandler.getTagValue(entrynode, "jobname") ); argFromPrevious = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "arg_from_previous") ); execPerRow = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "exec_per_row") ); setLogfile = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "set_logfile") ); addDate = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "add_date") ); addTime = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "add_time") ); logfile = XMLHandler.getTagValue(entrynode, "logfile"); logext = XMLHandler.getTagValue(entrynode, "logext"); loglevel = LogWriter.getLogLevel( XMLHandler.getTagValue(entrynode, "loglevel")); String remoteSlaveServerName = XMLHandler.getTagValue(entrynode, "slave_server_name"); remoteSlaveServer = SlaveServer.findSlaveServer(slaveServers, remoteSlaveServerName); directoryPath = XMLHandler.getTagValue(entrynode, "directory"); if (rep!=null) // import from XML into a repository for example... (or copy/paste) { directory = rep.getDirectoryTree().findDirectory(directoryPath); } // How many arguments? int argnr = 0; while ( XMLHandler.getTagValue(entrynode, "argument"+argnr)!=null) argnr++; arguments = new String[argnr]; // Read them all... for (int a=0;a<argnr;a++) arguments[a]=XMLHandler.getTagValue(entrynode, "argument"+a); } catch(KettleXMLException xe) { throw new KettleXMLException("Unable to load 'job' job entry from XML node", xe); } } /* * Load the jobentry from repository */ public void loadRep(Repository rep, long id_jobentry, List<DatabaseMeta> databases, List<SlaveServer> slaveServers) throws KettleException { try { super.loadRep(rep, id_jobentry, databases, slaveServers); jobname = rep.getJobEntryAttributeString(id_jobentry, "name"); String dirPath = rep.getJobEntryAttributeString(id_jobentry, "dir_path"); directory = rep.getDirectoryTree().findDirectory(dirPath); filename = rep.getJobEntryAttributeString(id_jobentry, "file_name"); argFromPrevious = rep.getJobEntryAttributeBoolean(id_jobentry, "arg_from_previous"); execPerRow = rep.getJobEntryAttributeBoolean(id_jobentry, "exec_per_row"); setLogfile = rep.getJobEntryAttributeBoolean(id_jobentry, "set_logfile"); addDate = rep.getJobEntryAttributeBoolean(id_jobentry, "add_date"); addTime = rep.getJobEntryAttributeBoolean(id_jobentry, "add_time"); logfile = rep.getJobEntryAttributeString(id_jobentry, "logfile"); logext = rep.getJobEntryAttributeString(id_jobentry, "logext"); loglevel = LogWriter.getLogLevel( rep.getJobEntryAttributeString(id_jobentry, "loglevel") ); String remoteSlaveServerName = rep.getJobEntryAttributeString(id_jobentry, "slave_server_name"); remoteSlaveServer = SlaveServer.findSlaveServer(slaveServers, remoteSlaveServerName); // How many arguments? int argnr = rep.countNrJobEntryAttributes(id_jobentry, "argument"); arguments = new String[argnr]; // Read them all... for (int a=0;a<argnr;a++) { arguments[a]= rep.getJobEntryAttributeString(id_jobentry, a, "argument"); } } catch(KettleDatabaseException dbe) { throw new KettleException("Unable to load job entry of type 'job' from the repository with id_jobentry="+id_jobentry, dbe); } } // Save the attributes of this job entry public void saveRep(Repository rep, long id_job) throws KettleException { try { super.saveRep(rep, id_job); long id_job_attr = rep.getJobID(jobname, directory.getID()); rep.saveJobEntryAttribute(id_job, getID(), "id_job", id_job_attr); rep.saveJobEntryAttribute(id_job, getID(), "name", getJobName()); rep.saveJobEntryAttribute(id_job, getID(), "dir_path", getDirectory()!=null?getDirectory().getPath():""); rep.saveJobEntryAttribute(id_job, getID(), "file_name", filename); rep.saveJobEntryAttribute(id_job, getID(), "arg_from_previous", argFromPrevious); rep.saveJobEntryAttribute(id_job, getID(), "exec_per_row", execPerRow); rep.saveJobEntryAttribute(id_job, getID(), "set_logfile", setLogfile); rep.saveJobEntryAttribute(id_job, getID(), "add_date", addDate); rep.saveJobEntryAttribute(id_job, getID(), "add_time", addTime); rep.saveJobEntryAttribute(id_job, getID(), "logfile", logfile); rep.saveJobEntryAttribute(id_job, getID(), "logext", logext); rep.saveJobEntryAttribute(id_job, getID(), "loglevel", LogWriter.getLogLevelDesc(loglevel)); rep.saveJobEntryAttribute(id_job, getID(), "slave_server_name", remoteSlaveServer!=null ? remoteSlaveServer.getName() : null); // save the arguments... if (arguments!=null) { for (int i=0;i<arguments.length;i++) { rep.saveJobEntryAttribute(id_job, getID(), i, "argument", arguments[i]); } } } catch(KettleDatabaseException dbe) { throw new KettleException("Unable to save job entry of type job to the repository with id_job="+id_job, dbe); } } public Result execute(Result result, int nr, Repository rep, Job parentJob) throws KettleException { result.setEntryNr( nr ); LogWriter logwriter = log; Log4jFileAppender appender = null; int backupLogLevel = log.getLogLevel(); if (setLogfile) { try { appender = LogWriter.createFileAppender(environmentSubstitute(getLogFilename()), true); } catch(KettleException e) { log.logError(toString(), "Unable to open file appender for file ["+getLogFilename()+"] : "+e.toString()); log.logError(toString(), Const.getStackTracker(e)); result.setNrErrors(1); result.setResult(false); return result; } log.addAppender(appender); log.setLogLevel(loglevel); logwriter = LogWriter.getInstance(environmentSubstitute(getLogFilename()), true, loglevel); } try { // First load the job, outside of the loop... if ( parentJob.getJobMeta() != null ) { // reset the internal variables again. // Maybe we should split up the variables even more like in UNIX shells. // The internal variables need to be reset to be able use them properly in 2 sequential sub jobs. parentJob.getJobMeta().setInternalKettleVariables(); } JobMeta jobMeta = null; boolean fromRepository = rep!=null && !Const.isEmpty(jobname) && directory!=null; boolean fromXMLFile = !Const.isEmpty(filename); if (fromRepository) // load from the repository... { log.logDetailed(toString(), "Loading job from repository : ["+directory+" : "+environmentSubstitute(jobname)+"]"); jobMeta = new JobMeta(logwriter, rep, environmentSubstitute(jobname), directory); jobMeta.setParentVariableSpace(parentJob); } else // Get it from the XML file if (fromXMLFile) { log.logDetailed(toString(), "Loading job from XML file : ["+environmentSubstitute(filename)+"]"); jobMeta = new JobMeta(logwriter, environmentSubstitute(filename), rep, null); jobMeta.setParentVariableSpace(parentJob); } if (jobMeta==null) { throw new KettleException("Unable to load the job: please specify the name and repository directory OR a filename"); } verifyRecursiveExecution(parentJob, jobMeta); // Tell logging what job entry we are launching... if (fromRepository) { log.logBasic(toString(), "Starting job, loaded from repository : ["+directory+" : "+environmentSubstitute(jobname)+"]"); } else if (fromXMLFile) { log.logDetailed(toString(), "Starting job, loaded from XML file : ["+environmentSubstitute(filename)+"]"); } int iteration = 0; String args1[] = arguments; if (args1==null || args1.length==0) // no arguments? Check the parent jobs arguments { args1 = parentJob.getJobMeta().getArguments(); } copyVariablesFrom(parentJob); setParentVariableSpace(parentJob); // For the moment only do variable translation at the start of a job, not // for every input row (if that would be switched on) String args[] = null; if ( args1 != null ) { args = new String[args1.length]; for ( int idx = 0; idx < args1.length; idx++ ) { args[idx] = environmentSubstitute(args1[idx]); } } RowMetaAndData resultRow = null; boolean first = true; List<RowMetaAndData> rows = result.getRows(); while( ( first && !execPerRow ) || ( execPerRow && rows!=null && iteration<rows.size() && result.getNrErrors()==0 ) ) { first=false; if (rows!=null && execPerRow) { resultRow = (RowMetaAndData) rows.get(iteration); } else { resultRow = null; } Result oneResult = new Result(); List<RowMetaAndData> sourceRows = null; if (execPerRow) // Execute for each input row { if (argFromPrevious) // Copy the input row to the (command line) arguments { args = null; if (resultRow!=null) { args = new String[resultRow.size()]; for (int i=0;i<resultRow.size();i++) { args[i] = resultRow.getString(i, null); } } } else { // Just pass a single row List<RowMetaAndData> newList = new ArrayList<RowMetaAndData>(); newList.add(resultRow); sourceRows = newList; } } else { if (argFromPrevious) { // Only put the first Row on the arguments args = null; if (resultRow!=null) { args = new String[resultRow.size()]; for (int i=0;i<resultRow.size();i++) { args[i] = resultRow.getString(i, null); } } } else { // Keep it as it was... sourceRows = result.getRows(); } } if (remoteSlaveServer==null) { // Local execution... // Create a new job Job job = new Job(logwriter, StepLoader.getInstance(), rep, jobMeta); job.shareVariablesWith(this); // Set the source rows we calculated above... job.setSourceRows(sourceRows); // Don't forget the logging... job.beginProcessing(); // Link the job with the sub-job parentJob.getJobTracker().addJobTracker(job.getJobTracker()); // Link both ways! job.getJobTracker().setParentJobTracker(parentJob.getJobTracker()); // Tell this sub-job about its parent... job.setParentJob(parentJob); if (parentJob.getJobMeta().isBatchIdPassed()) { job.setPassedBatchId(parentJob.getBatchId()); } job.getJobMeta().setArguments( args ); JobEntryJobRunner runner = new JobEntryJobRunner( job, result, nr); Thread jobRunnerThread = new Thread(runner); jobRunnerThread.setName( Const.NVL(job.getJobMeta().getName(), job.getJobMeta().getFilename()) ); jobRunnerThread.start(); try { while (!runner.isFinished() && !parentJob.isStopped()) { try { Thread.sleep(100);} catch(InterruptedException e) { } } // if the parent-job was stopped, stop the sub-job too... if (parentJob.isStopped()) { job.stopAll(); runner.waitUntilFinished(); // Wait until finished! job.endProcessing("stop", new Result()); // dummy result } else { job.endProcessing("end", runner.getResult()); // the result of the execution to be stored in the log file. } } catch(KettleException je) { log.logError(toString(), "Unable to open job entry job with name ["+getName()+"] : "+Const.CR+je.toString()); result.setNrErrors(1); } oneResult = runner.getResult(); } else { // Remote execution... JobExecutionConfiguration jobExecutionConfiguration = new JobExecutionConfiguration(); jobExecutionConfiguration.setPreviousResult(result.clone()); jobExecutionConfiguration.getPreviousResult().setRows(sourceRows); jobExecutionConfiguration.setArgumentStrings(args); jobExecutionConfiguration.setVariables(this); jobExecutionConfiguration.setRemoteServer(remoteSlaveServer); jobExecutionConfiguration.setRepository(rep); // Send the XML over to the slave server // Also start the job over there... Job.sendXMLToSlaveServer(jobMeta, jobExecutionConfiguration); // Now start the monitoring... while (!parentJob.isStopped()) { try { SlaveServerJobStatus jobStatus = remoteSlaveServer.getJobStatus(jobMeta.getName()); if (jobStatus.getResult()!=null) { // The job is finished, get the result... oneResult = jobStatus.getResult(); break; } } catch (Exception e1) { log.logError(toString(), "Unable to contact slave server ["+remoteSlaveServer+"] to verify the status of job ["+jobMeta.getName()+"]"); oneResult.setNrErrors(1L); break; // Stop looking too, chances are too low the server will come back on-line } try { Thread.sleep(10000); } catch(InterruptedException e) {} ; // sleep for 10 seconds } } if (iteration==0) { result.clear(); } result.add(oneResult); if (oneResult.getResult()==false) // if one of them fails, set the number of errors { result.setNrErrors(result.getNrErrors()+1); } iteration++; } } catch(KettleException ke) { log.logError(toString(), "Error running job entry 'job' : "+ke.toString()); log.logError(toString(), Const.getStackTracker(ke)); result.setResult(false); result.setNrErrors(1L); } if (setLogfile) { if (appender!=null) { log.removeAppender(appender); appender.close(); ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_LOG, appender.getFile(), parentJob.getJobname(), getName()); result.getResultFiles().put(resultFile.getFile().toString(), resultFile); } log.setLogLevel(backupLogLevel); } if (result.getNrErrors() > 0) { result.setResult( false ); } else { result.setResult( true ); } return result; } /** * Make sure that we are not loading jobs recursively... * * @param parentJobMeta the parent job metadata * @param jobMeta the job metadata * @throws KettleException in case both jobs are loaded from the same source */ private void verifyRecursiveExecution(Job parentJob, JobMeta jobMeta) throws KettleException { if (parentJob==null) return; JobMeta parentJobMeta = parentJob.getJobMeta(); if (parentJobMeta.getName()==null && jobMeta.getName()!=null) return; if (parentJobMeta.getName()!=null && jobMeta.getName()==null) return; // OK as well. // Not from the repository? just verify the filename if (jobMeta.getFilename()!=null && jobMeta.getFilename().equals(parentJobMeta.getFilename())) { throw new KettleException(Messages.getString("JobJobError.Recursive", jobMeta.getFilename())); } // Different directories: OK if (parentJobMeta.getDirectory()==null && jobMeta.getDirectory()!=null) return; if (parentJobMeta.getDirectory()!=null && jobMeta.getDirectory()==null) return; if (jobMeta.getDirectory().getID() != parentJobMeta.getDirectory().getID()) return; // Same names, same directories : loaded from same location in the repository: // --> recursive loading taking place! if (parentJobMeta.getName().equals(jobMeta.getName())) { throw new KettleException(Messages.getString("JobJobError.Recursive", jobMeta.getFilename())); } // Also compare with the grand-parent (if there is any) verifyRecursiveExecution(parentJob.getParentJob(), jobMeta); } public void clear() { super.clear(); jobname=null; filename=null; directory = new RepositoryDirectory(); arguments=null; argFromPrevious=false; addDate=false; addTime=false; logfile=null; logext=null; setLogfile=false; } public boolean evaluates() { return true; } public boolean isUnconditional() { return true; } public List<SQLStatement> getSQLStatements(Repository repository) throws KettleException { return getSQLStatements(repository, null); } public List<SQLStatement> getSQLStatements(Repository repository, VariableSpace space) throws KettleException { JobMeta jobMeta = getJobMeta(repository, space); return jobMeta.getSQLStatements(repository, null); } private JobMeta getJobMeta(Repository rep, VariableSpace space) throws KettleException { try { if (rep!=null && getDirectory()!=null) { return new JobMeta(LogWriter.getInstance(), rep, (space != null ? space.environmentSubstitute(getJobName()): getJobName()), getDirectory()); } else { return new JobMeta(LogWriter.getInstance(), (space != null ? space.environmentSubstitute(getFilename()) : getFilename()), rep, null); } } catch(Exception e) { throw new KettleException("Unexpected error during job metadata load", e); } } /** * @return Returns the runEveryResultRow. */ public boolean isExecPerRow() { return execPerRow; } /** * @param runEveryResultRow The runEveryResultRow to set. */ public void setExecPerRow(boolean runEveryResultRow) { this.execPerRow = runEveryResultRow; } public List<ResourceReference> getResourceDependencies(JobMeta jobMeta) { List<ResourceReference> references = super.getResourceDependencies(jobMeta); if (!Const.isEmpty(filename)) { String realFileName = jobMeta.environmentSubstitute(filename); ResourceReference reference = new ResourceReference(this); reference.getEntries().add( new ResourceEntry(realFileName, ResourceType.ACTIONFILE)); references.add(reference); } return references; } /** * We're going to load the transformation meta data referenced here. * Then we're going to give it a new filename, modify that filename in this entries. * The parent caller will have made a copy of it, so it should be OK to do so. */ public String exportResources(VariableSpace space, Map<String, ResourceDefinition> definitions, ResourceNamingInterface namingInterface) throws KettleException { // Try to load the transformation from repository or file. // Modify this recursively too... if (!Const.isEmpty(filename)) { // AGAIN: there is no need to clone this job entry because the caller is responsible for this. // First load the job meta data... copyVariablesFrom(space); // To make sure variables are available. JobMeta jobMeta = getJobMeta(null, null); // Also go down into the job and export the files there. (going down recursively) String newFilename = jobMeta.exportResources(jobMeta, definitions, namingInterface); // Set the filename in the job jobMeta.setFilename(newFilename); // change it in the job entry filename = newFilename; // Don't save it, that has already been done a few lines above, in jobMeta.exportResources() // String xml = jobMeta.getXML(); // definitions.put(newFilename, new ResourceDefinition(newFilename, xml)); return newFilename; } else { return null; } } @Override public void check(List<CheckResultInterface> remarks, JobMeta jobMeta) { if (setLogfile) { andValidator().validate(this, "logfile", remarks, putValidators(notBlankValidator())); //$NON-NLS-1$ } if (null != directory) { // if from repo andValidator().validate(this, "directory", remarks, putValidators(notNullValidator())); //$NON-NLS-1$ andValidator().validate(this, "jobName", remarks, putValidators(notBlankValidator())); //$NON-NLS-1$ } else { // else from xml file andValidator().validate(this, "filename", remarks, putValidators(notBlankValidator())); //$NON-NLS-1$ } } public static void main(String[] args) { List<CheckResultInterface> remarks = new ArrayList<CheckResultInterface>(); new JobEntryJob().check(remarks, null); System.out.printf("Remarks: %s\n", remarks); } protected String getLogfile() { return logfile; } /** * @return the remoteSlaveServer */ public SlaveServer getRemoteSlaveServer() { return remoteSlaveServer; } /** * @param remoteSlaveServer the remoteSlaveServer to set */ public void setRemoteSlaveServer(SlaveServer remoteSlaveServer) { this.remoteSlaveServer = remoteSlaveServer; } }
package me.coley.recaf; import me.coley.recaf.common.JavaFxTest; import me.coley.recaf.config.impl.ConfDisplay; import me.coley.recaf.ui.FormatFactory; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.objectweb.asm.tree.*; import java.util.ArrayList; import static java.util.Arrays.asList; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.objectweb.asm.Opcodes.*; /** * Tests for FormatFactory * * @author Matt */ // TODO: InvokeDynamic insns public class FormatFactoryTest implements JavaFxTest { @BeforeAll public static void setup() { // Assumes the @BeforeAll's of the interfaces are called first ConfDisplay.instance().jumpHelp = false; } @Test public void testBasicInsns() { individual(new InsnNode(NOP), "NOP"); individual(new IntInsnNode(BIPUSH, 10), "BIPUSH 10"); individual(new VarInsnNode(ALOAD, 0), "ALOAD 0"); individual(new LineNumberNode(10, new LabelNode()), "LINE 10:LABEL A"); } @Test public void testJumpInsns() { // Will be shown as "LABEL A" LabelNode dummy = new LabelNode(); individual(new JumpInsnNode(IFEQ, dummy), "IFEQ LABEL A"); individual(dummy, "LABEL A"); } @Test public void testTableSwitch() { // Setup int min = 0, max = 2; LabelNode dflt = new LabelNode(); LabelNode exit = new LabelNode(); LabelNode[] lbls = new LabelNode[]{new LabelNode(), new LabelNode(), new LabelNode()}; MethodNode dummyMethod = new MethodNode(ACC_PUBLIC, "name", "()V", null, null); InsnList insns = dummyMethod.instructions = new InsnList(); insns.add(new TableSwitchInsnNode(min, max, dflt, lbls)); for(LabelNode lbl : lbls) { insns.add(lbl); insns.add(new InsnNode(NOP)); insns.add(new JumpInsnNode(GOTO, exit)); } insns.add(dflt); insns.add(new InsnNode(NOP)); insns.add(new InsnNode(NOP)); insns.add(new JumpInsnNode(GOTO, exit)); insns.add(exit); insns.add(new InsnNode(RETURN)); // Matching // - Range should be min-max // - Offsets should be A, B, C due to insertion order into "insns", Default then is "D" String[] out = FormatFactory.insnsString(asList(insns.toArray()), dummyMethod).split("\n"); assertEquals(out[0], "0 : TABLESWITCH range[0-2] offsets[A, B, C] default:D"); } @Test public void testLookupSwitch() { LabelNode dflt = new LabelNode(); LabelNode exit = new LabelNode(); int[] keys = new int[]{0, 1, 2}; LabelNode[] lbls = new LabelNode[]{new LabelNode(), new LabelNode(), new LabelNode()}; MethodNode dummyMethod = new MethodNode(ACC_PUBLIC, "name", "()V", null, null); InsnList insns = dummyMethod.instructions = new InsnList(); insns.add(new LookupSwitchInsnNode(dflt, keys, lbls)); for(LabelNode lbl : lbls) { insns.add(lbl); insns.add(new InsnNode(NOP)); insns.add(new JumpInsnNode(GOTO, exit)); } insns.add(dflt); insns.add(new InsnNode(NOP)); insns.add(new InsnNode(NOP)); insns.add(new JumpInsnNode(GOTO, exit)); insns.add(exit); insns.add(new InsnNode(RETURN)); // Matching // - Keys and mappings fit a 1:1 ratio // - Mappings should be A, B, C due to insertion order into "insns", Default then is "D" String[] out = FormatFactory.insnsString(asList(insns.toArray()), dummyMethod).split("\n"); assertEquals(out[0], "0 : LOOKUPSWITCH mapping[0=A, 1=B, 2=C] default:D"); } @Test public void testLdcInsns() { individual(new LdcInsnNode("String"), "LDC \"String\""); individual(new LdcInsnNode("String\nSplit"), "LDC \"String\\nSplit\""); individual(new LdcInsnNode(100L), "LDC 100"); individual(new LdcInsnNode(100D), "LDC 100.0"); individual(new LdcInsnNode(100F), "LDC 100.0"); individual(new IincInsnNode(1, 1), "IINC $1 + 1"); individual(new IincInsnNode(1, -1), "IINC $1 - 1"); } @Test public void testSimplifiableInsns() { individual(new TypeInsnNode(NEW, "some/example/Type"), "NEW Type", "NEW some/example/Type"); individual(new MultiANewArrayInsnNode("Ljava/lang/String;", 2), "MULTIANEWARRAY String[][]", "MULTIANEWARRAY Ljava/lang/String;[][]"); individual(new FieldInsnNode(GETFIELD, "java/lang/System", "out", "Ljava/io/PrintStream;"), "GETFIELD System.out PrintStream", "GETFIELD java/lang/System.out Ljava/io/PrintStream;"); individual(new MethodInsnNode(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V"), "INVOKEVIRTUAL PrintStream.println(String)void", "INVOKEVIRTUAL java/io/PrintStream.println(Ljava/lang/String;)V"); } @Test public void testVariableData() { // Setup method MethodNode dummyMethod = new MethodNode(ACC_PUBLIC, "name", "(I)V", null, null); InsnList insns = dummyMethod.instructions = new InsnList(); LabelNode start = new LabelNode(), end = new LabelNode(); insns.add(start); insns.add(new VarInsnNode(ALOAD, 0)); insns.add(new VarInsnNode(ILOAD, 1)); insns.add(end); // Setup variables dummyMethod.localVariables = new ArrayList<>(); dummyMethod.localVariables.add(new LocalVariableNode("this", "Ljava/lang/Object;", null, start, end, 0)); dummyMethod.localVariables.add(new LocalVariableNode("param", "I", null, start, end, 1)); // Matching individual(dummyMethod, insns.get(1), "1: ALOAD 0 [this:Ljava/lang/Object;]"); individual(dummyMethod, insns.get(2), "2: ILOAD 1 [param:I]"); } private void individual(MethodNode method, AbstractInsnNode insn, String expected) { String actual = FormatFactory.insnNode(insn, method).getText(); assertEquals(expected, actual); } private void individual(AbstractInsnNode insn, String expected) { String actual = FormatFactory.insnNode(insn, null).getText(); assertEquals(expected, actual); } private void individual(AbstractInsnNode insn, String expectedSimple, String expectedFull) { ConfDisplay.instance().simplify = true; individual(insn, expectedSimple); ConfDisplay.instance().simplify = false; individual(insn, expectedFull); } }
package app.musicplayer.model; import java.io.File; import java.io.FileInputStream; import java.nio.file.Paths; import java.time.Duration; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.stream.Collectors; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamReader; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathFactory; import org.jaudiotagger.audio.AudioFile; import org.jaudiotagger.audio.AudioFileIO; import org.jaudiotagger.audio.AudioHeader; import org.jaudiotagger.tag.FieldKey; import org.jaudiotagger.tag.Tag; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import app.musicplayer.MusicPlayer; import app.musicplayer.util.ImportMusicTask; import app.musicplayer.util.Resources; import javafx.collections.FXCollections; import javafx.collections.ObservableList; public final class Library { private static final String ID = "id"; private static final String TITLE = "title"; private static final String ARTIST = "artist"; private static final String ALBUM = "album"; private static final String LENGTH = "length"; private static final String TRACKNUMBER = "trackNumber"; private static final String DISCNUMBER = "discNumber"; private static final String PLAYCOUNT = "playCount"; private static final String PLAYDATE = "playDate"; private static final String LOCATION = "location"; private static ArrayList<Song> songs; private static ArrayList<Artist> artists; private static ArrayList<Album> albums; private static ArrayList<Playlist> playlists; private static int maxProgress; private static ImportMusicTask<Boolean> task; // Stores new songs added to library when app is running. private static ArrayList<Song> newSongs; // Stores the currently selected playlist. private static Playlist selectedPlaylist; /** * Gets a list of songs. * @return observable list of songs */ public static ObservableList<Song> getSongs() { // If the observable list of songs has not been initialized. if (songs == null) { songs = new ArrayList<Song>(); // Updates the songs array list. updateSongsList(); } else if (songs != null) { // Empties the song list to avoid duplicates and clears the songs array list. songs.clear(); updateSongsList(); } return FXCollections.observableArrayList(songs); } /** * Gets a list of albums. * * @return observable list of albums */ public static ObservableList<Album> getAlbums() { // If the observable list of albums has not been initialized. if (albums == null) { if (songs == null) { getSongs(); } // Updates the albums array list. updateAlbumsList(); } else if (albums != null) { // Empties the albums list to avoid duplicates and clears the albums array list. albums.clear(); updateAlbumsList(); } return FXCollections.observableArrayList(albums); } /** * Gets a list of artists. * * @return observable list of artists */ public static ObservableList<Artist> getArtists() { if (artists == null) { if (albums == null) { getAlbums(); } // Updates the artists array list. updateArtistsList(); } else if (artists != null) { // Empties the artists list to avoid duplicates and clears the artists array list. artists.clear(); updateArtistsList(); } return FXCollections.observableArrayList(artists); } public static ObservableList<Playlist> getPlaylists() { if (playlists == null) { playlists = new ArrayList<Playlist>(); int id = 0; try { XMLInputFactory factory = XMLInputFactory.newInstance(); factory.setProperty("javax.xml.stream.isCoalescing", true); FileInputStream is = new FileInputStream(new File(Resources.JAR + "library.xml")); XMLStreamReader reader = factory.createXMLStreamReader(is, "UTF-8"); String element = ""; boolean isPlaylist = false; String title = null; ArrayList<Song> songs = new ArrayList<Song>(); while(reader.hasNext()) { reader.next(); if (reader.isWhiteSpace()) { continue; } else if (reader.isStartElement()) { element = reader.getName().getLocalPart(); // If the element is a play list, reads the element attributes to retrieve // the play list id and title. if (element.equals("playlist")) { isPlaylist = true; id = Integer.parseInt(reader.getAttributeValue(0)); title = reader.getAttributeValue(1); } } else if (reader.isCharacters() && isPlaylist) { // Retrieves the reader value (song ID), gets the song and adds it to the songs list. String value = reader.getText(); songs.add(getSong(Integer.parseInt(value))); } else if (reader.isEndElement() && reader.getName().getLocalPart().equals("playlist")) { // If the play list id, title, and songs have been retrieved, a new play list is created // and the values reset. playlists.add(new Playlist(id, title, songs)); id = -1; title = null; songs = new ArrayList<Song>(); } else if (reader.isEndElement() && reader.getName().getLocalPart().equals("playlists")) { reader.close(); break; } } reader.close(); } catch (Exception ex) { ex.printStackTrace(); } playlists.sort((x, y) -> { if (x.getId() < y.getId()) { return 1; } else if (x.getId() > y.getId()) { return -1; } else { return 0; } }); playlists.add(new MostPlayedPlaylist(id++)); playlists.add(new RecentlyPlayedPlaylist(id++)); } return FXCollections.observableArrayList(playlists); } public static ArrayList<Song> loadPlayingList() { ArrayList<Song> nowPlayingList = new ArrayList<Song>(); try { XMLInputFactory factory = XMLInputFactory.newInstance(); FileInputStream is = new FileInputStream(new File(Resources.JAR + "library.xml")); XMLStreamReader reader = factory.createXMLStreamReader(is, "UTF-8"); String element = ""; boolean isNowPlayingList = false; while(reader.hasNext()) { reader.next(); if (reader.isWhiteSpace()) { continue; } else if (reader.isCharacters() && isNowPlayingList) { String value = reader.getText(); if (element.equals(ID)) { nowPlayingList.add(getSong(Integer.parseInt(value))); } } else if (reader.isStartElement()) { element = reader.getName().getLocalPart(); if (element.equals("nowPlayingList")) { isNowPlayingList = true; } } else if (reader.isEndElement() && reader.getName().getLocalPart().equals("nowPlayingList")) { reader.close(); break; } } reader.close(); } catch (Exception ex) { ex.printStackTrace(); } return nowPlayingList; } public static void savePlayingList() { Thread thread = new Thread(() -> { try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(Resources.JAR + "library.xml"); XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); XPathExpression expr = xpath.compile("/library/nowPlayingList"); Node playingList = ((NodeList) expr.evaluate(doc, XPathConstants.NODESET)).item(0); NodeList nodes = playingList.getChildNodes(); while (nodes.getLength() > 0) { playingList.removeChild(nodes.item(0)); } for (Song song : MusicPlayer.getNowPlayingList()) { Element id = doc.createElement(ID); id.setTextContent(Integer.toString(song.getId())); playingList.appendChild(id); } TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource source = new DOMSource(doc); File xmlFile = new File(Resources.JAR + "library.xml"); StreamResult result = new StreamResult(xmlFile); transformer.transform(source, result); } catch (Exception ex) { ex.printStackTrace(); } }); thread.start(); } public static void addPlaylist(String text) { Thread thread = new Thread(() -> { int i = playlists.size() - 2; playlists.add(new Playlist(i, text, new ArrayList<Song>())); try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(Resources.JAR + "library.xml"); XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); XPathExpression expr = xpath.compile("/library/playlists"); Node playlists = ((NodeList) expr.evaluate(doc, XPathConstants.NODESET)).item(0); Element playlist = doc.createElement("playlist"); playlist.setAttribute("id", Integer.toString(i)); playlist.setAttribute(TITLE, text); playlists.appendChild(playlist); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource source = new DOMSource(doc); File xmlFile = new File(Resources.JAR + "library.xml"); StreamResult result = new StreamResult(xmlFile); transformer.transform(source, result); } catch (Exception ex) { ex.printStackTrace(); } }); thread.start(); } // GETTERS /** * Gets artists based on id number. * * @param id * @return artists */ public static Artist getArtist(int id) { if (artists == null) { getArtists(); } return artists.get(id); } public static Album getAlbum(int id) { if (albums == null) { getAlbums(); } return albums.get(id); } public static Song getSong(int id) { if (songs == null) { getSongs(); } return songs.get(id); } public static Playlist getPlaylist(int id) { if (playlists == null) { getPlaylists(); } // Gets the play list size. int playListSize = Library.getPlaylists().size(); // The +2 takes into account the two default play lists. // The -1 is used because size() starts at 1 but indexes start at 0. return playlists.get(playListSize - (id + 2) - 1); } public static Artist getArtist(String title) { if (artists == null) { getArtists(); } return artists.stream().filter(artist -> title.equals(artist.getTitle())).findFirst().get(); } public static Album getAlbum(String title) { if (albums == null) { getAlbums(); } return albums.stream().filter(album -> title.equals(album.getTitle())).findFirst().get(); } public static Song getSong(String title) { if (songs == null) { getSongs(); } return songs.stream().filter(song -> title.equals(song.getTitle())).findFirst().get(); } public static Playlist getPlaylist(String title) { if (playlists == null) { getPlaylists(); } return playlists.stream().filter(playlist -> title.equals(playlist.getTitle())).findFirst().get(); } public static Playlist getSelectedPlaylist() { return selectedPlaylist; } public static ObservableList<Song> getNewSongs() { // Initializes the array list if it is null. if (newSongs == null) { newSongs = new ArrayList<Song>(); } return FXCollections.observableArrayList(newSongs); } public static void setSelectedPlaylist(Playlist playlist) { selectedPlaylist = playlist; } /** * Adds a song to the new song array list. * @param newSong */ public static void addNewSong(Song newSong) { // Initializes the array list if it is null. if (newSongs == null) { newSongs = new ArrayList<Song>(); } newSongs.add(newSong); } /** * Clears the new songs array list to prevent song duplicates. */ public static void clearNewSongs() { newSongs.clear(); } public static void importMusic(String path, ImportMusicTask<Boolean> task) throws Exception { Library.maxProgress = 0; Library.task = task; DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.newDocument(); Element library = doc.createElement("library"); Element musicLibrary = doc.createElement("musicLibrary"); Element songs = doc.createElement("songs"); Element playlists = doc.createElement("playlists"); Element nowPlayingList = doc.createElement("nowPlayingList"); // Adds elements to library section. doc.appendChild(library); library.appendChild(musicLibrary); library.appendChild(songs); library.appendChild(playlists); library.appendChild(nowPlayingList); // Creates sub sections for music library path and number of files. Element musicLibraryPath = doc.createElement("path"); Element musicLibraryFileNum = doc.createElement("fileNum"); // Adds music library path to xml file. musicLibraryPath.setTextContent(path); musicLibrary.appendChild(musicLibraryPath); int id = 0; File directory = new File(Paths.get(path).toUri()); getMaxProgress(directory); Library.task.updateProgress(id, Library.maxProgress); // Writes xml file and returns the number of files in the music directory. int i = writeXML(directory, doc, songs, id); String fileNumber = Integer.toString(i); // Adds the number of files in the music directory to the appropriate section in the xml file. musicLibraryFileNum.setTextContent(fileNumber); musicLibrary.appendChild(musicLibraryFileNum); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource source = new DOMSource(doc); File xmlFile = new File(Resources.JAR + "library.xml"); StreamResult result = new StreamResult(xmlFile); transformer.transform(source, result); Library.maxProgress = 0; Library.task = null; } public static void updateSongsList() { try { XMLInputFactory factory = XMLInputFactory.newInstance(); factory.setProperty("javax.xml.stream.isCoalescing", true); FileInputStream is = new FileInputStream(new File(Resources.JAR + "library.xml")); XMLStreamReader reader = factory.createXMLStreamReader(is, "UTF-8"); String element = ""; int id = -1; String title = null; String artist = null; String album = null; Duration length = null; int trackNumber = -1; int discNumber = -1; int playCount = -1; LocalDateTime playDate = null; String location = null; while(reader.hasNext()) { reader.next(); if (reader.isWhiteSpace()) { continue; } else if (reader.isCharacters()) { String value = reader.getText(); switch (element) { case ID: id = Integer.parseInt(value); break; case TITLE: title = value; break; case ARTIST: artist = value; break; case ALBUM: album = value; break; case LENGTH: length = Duration.ofSeconds(Long.parseLong(value)); break; case TRACKNUMBER: trackNumber = Integer.parseInt(value); break; case DISCNUMBER: discNumber = Integer.parseInt(value); break; case PLAYCOUNT: playCount = Integer.parseInt(value); break; case PLAYDATE: playDate = LocalDateTime.parse(value); break; case LOCATION: location = value; break; } // End switch } else if (reader.isStartElement()) { element = reader.getName().getLocalPart(); } else if (reader.isEndElement() && reader.getName().getLocalPart().equals("song")) { songs.add(new Song(id, title, artist, album, length, trackNumber, discNumber, playCount, playDate, location)); id = -1; title = null; artist = null; album = null; length = null; trackNumber = -1; discNumber = -1; playCount = -1; playDate = null; location = null; } else if (reader.isEndElement() && reader.getName().getLocalPart().equals("songs")) { reader.close(); break; } } // End while reader.close(); } catch (Exception ex) { ex.printStackTrace(); } } public static void updateAlbumsList() { albums = new ArrayList<Album>(); TreeMap<String, List<Song>> albumMap = new TreeMap<String, List<Song>>( songs.stream() .filter(song -> song.getAlbum() != null) .collect(Collectors.groupingBy(Song::getAlbum)) ); int id = 0; for (Map.Entry<String, List<Song>> entry : albumMap.entrySet()) { ArrayList<Song> songs = new ArrayList<Song>(); for (Song song : entry.getValue()) { songs.add(song); } TreeMap<String, List<Song>> artistMap = new TreeMap<String, List<Song>>( songs.stream() .filter(song -> song.getArtist() != null) .collect(Collectors.groupingBy(Song::getArtist)) ); for (Map.Entry<String, List<Song>> e : artistMap.entrySet()) { ArrayList<Song> albumSongs = new ArrayList<Song>(); String artist = e.getValue().get(0).getArtist(); for (Song s : e.getValue()) { albumSongs.add(s); } albums.add(new Album(id++, entry.getKey(), artist, albumSongs)); } } } public static void updateArtistsList() { artists = new ArrayList<Artist>(); TreeMap<String, List<Album>> artistMap = new TreeMap<String, List<Album>>( albums.stream() .filter(album -> album.getArtist() != null) .collect(Collectors.groupingBy(Album::getArtist)) ); for (Map.Entry<String, List<Album>> entry : artistMap.entrySet()) { ArrayList<Album> albums = new ArrayList<Album>(); for (Album album : entry.getValue()) { albums.add(album); } artists.add(new Artist(entry.getKey(), albums)); } } public static void removePlaylist(Playlist playlist) { playlists.remove(playlist); } private static void getMaxProgress(File directory) { File[] files = directory.listFiles(); for (File file : files) { if (file.isFile() && isSupportedFileType(file.getName())) { Library.maxProgress++; } else if (file.isDirectory()) { getMaxProgress(file); } } } private static boolean isSupportedFileType(String fileName) { String extension = ""; int i = fileName.lastIndexOf('.'); if (i > 0) { extension = fileName.substring(i+1); } switch (extension) { // MP3 case "mp3": // MP4 case "mp4": case "m4a": case "m4p": case "m4b": case "m4r": case "m4v": // OGG VORBIS case "ogg": case "oga": case "ogx": case "ogm": case "spx": case "opus": // FLAC case "flac": // WAV case "wav": case "wave": // WMA case "wma": // REAL case "ra": case "ram": return true; default: return false; } } private static int writeXML(File directory, Document doc, Element songs, int i) { File[] files = directory.listFiles(); for (File file : files) { if (file.isFile()) { try { AudioFile audioFile = AudioFileIO.read(file); Tag tag = audioFile.getTag(); AudioHeader header = audioFile.getAudioHeader(); Element song = doc.createElement("song"); songs.appendChild(song); Element id = doc.createElement("id"); Element title = doc.createElement("title"); Element artist = doc.createElement("artist"); Element album = doc.createElement("album"); Element length = doc.createElement("length"); Element trackNumber = doc.createElement("trackNumber"); Element discNumber = doc.createElement("discNumber"); Element playCount = doc.createElement("playCount"); Element playDate = doc.createElement("playDate"); Element location = doc.createElement("location"); id.setTextContent(Integer.toString(i++)); title.setTextContent(tag.getFirst(FieldKey.TITLE)); String artistTitle = tag.getFirst(FieldKey.ALBUM_ARTIST); if (artistTitle == null || artistTitle.equals("") || artistTitle.equals("null")) { artistTitle = tag.getFirst(FieldKey.ARTIST); } artist.setTextContent( (artistTitle == null || artistTitle.equals("") || artistTitle.equals("null")) ? "" : artistTitle ); album.setTextContent(tag.getFirst(FieldKey.ALBUM)); length.setTextContent(Integer.toString(header.getTrackLength())); String track = tag.getFirst(FieldKey.TRACK); trackNumber.setTextContent( (track == null || track.equals("") || track.equals("null")) ? "0" : track ); String disc = tag.getFirst(FieldKey.DISC_NO); discNumber.setTextContent( (disc == null || disc.equals("") || disc.equals("null")) ? "0" : disc ); playCount.setTextContent("0"); playDate.setTextContent(LocalDateTime.now().toString()); location.setTextContent(Paths.get(file.getAbsolutePath()).toString()); song.appendChild(id); song.appendChild(title); song.appendChild(artist); song.appendChild(album); song.appendChild(length); song.appendChild(trackNumber); song.appendChild(discNumber); song.appendChild(playCount); song.appendChild(playDate); song.appendChild(location); task.updateProgress(i, Library.maxProgress); } catch (Exception ex) { ex.printStackTrace(); } } else if (file.isDirectory()) { i = writeXML(file, doc, songs, i); } } return i; } }
package org.owasp.esapi.codecs; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; public class CodecTest extends TestCase { private static final char[] EMPTY_CHAR_ARRAY = new char[0]; private static final Character LESS_THAN = Character.valueOf('<'); private static final Character SINGLE_QUOTE = Character.valueOf('\''); private HTMLEntityCodec htmlCodec = new HTMLEntityCodec(); private PercentCodec percentCodec = new PercentCodec(); private JavaScriptCodec javaScriptCodec = new JavaScriptCodec(); private VBScriptCodec vbScriptCodec = new VBScriptCodec(); private CSSCodec cssCodec = new CSSCodec(); private MySQLCodec mySQLCodecANSI = new MySQLCodec( MySQLCodec.ANSI_MODE ); private MySQLCodec mySQLCodecStandard = new MySQLCodec( MySQLCodec.MYSQL_MODE ); private OracleCodec oracleCodec = new OracleCodec(); private UnixCodec unixCodec = new UnixCodec(); private WindowsCodec windowsCodec = new WindowsCodec(); /** * Instantiates a new access reference map test. * * @param testName * the test name */ public CodecTest(String testName) { super(testName); } /** * {@inheritDoc} * @throws Exception */ protected void setUp() throws Exception { // none } /** * {@inheritDoc} * @throws Exception */ protected void tearDown() throws Exception { // none } /** * Suite. * * @return the test */ public static Test suite() { TestSuite suite = new TestSuite(CodecTest.class); return suite; } public void testHtmlEncode() { assertEquals( "test", htmlCodec.encode( EMPTY_CHAR_ARRAY, "test") ); } public void testPercentEncode() { assertEquals( "%3c", percentCodec.encode(EMPTY_CHAR_ARRAY, "<") ); } public void testJavaScriptEncode() { assertEquals( "\\x3C", javaScriptCodec.encode(EMPTY_CHAR_ARRAY, "<") ); } public void testVBScriptEncode() { assertEquals( "chrw(60)", vbScriptCodec.encode(EMPTY_CHAR_ARRAY, "<") ); } public void testCSSEncode() { assertEquals( "\\3c ", cssCodec.encode(EMPTY_CHAR_ARRAY, "<") ); } public void testMySQLANSCIEncode() { assertEquals( "\'\'", mySQLCodecANSI.encode(EMPTY_CHAR_ARRAY, "\'") ); } public void testMySQLStandardEncode() { assertEquals( "\\<", mySQLCodecStandard.encode(EMPTY_CHAR_ARRAY, "<") ); } public void testOracleEncode() { assertEquals( "\'\'", oracleCodec.encode(EMPTY_CHAR_ARRAY, "\'") ); } public void testUnixEncode() { assertEquals( "\\<", unixCodec.encode(EMPTY_CHAR_ARRAY, "<") ); } public void testWindowsEncode() { assertEquals( "^<", windowsCodec.encode(EMPTY_CHAR_ARRAY, "<") ); } public void testHtmlEncodeChar() { assertEquals( "&lt;", htmlCodec.encodeCharacter(EMPTY_CHAR_ARRAY, LESS_THAN) ); } public void testPercentEncodeChar() { assertEquals( "%3c", percentCodec.encodeCharacter(EMPTY_CHAR_ARRAY, LESS_THAN) ); } public void testJavaScriptEncodeChar() { assertEquals( "\\x3C", javaScriptCodec.encodeCharacter(EMPTY_CHAR_ARRAY, LESS_THAN) ); } public void testVBScriptEncodeChar() { assertEquals( "chrw(60)", vbScriptCodec.encodeCharacter(EMPTY_CHAR_ARRAY, LESS_THAN) ); } public void testCSSEncodeChar() { assertEquals( "\\3c ", cssCodec.encodeCharacter(EMPTY_CHAR_ARRAY, LESS_THAN) ); } public void testMySQLANSIEncodeChar() { assertEquals( "\'\'", mySQLCodecANSI.encodeCharacter(EMPTY_CHAR_ARRAY, SINGLE_QUOTE)); } public void testMySQLStandardEncodeChar() { assertEquals( "\\<", mySQLCodecStandard.encodeCharacter(EMPTY_CHAR_ARRAY, LESS_THAN) ); } public void testOracleEncodeChar() { assertEquals( "\'\'", oracleCodec.encodeCharacter(EMPTY_CHAR_ARRAY, SINGLE_QUOTE) ); } public void testUnixEncodeChar() { assertEquals( "\\<", unixCodec.encodeCharacter(EMPTY_CHAR_ARRAY, LESS_THAN) ); } public void testWindowsEncodeChar() { assertEquals( "^<", windowsCodec.encodeCharacter(EMPTY_CHAR_ARRAY, LESS_THAN) ); } public void testHtmlDecodeDecimalEntities() { assertEquals( "test!", htmlCodec.decode("&#116;&#101;&#115;&#116;!") ); } public void testHtmlDecodeHexEntitites() { assertEquals( "test!", htmlCodec.decode("&#x74;&#x65;&#x73;&#x74;!") ); } public void testHtmlDecodeInvalidAttribute() { assertEquals( "&jeff;", htmlCodec.decode("&jeff;") ); } public void testPercentDecode() { assertEquals( "<", percentCodec.decode("%3c") ); } public void testJavaScriptDecodeBackSlashHex() { assertEquals( "<", javaScriptCodec.decode("\\x3c") ); } public void testVBScriptDecode() { assertEquals( "<", vbScriptCodec.decode("\"<") ); } public void testCSSDecode() { assertEquals( "<", cssCodec.decode("\\<") ); } public void testMySQLANSIDecode() { assertEquals( "\'", mySQLCodecANSI.decode("\'\'") ); } public void testMySQLStandardDecode() { assertEquals( "<", mySQLCodecStandard.decode("\\<") ); } public void testOracleDecode() { assertEquals( "\'", oracleCodec.decode("\'\'") ); } public void testUnixDecode() { assertEquals( "<", unixCodec.decode("\\<") ); } public void testWindowsDecode() { assertEquals( "<", windowsCodec.decode("^<") ); } public void testHtmlDecodeCharLessThan() { assertEquals( LESS_THAN, htmlCodec.decodeCharacter(new PushbackString("&lt;")) ); } public void testPercentDecodeChar() { assertEquals( LESS_THAN, percentCodec.decodeCharacter(new PushbackString("%3c") )); } public void testJavaScriptDecodeCharBackSlashHex() { assertEquals( LESS_THAN, javaScriptCodec.decodeCharacter(new PushbackString("\\x3c") )); } public void testVBScriptDecodeChar() { assertEquals( LESS_THAN, vbScriptCodec.decodeCharacter(new PushbackString("\"<") )); } public void testCSSDecodeCharBackSlashHex() { assertEquals( LESS_THAN, cssCodec.decodeCharacter(new PushbackString("\\3c") )); } public void testMySQLANSIDecodCharQuoteQuote() { assertEquals( SINGLE_QUOTE, mySQLCodecANSI.decodeCharacter(new PushbackString("\'\'") )); } public void testMySQLStandardDecodeCharBackSlashLessThan() { assertEquals( LESS_THAN, mySQLCodecStandard.decodeCharacter(new PushbackString("\\<") )); } public void testOracleDecodeCharBackSlashLessThan() { assertEquals( SINGLE_QUOTE, oracleCodec.decodeCharacter(new PushbackString("\'\'") )); } public void testUnixDecodeCharBackSlashLessThan() { assertEquals( LESS_THAN, unixCodec.decodeCharacter(new PushbackString("\\<") )); } public void testWindowsDecodeCharCarrotLessThan() { assertEquals( LESS_THAN, windowsCodec.decodeCharacter(new PushbackString("^<") )); } }
package replicant; import arez.ArezContext; import arez.Disposable; import arez.annotations.Action; import arez.annotations.ContextRef; import arez.annotations.Observable; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Objects; import java.util.function.Consumer; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.realityforge.anodoc.TestOnly; import replicant.spy.ConnectFailureEvent; import replicant.spy.ConnectedEvent; import replicant.spy.DataLoadStatus; import replicant.spy.DisconnectFailureEvent; import replicant.spy.DisconnectedEvent; import replicant.spy.MessageProcessFailureEvent; import replicant.spy.MessageProcessedEvent; import replicant.spy.MessageReadFailureEvent; import replicant.spy.RestartEvent; import replicant.spy.SubscribeCompletedEvent; import replicant.spy.SubscribeFailedEvent; import replicant.spy.SubscribeRequestQueuedEvent; import replicant.spy.SubscribeStartedEvent; import replicant.spy.SubscriptionUpdateCompletedEvent; import replicant.spy.SubscriptionUpdateFailedEvent; import replicant.spy.SubscriptionUpdateRequestQueuedEvent; import replicant.spy.SubscriptionUpdateStartedEvent; import replicant.spy.UnsubscribeCompletedEvent; import replicant.spy.UnsubscribeFailedEvent; import replicant.spy.UnsubscribeRequestQueuedEvent; import replicant.spy.UnsubscribeStartedEvent; import static org.realityforge.braincheck.Guards.*; /** * The Connector is responsible for managing a Connection to a backend datasource. */ public abstract class Connector extends ReplicantService { private static final int DEFAULT_LINKS_TO_PROCESS_PER_TICK = 100; private static final int DEFAULT_CHANGES_TO_PROCESS_PER_TICK = 100; /** * The code to parse changesets. Extracted into a separate class so it can be vary by environment. */ private final ChangeSetParser _changeSetParser = new ChangeSetParser(); /** * The schema that defines data-API used to interact with datasource. */ @Nonnull private final SystemSchema _schema; /** * The transport that connects to the backend system. */ @Nonnull private final Transport _transport; @Nonnull private ConnectorState _state = ConnectorState.DISCONNECTED; /** * The current connection managed by the connector, if any. */ @Nullable private Connection _connection; /** * Flag indicating that the Connectors internal scheduler is actively progressing * requests and responses. A scheduler should only be active if there is a connection present. */ private boolean _schedulerActive; /** * This lock is acquired by the Connector when it begins processing messages from the network. * Once the processor is idle the lock should be released to allow Arez to reflect all the changes. */ @Nullable private Disposable _schedulerLock; /** * Maximum number of entity links to attempt in a single tick of the scheduler. After this many links have * been processed then return and any remaining links can occur in a later tick. */ private int _linksToProcessPerTick = DEFAULT_LINKS_TO_PROCESS_PER_TICK; /** * Maximum number of EntityChange messages processed in a single tick of the scheduler. After this many changes have * been processed then return and any remaining change can be processed in a later tick. */ private int _changesToProcessPerTick = DEFAULT_CHANGES_TO_PROCESS_PER_TICK; /** * Action invoked after current MessageResponse is processed. This is typically used to update or alter * change Connection on message processing complete. */ @Nullable private SafeProcedure _postMessageResponseAction; protected Connector( @Nullable final ReplicantContext context, @Nonnull final SystemSchema schema, @Nonnull final Transport transport ) { super( context ); _schema = Objects.requireNonNull( schema ); _transport = Objects.requireNonNull( transport ); getReplicantRuntime().registerConnector( this ); getReplicantContext().getSchemaService().registerSchema( schema ); } @PreDispose final void preDispose() { _schedulerActive = false; if ( null != _schedulerLock ) { _schedulerLock.dispose(); _schedulerLock = null; } } /** * Connect to the underlying data source. */ public void connect() { final ConnectorState state = getState(); if ( ConnectorState.CONNECTING != state && ConnectorState.CONNECTED != state ) { ConnectorState newState = ConnectorState.ERROR; try { doConnect( this::onConnected ); newState = ConnectorState.CONNECTING; } finally { setState( newState ); } } } /** * Perform the connection, invoking the action when connection has completed. * * @param action the action to invoke once connect has completed. */ protected abstract void doConnect( @Nonnull SafeProcedure action ); /** * Disconnect from underlying data source. */ public void disconnect() { final ConnectorState state = getState(); if ( ConnectorState.DISCONNECTING != state && ConnectorState.DISCONNECTED != state ) { ConnectorState newState = ConnectorState.ERROR; try { doDisconnect( this::onDisconnected ); newState = ConnectorState.DISCONNECTING; } finally { setState( newState ); } } } /** * Perform the disconnection, invoking the action when disconnection has completed. * * @param action the action to invoke once disconnect has completed. */ protected abstract void doDisconnect( @Nonnull SafeProcedure action ); /** * Return the schema associated with the connector. * * @return the schema associated with the connector. */ @Nonnull public final SystemSchema getSchema() { return _schema; } protected final void setConnection( @Nullable final Connection connection ) { if ( !Objects.equals( connection, _connection ) ) { _connection = connection; purgeSubscriptions(); } } @Nullable protected final Connection getConnection() { return _connection; } @Nonnull final Connection ensureConnection() { if ( Replicant.shouldCheckInvariants() ) { invariant( () -> null != _connection, () -> "Replicant-0031: Connector.ensureConnection() when no connection is present." ); } assert null != _connection; return _connection; } @Nonnull private MessageResponse ensureCurrentMessageResponse() { return ensureConnection().ensureCurrentMessageResponse(); } @Nonnull protected final Transport getTransport() { return _transport; } @Action protected void purgeSubscriptions() { Stream.concat( getReplicantContext().getTypeSubscriptions().stream(), getReplicantContext().getInstanceSubscriptions().stream() ) // Only purge subscriptions for current system .filter( s -> s.getAddress().getSystemId() == getSchema().getId() ) // Purge in reverse order. First instance subscriptions then type subscriptions .sorted( Comparator.reverseOrder() ) .forEachOrdered( Disposable::dispose ); } final void setLinksToProcessPerTick( final int linksToProcessPerTick ) { _linksToProcessPerTick = linksToProcessPerTick; } final void setChangesToProcessPerTick( final int changesToProcessPerTick ) { _changesToProcessPerTick = changesToProcessPerTick; } /** * Return true if an area of interest action with specified parameters is pending or being processed. * When the action parameter is DELETE the filter parameter is ignored. */ final boolean isAreaOfInterestRequestPending( @Nonnull final AreaOfInterestRequest.Type action, @Nonnull final ChannelAddress address, @Nullable final Object filter ) { final Connection connection = getConnection(); return null != connection && connection.isAreaOfInterestRequestPending( action, address, filter ); } /** * Return the index of last matching Type in pending aoi actions list. */ final int lastIndexOfPendingAreaOfInterestRequest( @Nonnull final AreaOfInterestRequest.Type action, @Nonnull final ChannelAddress address, @Nullable final Object filter ) { final Connection connection = getConnection(); return null == connection ? -1 : connection.lastIndexOfPendingAreaOfInterestRequest( action, address, filter ); } final void requestSubscribe( @Nonnull final ChannelAddress address, @Nullable final Object filter ) { ensureConnection().requestSubscribe( address, filter ); triggerMessageScheduler(); if ( Replicant.areSpiesEnabled() && getReplicantContext().getSpy().willPropagateSpyEvents() ) { getReplicantContext().getSpy().reportSpyEvent( new SubscribeRequestQueuedEvent( address, filter ) ); } } final void requestSubscriptionUpdate( @Nonnull final ChannelAddress address, @Nullable final Object filter ) { //TODO: Verify that this address is for an updateable channel ensureConnection().requestSubscriptionUpdate( address, filter ); triggerMessageScheduler(); if ( Replicant.areSpiesEnabled() && getReplicantContext().getSpy().willPropagateSpyEvents() ) { getReplicantContext().getSpy().reportSpyEvent( new SubscriptionUpdateRequestQueuedEvent( address, filter ) ); } } final void requestUnsubscribe( @Nonnull final ChannelAddress address ) { ensureConnection().requestUnsubscribe( address ); triggerMessageScheduler(); if ( Replicant.areSpiesEnabled() && getReplicantContext().getSpy().willPropagateSpyEvents() ) { getReplicantContext().getSpy().reportSpyEvent( new UnsubscribeRequestQueuedEvent( address ) ); } } final boolean isSchedulerActive() { return _schedulerActive; } /** * Schedule request and response processing. * This method should be invoked when requests are queued or responses are received. */ protected final void triggerMessageScheduler() { if ( !_schedulerActive ) { _schedulerActive = true; activateMessageScheduler(); } } /** * Perform a single step progressing requests and responses. * This is invoked from the scheduler and will continue to be * invoked until it returns false. * * @return true if more work is to be done. */ final boolean progressMessages() { if ( null == _schedulerLock ) { _schedulerLock = context().pauseScheduler(); } try { final boolean step1 = progressAreaOfInterestRequestProcessing(); final boolean step2 = progressResponseProcessing(); _schedulerActive = step1 || step2; } catch ( final Throwable e ) { onMessageProcessFailure( e ); _schedulerActive = false; return false; } finally { if ( !_schedulerActive ) { _schedulerLock.dispose(); _schedulerLock = null; } } return _schedulerActive; } /** * Activate the scheduler. * This involves creating a scheduler that will invoke {@link #progressMessages()} until * that method returns false. */ protected abstract void activateMessageScheduler(); /** * Perform a single step processing messages received from the server. * * @return true if more work is to be done. */ boolean progressResponseProcessing() { final Connection connection = ensureConnection(); final MessageResponse response = connection.getCurrentMessageResponse(); if ( null == response ) { // Select the MessageResponse if there is none active return connection.selectNextMessageResponse(); } else if ( response.needsParsing() ) { // Parse the json parseMessageResponse(); return true; } else if ( response.needsChannelChangesProcessed() ) { // Process the updates to channels processChannelChanges(); return true; } else if ( response.areEntityChangesPending() ) { // Process a chunk of entity changes processEntityChanges(); return true; } else if ( response.areEntityLinksPending() ) { // Process a chunk of links processEntityLinks(); return true; } else if ( !response.hasWorldBeenValidated() ) { // Validate the world after the change set has been applied (if feature is enabled) validateWorld(); return true; } else { completeMessageResponse(); return true; } } /** * {@inheritDoc} */ @Nonnull @Observable public ConnectorState getState() { return _state; } protected void setState( @Nonnull final ConnectorState state ) { _state = Objects.requireNonNull( state ); } /** * Build a ChannelAddress from a ChannelChange value. * * @param channelChange the change. * @return the address. */ @Nonnull final ChannelAddress toAddress( @Nonnull final ChannelChange channelChange ) { final int channelId = channelChange.getChannelId(); final Integer subChannelId = channelChange.hasSubChannelId() ? channelChange.getSubChannelId() : null; return new ChannelAddress( getSchema().getId(), channelId, subChannelId ); } @Action protected void processChannelChanges() { final MessageResponse response = ensureCurrentMessageResponse(); final ChangeSet changeSet = response.getChangeSet(); final ChannelChange[] channelChanges = changeSet.getChannelChanges(); for ( final ChannelChange channelChange : channelChanges ) { final ChannelAddress address = toAddress( channelChange ); final Object filter = channelChange.getChannelFilter(); final ChannelChange.Action actionType = channelChange.getAction(); if ( ChannelChange.Action.ADD == actionType ) { response.incChannelAddCount(); final boolean explicitSubscribe = ensureConnection() .getCurrentAreaOfInterestRequests() .stream() .anyMatch( a -> a.isInProgress() && a.getAddress().equals( address ) ); getReplicantContext().getSubscriptionService().createSubscription( address, filter, explicitSubscribe ); } else if ( ChannelChange.Action.REMOVE == actionType ) { final Subscription subscription = getReplicantContext().findSubscription( address ); if ( Replicant.shouldCheckInvariants() ) { invariant( () -> null != subscription, () -> "Replicant-0028: Received ChannelChange of type REMOVE for address " + address + " but no such subscription exists." ); assert null != subscription; } assert null != subscription; Disposable.dispose( subscription ); response.incChannelRemoveCount(); } else { assert ChannelChange.Action.UPDATE == actionType; final Subscription subscription = getReplicantContext().findSubscription( address ); if ( Replicant.shouldCheckInvariants() ) { invariant( () -> null != subscription, () -> "Replicant-0033: Received ChannelChange of type UPDATE for address " + address + " but no such subscription exists." ); assert null != subscription; invariant( subscription::isExplicitSubscription, () -> "Replicant-0029: Received ChannelChange of type UPDATE for address " + address + " but subscription is implicitly subscribed." ); } assert null != subscription; subscription.setFilter( filter ); updateSubscriptionForFilteredEntities( subscription ); response.incChannelUpdateCount(); } } response.markChannelActionsProcessed(); } @Action protected void processEntityLinks() { final MessageResponse response = ensureCurrentMessageResponse(); Linkable linkable; for ( int i = 0; i < _linksToProcessPerTick && null != ( linkable = response.nextEntityToLink() ); i++ ) { linkable.link(); response.incEntityLinkCount(); } } /** * Method invoked when a filter has updated and the Connector needs to delink any entities * that are no longer part of the subscription now that the filter has changed. * * @param subscription the subscription that was updated. */ final void updateSubscriptionForFilteredEntities( @Nonnull final Subscription subscription ) { for ( final Class<?> entityType : new ArrayList<>( subscription.findAllEntityTypes() ) ) { final List<Entity> entities = subscription.findAllEntitiesByType( entityType ); if ( !entities.isEmpty() ) { final SubscriptionUpdateEntityFilter entityFilter = getSubscriptionUpdateFilter(); final ChannelAddress address = subscription.getAddress(); final Object filter = subscription.getFilter(); for ( final Entity entity : entities ) { if ( !entityFilter.doesEntityMatchFilter( address, filter, entity ) ) { entity.delinkFromSubscription( subscription ); } } } } } protected final void setPostMessageResponseAction( @Nullable final SafeProcedure postMessageResponseAction ) { _postMessageResponseAction = postMessageResponseAction; } void completeMessageResponse() { final Connection connection = ensureConnection(); final MessageResponse response = connection.ensureCurrentMessageResponse(); // OOB messages are not sequenced if ( !response.isOob() ) { connection.setLastRxSequence( response.getChangeSet().getSequence() ); } //Step: Run the post actions final RequestEntry request = response.getRequest(); if ( null != request ) { request.markResultsAsArrived(); } /* * An action will be returned if the message is an OOB message * or it is an answer to a response and the rpc invocation has * already returned. */ final SafeProcedure action = response.getCompletionAction(); if ( null != action ) { action.call(); // OOB messages are not in response to requests (at least not request associated with the current connection) if ( !response.isOob() ) { // We can remove the request because this side ran second and the RPC channel has already returned. final ChangeSet changeSet = response.getChangeSet(); final Integer requestId = changeSet.getRequestId(); if ( null != requestId ) { connection.removeRequest( requestId ); } } } connection.setCurrentMessageResponse( null ); onMessageProcessed( response.toStatus() ); if ( null != _postMessageResponseAction ) { _postMessageResponseAction.call(); _postMessageResponseAction = null; } } @Action protected void removeExplicitSubscriptions( @Nonnull final List<AreaOfInterestRequest> requests ) { requests.forEach( request -> { if ( Replicant.shouldCheckInvariants() ) { invariant( () -> AreaOfInterestRequest.Type.REMOVE == request.getType(), () -> "Replicant-0034: Connector.removeExplicitSubscriptions() invoked with request " + "with type that is not REMOVE. Request: " + request ); } final Subscription subscription = getReplicantContext().findSubscription( request.getAddress() ); if ( null != subscription ) { /* * It is unclear whether this code is actually required as should note the response from the server * automatically setExplicitSubscription to false? */ subscription.setExplicitSubscription( false ); } } ); } @Action protected void removeUnneededAddRequests( @Nonnull final List<AreaOfInterestRequest> requests ) { requests.removeIf( request -> { final ChannelAddress address = request.getAddress(); final Subscription subscription = getReplicantContext().findSubscription( address ); if ( Replicant.shouldCheckInvariants() ) { invariant( () -> null == subscription || !subscription.isExplicitSubscription(), () -> "Replicant-0030: Request to add channel at address " + address + " but already explicitly subscribed to channel." ); } if ( null != subscription && !subscription.isExplicitSubscription() ) { // Existing subscription converted to an explicit subscription subscription.setExplicitSubscription( true ); request.markAsComplete(); return true; } else { return false; } } ); } @Action protected void removeUnneededUpdateRequests( @Nonnull final List<AreaOfInterestRequest> requests ) { requests.removeIf( a -> { final ChannelAddress address = a.getAddress(); final Subscription subscription = getReplicantContext().findSubscription( address ); if ( Replicant.shouldCheckInvariants() ) { invariant( () -> null != subscription, () -> "Replicant-0048: Request to update channel at address " + address + " but not subscribed to channel." ); } // The following code can probably be removed but it was present in the previous system // and it is unclear if there is any scenarios where it can still happen. The code has // been left in until we can verify it is no longer an issue. The above invariants will trigger // in development mode to help us track down these scenarios if ( null == subscription ) { a.markAsComplete(); return true; } else { return false; } } ); } @Action protected void removeUnneededRemoveRequests( @Nonnull final List<AreaOfInterestRequest> requests ) { requests.removeIf( request -> { final ChannelAddress address = request.getAddress(); final Subscription subscription = getReplicantContext().findSubscription( address ); if ( Replicant.shouldCheckInvariants() ) { invariant( () -> null != subscription, () -> "Replicant-0046: Request to unsubscribe from channel at address " + address + " but not subscribed to channel." ); invariant( () -> null == subscription || subscription.isExplicitSubscription(), () -> "Replicant-0047: Request to unsubscribe from channel at address " + address + " but subscription is not an explicit subscription." ); } // The following code can probably be removed but it was present in the previous system // and it is unclear if there is any scenarios where it can still happen. The code has // been left in until we can verify it is no longer an issue. The above invariants will trigger // in development mode to help us track down these scenarios if ( null == subscription || !subscription.isExplicitSubscription() ) { request.markAsComplete(); return true; } else { return false; } } ); } /** * Parse the json data associated with the current response and then enqueue it. */ void parseMessageResponse() { final Connection connection = ensureConnection(); final MessageResponse response = connection.ensureCurrentMessageResponse(); final String rawJsonData = response.getRawJsonData(); assert null != rawJsonData; final ChangeSet changeSet = _changeSetParser.parseChangeSet( rawJsonData ); if ( Replicant.shouldValidateChangeSetOnRead() ) { changeSet.validate(); } final RequestEntry request; if ( response.isOob() ) { /* * OOB messages are really just cached messages at this stage and they are the * same bytes as originally sent down and then cached. So the requestId present * in the json blob is for old connection and can be ignored. */ request = null; } else { final Integer requestId = changeSet.getRequestId(); final String eTag = changeSet.getETag(); final int sequence = changeSet.getSequence(); request = null != requestId ? connection.getRequest( requestId ) : null; if ( Replicant.shouldCheckApiInvariants() ) { apiInvariant( () -> null != request || null == requestId, () -> "Replicant-0066: Unable to locate request with id '" + requestId + "' specified for ChangeSet with sequence " + sequence + ". Existing Requests: " + connection.getRequests() ); } if ( null != request ) { final String cacheKey = request.getCacheKey(); if ( null != eTag && null != cacheKey ) { final CacheService cacheService = getReplicantContext().getCacheService(); if ( null != cacheService ) { cacheService.store( cacheKey, eTag, rawJsonData ); } } } } response.recordChangeSet( changeSet, request ); connection.queueCurrentResponse(); } @Action protected void processEntityChanges() { final MessageResponse response = ensureCurrentMessageResponse(); EntityChange change; for ( int i = 0; i < _changesToProcessPerTick && null != ( change = response.nextEntityChange() ); i++ ) { final int id = change.getId(); final int typeId = change.getTypeId(); final EntitySchema entitySchema = getSchema().getEntity( typeId ); final Class<?> type = entitySchema.getType(); Entity entity = getReplicantContext().getEntityService().findEntityByTypeAndId( type, id ); if ( change.isRemove() ) { if ( null != entity ) { Disposable.dispose( entity ); } else { if ( Replicant.shouldCheckInvariants() ) { fail( () -> "Replicant-0068: ChangeSet " + response.getChangeSet().getSequence() + " contained an " + "EntityChange message to delete entity of type " + typeId + " and id " + id + " but no such entity exists locally." ); } } response.incEntityRemoveCount(); } else { final EntityChangeData data = change.getData(); if ( null == entity ) { final String name = Replicant.areNamesEnabled() ? entitySchema.getName() + "/" + id : null; entity = getReplicantContext().getEntityService().findOrCreateEntity( name, type, id ); final Object userObject = getChangeMapper().createEntity( entitySchema, id, data ); entity.setUserObject( userObject ); } else { getChangeMapper().updateEntity( entitySchema, entity.getUserObject(), data ); } final EntityChannel[] changeCount = change.getChannels(); final int schemaId = getSchema().getId(); for ( final EntityChannel entityChannel : changeCount ) { final ChannelAddress address = entityChannel.toAddress( schemaId ); final Subscription subscription = getReplicantContext().findSubscription( address ); if ( Replicant.shouldCheckInvariants() ) { invariant( () -> null != subscription, () -> "Replicant-0069: ChangeSet " + response.getChangeSet().getSequence() + " contained an " + "EntityChange message referencing channel " + entityChannel.toAddress( schemaId ) + " but no such subscription exists locally." ); } assert null != subscription; entity.linkToSubscription( subscription ); } response.incEntityUpdateCount(); response.changeProcessed( entity.getUserObject() ); } } } @Nonnull protected abstract ChangeMapper getChangeMapper(); @Nonnull protected abstract SubscriptionUpdateEntityFilter getSubscriptionUpdateFilter(); final void validateWorld() { ensureCurrentMessageResponse().markWorldAsValidated(); if ( Replicant.shouldValidateEntitiesOnLoad() ) { getReplicantContext().getValidator().validateEntities(); } } /** * Perform a single step in sending one (or a batch) or requests to the server. */ final boolean progressAreaOfInterestRequestProcessing() { final List<AreaOfInterestRequest> requests = new ArrayList<>( ensureConnection().getCurrentAreaOfInterestRequests() ); if ( requests.isEmpty() ) { return false; } else if ( requests.get( 0 ).isInProgress() ) { return false; } else { requests.forEach( AreaOfInterestRequest::markAsInProgress ); final AreaOfInterestRequest.Type type = requests.get( 0 ).getType(); if ( AreaOfInterestRequest.Type.ADD == type ) { progressAreaOfInterestAddRequests( requests ); } else if ( AreaOfInterestRequest.Type.REMOVE == type ) { progressAreaOfInterestRemoveRequests( requests ); } else { progressAreaOfInterestUpdateRequests( requests ); } return true; } } final void progressAreaOfInterestAddRequests( @Nonnull final List<AreaOfInterestRequest> requests ) { removeUnneededAddRequests( requests ); if ( requests.isEmpty() ) { completeAreaOfInterestRequest(); } else if ( 1 == requests.size() ) { progressAreaOfInterestAddRequest( requests.get( 0 ) ); } else { progressBulkAreaOfInterestAddRequests( requests ); } } final void progressAreaOfInterestAddRequest( @Nonnull final AreaOfInterestRequest request ) { final ChannelAddress address = request.getAddress(); onSubscribeStarted( address ); final SafeProcedure onSuccess = () -> { completeAreaOfInterestRequest(); onSubscribeCompleted( address ); }; final Consumer<Throwable> onError = error -> { completeAreaOfInterestRequest(); onSubscribeFailed( address, error ); }; final String cacheKey = request.getCacheKey(); final CacheService cacheService = getReplicantContext().getCacheService(); final CacheEntry cacheEntry = null == cacheService ? null : cacheService.lookup( cacheKey ); final String eTag; final SafeProcedure onCacheValid; if ( null != cacheEntry ) { if ( Replicant.shouldCheckInvariants() ) { invariant( () -> getSchema().getChannel( request.getAddress().getChannelId() ).isCacheable(), () -> "Replicant-0072: Found cache entry for non-cacheable channel." ); } //Found locally cached data eTag = cacheEntry.getETag(); onCacheValid = () -> { // Loading cached data completeAreaOfInterestRequest(); ensureConnection().enqueueOutOfBandResponse( cacheEntry.getContent(), onSuccess ); triggerMessageScheduler(); }; } else { eTag = null; onCacheValid = null; } getTransport().requestSubscribe( request.getAddress(), request.getFilter(), cacheKey, eTag, onCacheValid, onSuccess, onError ); } final void progressBulkAreaOfInterestAddRequests( @Nonnull final List<AreaOfInterestRequest> requests ) { final List<ChannelAddress> addresses = requests.stream().map( AreaOfInterestRequest::getAddress ).collect( Collectors.toList() ); addresses.forEach( this::onSubscribeStarted ); final SafeProcedure onSuccess = () -> { completeAreaOfInterestRequest(); addresses.forEach( this::onSubscribeCompleted ); }; final Consumer<Throwable> onError = error -> { completeAreaOfInterestRequest(); addresses.forEach( a -> onSubscribeFailed( a, error ) ); }; getTransport().requestBulkSubscribe( addresses, requests.get( 0 ).getFilter(), onSuccess, onError ); } final void progressAreaOfInterestUpdateRequests( @Nonnull final List<AreaOfInterestRequest> requests ) { removeUnneededUpdateRequests( requests ); if ( requests.isEmpty() ) { completeAreaOfInterestRequest(); } else if ( requests.size() > 1 ) { progressBulkAreaOfInterestUpdateRequests( requests ); } else { progressAreaOfInterestUpdateRequest( requests.get( 0 ) ); } } final void progressAreaOfInterestUpdateRequest( @Nonnull final AreaOfInterestRequest request ) { final ChannelAddress address = request.getAddress(); onSubscriptionUpdateStarted( address ); final SafeProcedure onSuccess = () -> { completeAreaOfInterestRequest(); onSubscriptionUpdateCompleted( address ); }; final Consumer<Throwable> onError = error -> { completeAreaOfInterestRequest(); onSubscriptionUpdateFailed( address, error ); }; final Object filter = request.getFilter(); assert null != filter; getTransport().requestSubscriptionUpdate( address, filter, onSuccess, onError ); } final void progressBulkAreaOfInterestUpdateRequests( @Nonnull final List<AreaOfInterestRequest> requests ) { final List<ChannelAddress> addresses = requests.stream().map( AreaOfInterestRequest::getAddress ).collect( Collectors.toList() ); addresses.forEach( this::onSubscriptionUpdateStarted ); final SafeProcedure onSuccess = () -> { completeAreaOfInterestRequest(); addresses.forEach( this::onSubscriptionUpdateCompleted ); }; final Consumer<Throwable> onError = error -> { completeAreaOfInterestRequest(); addresses.forEach( a -> onSubscriptionUpdateFailed( a, error ) ); }; // All filters will be the same if they are grouped final Object filter = requests.get( 0 ).getFilter(); assert null != filter; getTransport().requestBulkSubscriptionUpdate( addresses, filter, onSuccess, onError ); } final void progressAreaOfInterestRemoveRequests( @Nonnull final List<AreaOfInterestRequest> requests ) { removeUnneededRemoveRequests( requests ); if ( requests.isEmpty() ) { completeAreaOfInterestRequest(); } else if ( requests.size() > 1 ) { progressBulkAreaOfInterestRemoveRequests( requests ); } else { progressAreaOfInterestRemoveRequest( requests.get( 0 ) ); } } final void progressAreaOfInterestRemoveRequest( @Nonnull final AreaOfInterestRequest request ) { final ChannelAddress address = request.getAddress(); onUnsubscribeStarted( address ); final SafeProcedure onSuccess = () -> { removeExplicitSubscriptions( Collections.singletonList( request ) ); completeAreaOfInterestRequest(); onUnsubscribeCompleted( address ); }; final Consumer<Throwable> onError = error -> { removeExplicitSubscriptions( Collections.singletonList( request ) ); completeAreaOfInterestRequest(); onUnsubscribeFailed( address, error ); }; getTransport().requestUnsubscribe( address, onSuccess, onError ); } final void progressBulkAreaOfInterestRemoveRequests( @Nonnull final List<AreaOfInterestRequest> requests ) { final List<ChannelAddress> addresses = requests.stream().map( AreaOfInterestRequest::getAddress ).collect( Collectors.toList() ); addresses.forEach( this::onUnsubscribeStarted ); final SafeProcedure onSuccess = () -> { removeExplicitSubscriptions( requests ); completeAreaOfInterestRequest(); addresses.forEach( this::onUnsubscribeCompleted ); }; final Consumer<Throwable> onError = error -> { removeExplicitSubscriptions( requests ); completeAreaOfInterestRequest(); addresses.forEach( a -> onUnsubscribeFailed( a, error ) ); }; getTransport().requestBulkUnsubscribe( addresses, onSuccess, onError ); } /** * The AreaOfInterestRequest currently being processed can be completed and * trigger scheduler to start next step. */ final void completeAreaOfInterestRequest() { ensureConnection().completeAreaOfInterestRequest(); triggerMessageScheduler(); } /** * Invoked to fire an event when disconnect has completed. */ @Action protected void onConnected() { setState( ConnectorState.CONNECTED ); if ( Replicant.areSpiesEnabled() && getReplicantContext().getSpy().willPropagateSpyEvents() ) { getReplicantContext().getSpy().reportSpyEvent( new ConnectedEvent( getSchema().getId(), getSchema().getName() ) ); } } /** * Invoked to fire an event when failed to connect. */ @Action protected void onConnectFailure( @Nonnull final Throwable error ) { setState( ConnectorState.ERROR ); if ( Replicant.areSpiesEnabled() && getReplicantContext().getSpy().willPropagateSpyEvents() ) { getReplicantContext().getSpy() .reportSpyEvent( new ConnectFailureEvent( getSchema().getId(), getSchema().getName(), error ) ); } } /** * Invoked to fire an event when disconnect has completed. */ @Action protected void onDisconnected() { setState( ConnectorState.DISCONNECTED ); if ( Replicant.areSpiesEnabled() && getReplicantContext().getSpy().willPropagateSpyEvents() ) { getReplicantContext().getSpy() .reportSpyEvent( new DisconnectedEvent( getSchema().getId(), getSchema().getName() ) ); } } /** * Invoked to fire an event when failed to connect. */ @Action protected void onDisconnectFailure( @Nonnull final Throwable error ) { setState( ConnectorState.ERROR ); if ( Replicant.areSpiesEnabled() && getReplicantContext().getSpy().willPropagateSpyEvents() ) { getReplicantContext().getSpy() .reportSpyEvent( new DisconnectFailureEvent( getSchema().getId(), getSchema().getName(), error ) ); } } /** * Invoked when a change set has been completely processed. * * @param status the status describing the results of data load. */ protected void onMessageProcessed( @Nonnull final DataLoadStatus status ) { if ( Replicant.areSpiesEnabled() && getReplicantContext().getSpy().willPropagateSpyEvents() ) { getReplicantContext().getSpy() .reportSpyEvent( new MessageProcessedEvent( getSchema().getId(), getSchema().getName(), status ) ); } } /** * Called when a data load has resulted in a failure. */ @Action protected void onMessageProcessFailure( @Nonnull final Throwable error ) { if ( Replicant.areSpiesEnabled() && getReplicantContext().getSpy().willPropagateSpyEvents() ) { getReplicantContext().getSpy() .reportSpyEvent( new MessageProcessFailureEvent( getSchema().getId(), getSchema().getName(), error ) ); } disconnectIfPossible( error ); } /** * Attempted to retrieve data from backend and failed. */ @Action protected void onMessageReadFailure( @Nonnull final Throwable error ) { if ( Replicant.areSpiesEnabled() && getReplicantContext().getSpy().willPropagateSpyEvents() ) { getReplicantContext().getSpy() .reportSpyEvent( new MessageReadFailureEvent( getSchema().getId(), getSchema().getName(), error ) ); } disconnectIfPossible( error ); } final void disconnectIfPossible( @Nonnull final Throwable cause ) { if ( !ConnectorState.isTransitionState( getState() ) ) { if ( Replicant.areSpiesEnabled() && getReplicantContext().getSpy().willPropagateSpyEvents() ) { getReplicantContext().getSpy() .reportSpyEvent( new RestartEvent( getSchema().getId(), getSchema().getName(), cause ) ); } disconnect(); } } @Action protected void onSubscribeStarted( @Nonnull final ChannelAddress address ) { updateAreaOfInterest( address, AreaOfInterest.Status.LOADING, null ); if ( Replicant.areSpiesEnabled() && getReplicantContext().getSpy().willPropagateSpyEvents() ) { getReplicantContext().getSpy() .reportSpyEvent( new SubscribeStartedEvent( getSchema().getId(), getSchema().getName(), address ) ); } } @Action protected void onSubscribeCompleted( @Nonnull final ChannelAddress address ) { updateAreaOfInterest( address, AreaOfInterest.Status.LOADED, null ); if ( Replicant.areSpiesEnabled() && getReplicantContext().getSpy().willPropagateSpyEvents() ) { getReplicantContext().getSpy() .reportSpyEvent( new SubscribeCompletedEvent( getSchema().getId(), getSchema().getName(), address ) ); } } @Action protected void onSubscribeFailed( @Nonnull final ChannelAddress address, @Nonnull final Throwable error ) { updateAreaOfInterest( address, AreaOfInterest.Status.LOAD_FAILED, error ); if ( Replicant.areSpiesEnabled() && getReplicantContext().getSpy().willPropagateSpyEvents() ) { getReplicantContext().getSpy() .reportSpyEvent( new SubscribeFailedEvent( getSchema().getId(), getSchema().getName(), address, error ) ); } } @Action protected void onUnsubscribeStarted( @Nonnull final ChannelAddress address ) { updateAreaOfInterest( address, AreaOfInterest.Status.UNLOADING, null ); if ( Replicant.areSpiesEnabled() && getReplicantContext().getSpy().willPropagateSpyEvents() ) { getReplicantContext().getSpy() .reportSpyEvent( new UnsubscribeStartedEvent( getSchema().getId(), getSchema().getName(), address ) ); } } @Action protected void onUnsubscribeCompleted( @Nonnull final ChannelAddress address ) { updateAreaOfInterest( address, AreaOfInterest.Status.UNLOADED, null ); if ( Replicant.areSpiesEnabled() && getReplicantContext().getSpy().willPropagateSpyEvents() ) { getReplicantContext().getSpy() .reportSpyEvent( new UnsubscribeCompletedEvent( getSchema().getId(), getSchema().getName(), address ) ); } } @Action protected void onUnsubscribeFailed( @Nonnull final ChannelAddress address, @Nonnull final Throwable error ) { updateAreaOfInterest( address, AreaOfInterest.Status.UNLOADED, null ); if ( Replicant.areSpiesEnabled() && getReplicantContext().getSpy().willPropagateSpyEvents() ) { getReplicantContext().getSpy() .reportSpyEvent( new UnsubscribeFailedEvent( getSchema().getId(), getSchema().getName(), address, error ) ); } } @Action protected void onSubscriptionUpdateStarted( @Nonnull final ChannelAddress address ) { updateAreaOfInterest( address, AreaOfInterest.Status.UPDATING, null ); if ( Replicant.areSpiesEnabled() && getReplicantContext().getSpy().willPropagateSpyEvents() ) { getReplicantContext().getSpy() .reportSpyEvent( new SubscriptionUpdateStartedEvent( getSchema().getId(), getSchema().getName(), address ) ); } } @Action protected void onSubscriptionUpdateCompleted( @Nonnull final ChannelAddress address ) { updateAreaOfInterest( address, AreaOfInterest.Status.UPDATED, null ); if ( Replicant.areSpiesEnabled() && getReplicantContext().getSpy().willPropagateSpyEvents() ) { getReplicantContext().getSpy() .reportSpyEvent( new SubscriptionUpdateCompletedEvent( getSchema().getId(), getSchema().getName(), address ) ); } } @Action protected void onSubscriptionUpdateFailed( @Nonnull final ChannelAddress address, @Nonnull final Throwable error ) { updateAreaOfInterest( address, AreaOfInterest.Status.UPDATE_FAILED, error ); if ( Replicant.areSpiesEnabled() && getReplicantContext().getSpy().willPropagateSpyEvents() ) { getReplicantContext() .getSpy() .reportSpyEvent( new SubscriptionUpdateFailedEvent( getSchema().getId(), getSchema().getName(), address, error ) ); } } private void updateAreaOfInterest( @Nonnull final ChannelAddress address, @Nonnull final AreaOfInterest.Status status, @Nullable final Throwable error ) { final AreaOfInterest areaOfInterest = getReplicantContext().findAreaOfInterestByAddress( address ); if ( null != areaOfInterest ) { areaOfInterest.updateAreaOfInterest( status, error ); } } @Nonnull final ReplicantRuntime getReplicantRuntime() { return getReplicantContext().getRuntime(); } @ContextRef @Nonnull protected abstract ArezContext context(); /** * {@inheritDoc} */ @Override public String toString() { return Replicant.areNamesEnabled() ? "Connector[" + getSchema().getName() + "]" : super.toString(); } @TestOnly @Nullable final Disposable getSchedulerLock() { return _schedulerLock; } }
package org.scribe.utils; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import org.junit.Test; import static org.junit.Assert.*; public class StreamUtilsTest { @Test public void shouldCorrectlyDecodeAStream() { String value = "expected"; InputStream is = new ByteArrayInputStream(value.getBytes()); String decoded = StreamUtils.getStreamContents(is); assertEquals("expected", decoded); } @Test(expected = IllegalArgumentException.class) public void shouldFailForNullParameter() { InputStream is = null; StreamUtils.getStreamContents(is); fail("Must throw exception before getting here"); } @Test(expected = IllegalStateException.class) public void shouldFailWithBrokenStream() { // This object simulates problems with input stream. final InputStream is = new InputStream() { @Override public int read() throws IOException { throw new IOException(); } }; StreamUtils.getStreamContents(is); fail("Must throw exception before getting here"); } }
package replicant; import arez.Disposable; import arez.annotations.ArezComponent; import arez.annotations.Autorun; import arez.annotations.Observable; import java.util.HashSet; import java.util.Objects; import java.util.Set; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.inject.Singleton; import org.realityforge.anodoc.VisibleForTesting; import replicant.spy.SubscriptionOrphanedEvent; import static org.realityforge.braincheck.Guards.*; @Singleton @ArezComponent public abstract class Converger { /** * Reference to the context to which this service belongs. */ @Nullable private final ReplicantContext _context; static Converger create( @Nullable final ReplicantContext context ) { return new Arez_Converger( context ); } Converger( @Nullable final ReplicantContext context ) { if ( Replicant.shouldCheckInvariants() ) { apiInvariant( () -> Replicant.areZonesEnabled() || null == context, () -> "Replicant-0124: Converger passed a context but Replicant.areZonesEnabled() is false" ); } _context = Replicant.areZonesEnabled() ? Objects.requireNonNull( context ) : null; } /** * Set action that is run prior to converging. * This is typically used to ensure the subscriptions are uptodate prior to attempting to convergeStep. */ @Observable public abstract void setPreConvergeAction( @Nullable Runnable preConvergeAction ); @Nullable public abstract Runnable getPreConvergeAction(); /** * Set action that is runs after all the subscriptions have converged. */ @Observable public abstract void setConvergeCompleteAction( @Nullable Runnable convergeCompleteAction ); @Nullable public abstract Runnable getConvergeCompleteAction(); @Autorun void converge() { preConverge(); removeOrphanSubscriptions(); if ( RuntimeState.CONNECTED == getReplicantRuntime().getState() ) { convergeStep(); } } void preConverge() { final Runnable preConvergeAction = getPreConvergeAction(); if ( null != preConvergeAction ) { preConvergeAction.run(); } } void convergeComplete() { final Runnable convergeCompleteAction = getConvergeCompleteAction(); if ( null != convergeCompleteAction ) { convergeCompleteAction.run(); } } private void convergeStep() { AreaOfInterest groupTemplate = null; AreaOfInterestAction groupAction = null; for ( final AreaOfInterest areaOfInterest : getReplicantContext().getAreasOfInterest() ) { final ConvergeAction convergeAction = convergeAreaOfInterest( areaOfInterest, groupTemplate, groupAction, true ); switch ( convergeAction ) { case TERMINATE: return; case SUBMITTED_ADD: groupAction = AreaOfInterestAction.ADD; groupTemplate = areaOfInterest; break; case SUBMITTED_UPDATE: groupAction = AreaOfInterestAction.UPDATE; groupTemplate = areaOfInterest; break; case IN_PROGRESS: if ( null == groupTemplate ) { // First thing in the subscription queue is in flight, so terminate return; } break; case NO_ACTION: break; } } if ( null != groupTemplate ) { return; } convergeComplete(); } @VisibleForTesting final ConvergeAction convergeAreaOfInterest( @Nonnull final AreaOfInterest areaOfInterest, @Nullable final AreaOfInterest groupTemplate, @Nullable final AreaOfInterestAction groupAction, final boolean canGroup ) { if ( Replicant.shouldCheckInvariants() ) { invariant( () -> !Disposable.isDisposed( areaOfInterest ), () -> "Replicant-0020: Invoked convergeAreaOfInterest() with disposed AreaOfInterest." ); } final ChannelAddress address = areaOfInterest.getAddress(); final Connector connector = getReplicantRuntime().getConnector( address.getSystem() ); // service can be disconnected if it is not a required service and will converge later when it connects if ( ConnectorState.CONNECTED == connector.getState() ) { final Subscription subscription = getReplicantContext().findSubscription( address ); final boolean subscribed = null != subscription; final Object filter = areaOfInterest.getChannel().getFilter(); final int addIndex = connector.indexOfPendingAreaOfInterestAction( AreaOfInterestAction.ADD, address, filter ); final int removeIndex = connector.indexOfPendingAreaOfInterestAction( AreaOfInterestAction.REMOVE, address, null ); final int updateIndex = connector.indexOfPendingAreaOfInterestAction( AreaOfInterestAction.UPDATE, address, filter ); if ( ( !subscribed && addIndex < 0 ) || removeIndex > addIndex ) { if ( null != groupTemplate && !canGroup ) { return ConvergeAction.TERMINATE; } if ( null == groupTemplate || canGroup( groupTemplate, groupAction, areaOfInterest, AreaOfInterestAction.ADD ) ) { connector.requestSubscribe( address, filter ); return ConvergeAction.SUBMITTED_ADD; } else { return ConvergeAction.NO_ACTION; } } else if ( addIndex >= 0 ) { //Must have add in pipeline so pause until it completed return ConvergeAction.IN_PROGRESS; } else { // Must be subscribed... if ( updateIndex >= 0 ) { //Update in progress so wait till it completes return ConvergeAction.IN_PROGRESS; } final Object existing = subscription.getChannel().getFilter(); final String newFilter = FilterUtil.filterToString( filter ); final String existingFilter = FilterUtil.filterToString( existing ); if ( !Objects.equals( newFilter, existingFilter ) ) { if ( null != groupTemplate && !canGroup ) { return ConvergeAction.TERMINATE; } if ( null == groupTemplate || canGroup( groupTemplate, groupAction, areaOfInterest, AreaOfInterestAction.UPDATE ) ) { connector.requestSubscriptionUpdate( address, filter ); return ConvergeAction.SUBMITTED_UPDATE; } else { return ConvergeAction.NO_ACTION; } } } } return ConvergeAction.NO_ACTION; } boolean canGroup( @Nonnull final AreaOfInterest groupTemplate, @Nullable final AreaOfInterestAction groupAction, @Nonnull final AreaOfInterest areaOfInterest, @Nullable final AreaOfInterestAction action ) { if ( null != groupAction && null != action && !groupAction.equals( action ) ) { return false; } else { final boolean sameChannel = groupTemplate.getAddress().getChannelType().equals( areaOfInterest.getAddress().getChannelType() ); return sameChannel && ( AreaOfInterestAction.REMOVE == action || FilterUtil.filtersEqual( groupTemplate.getChannel().getFilter(), areaOfInterest.getChannel().getFilter() ) ); } } void removeOrphanSubscriptions() { final HashSet<ChannelAddress> expected = new HashSet<>(); getReplicantContext().getAreasOfInterest().forEach( aoi -> expected.add( aoi.getAddress() ) ); for ( final Subscription subscription : getReplicantContext().getTypeSubscriptions() ) { removeSubscriptionIfOrphan( expected, subscription ); } for ( final Subscription subscription : getReplicantContext().getInstanceSubscriptions() ) { removeSubscriptionIfOrphan( expected, subscription ); } } void removeSubscriptionIfOrphan( @Nonnull final Set<ChannelAddress> expected, @Nonnull final Subscription subscription ) { final ChannelAddress address = subscription.getChannel().getAddress(); if ( !expected.contains( address ) && subscription.isExplicitSubscription() ) { removeOrphanSubscription( address ); } } void removeOrphanSubscription( @Nonnull final ChannelAddress address ) { final ReplicantContext replicantContext = getReplicantContext(); final Connector connector = getReplicantRuntime().getConnector( address.getSystem() ); if ( ConnectorState.CONNECTED == connector.getState() && !connector.isAreaOfInterestActionPending( AreaOfInterestAction.REMOVE, address, null ) ) { if ( Replicant.areSpiesEnabled() && replicantContext.getSpy().willPropagateSpyEvents() ) { final Subscription subscription = replicantContext.findSubscription( address ); assert null != subscription; replicantContext.getSpy().reportSpyEvent( new SubscriptionOrphanedEvent( subscription ) ); } connector.requestUnsubscribe( address ); } } @Nonnull private ReplicantRuntime getReplicantRuntime() { return getReplicantContext().getRuntime(); } @Nonnull final ReplicantContext getReplicantContext() { return Replicant.areZonesEnabled() ? Objects.requireNonNull( _context ) : Replicant.context(); } }
package org.zkoss.gridster; import org.zkoss.bind.annotation.AfterCompose; import org.zkoss.bind.annotation.Command; import org.zkoss.bind.annotation.ContextParam; import org.zkoss.bind.annotation.ContextType; import org.zkoss.zk.ui.Component; import org.zkoss.zk.ui.event.Event; import org.zkoss.zk.ui.event.EventListener; import org.zkoss.zk.ui.event.Events; import org.zkoss.zk.ui.select.Selectors; import org.zkoss.zk.ui.select.annotation.Wire; import org.zkoss.zul.Button; import org.zkoss.zul.Window; import java.util.Random; /** * View-Model for the demo of {@link Gridster} in action. * * @author Sean Connolly */ public class DemoViewModel { private static final String[] CAMPFIRE = new String[]{"#588C73", "#F2E394", "#F2AE72", "#D96459", "#8C4646"}; private final Random random = new Random(); @Wire("#win") private Window base; @Wire private Gridster dynamicGridster; @AfterCompose public void afterCompose(@ContextParam(ContextType.VIEW) Component view) { Selectors.wireComponents(view, this, false); PrintEventListener printer = new PrintEventListener(); dynamicGridster.addEventListener(GridsterEvents.ON_DRAG_START, printer); dynamicGridster.addEventListener(GridsterEvents.ON_DRAG, printer); dynamicGridster.addEventListener(GridsterEvents.ON_DRAG_STOP, printer); } @Command public void addSmallItem() { addItem(1, 1); } @Command public void addLargeItem() { addItem(randomSize(), randomSize()); } private int randomSize() { return random.nextInt(3) + 1; } private void addItem(int sizeX, int sizeY) { GridItem item = new GridItem(); item.setSizeX(sizeX); item.setSizeY(sizeY); item.setRow(randomPosition()); item.setCol(randomPosition()); item.setStyle("background-color: " + randomColor()); Button closeButton = new Button("Remove"); closeButton.addEventListener(Events.ON_CLICK, new CloseItemEventListener(item)); item.appendChild(closeButton); dynamicGridster.appendChild(item); } private int randomPosition() { return random.nextInt(5) + 1; } private String randomColor() { return CAMPFIRE[random.nextInt(5)]; } @Command public void reinitialize() { dynamicGridster.invalidate(); } private static final class CloseItemEventListener implements EventListener<Event> { private final GridItem item; private CloseItemEventListener(GridItem item) { this.item = item; } @Override public void onEvent(Event event) throws Exception { item.detach(); } } private static final class PrintEventListener implements EventListener<Event> { @Override public void onEvent(Event event) throws Exception { System.out.println(event.getName()); } } }
package org.jdesktop.swingx; import java.awt.BorderLayout; import java.awt.Color; import java.awt.ComponentOrientation; import java.awt.Font; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.BoxLayout; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import org.jdesktop.swingx.util.PropertyChangeReport; /** * @author Jeanette Winzenburg */ public class JXTitledPanelTest extends InteractiveTestCase { public JXTitledPanelTest() { super("JXTitledPane interactive test"); } /** * Issue ??: notifications missing on all "title"XX properties. * */ public void testTitlePropertiesNotify() { String title = "starting title"; final JXTitledPanel panel = new JXTitledPanel(title); PropertyChangeReport report = new PropertyChangeReport(); panel.addPropertyChangeListener(report); Font deriveFont = panel.getTitleFont().deriveFont(27f); panel.setTitleFont(deriveFont); assertTrue("panel must notify on titleFont change", report.hasEvents("titleFont")); panel.setTitleForeground(Color.black); assertTrue("panel must notify on titleForeground change", report.hasEvents("titleForeground")); panel.setTitleDarkBackground(Color.black); assertTrue("panel must notify on titleDarkBackground change", report.hasEvents("titleDarkBackground")); panel.setTitleLightBackground(Color.black); assertTrue("panel must notify on titleLightBackground change", report.hasEvents("titleLightBackground")); } /** * SwingX Issue #9: missing notification on title change. * happens if a generic property change listener (== one who * wants to get all property changes) is registered. */ public void testTitleNotify() { String title = "starting title"; final JXTitledPanel panel = new JXTitledPanel(title); PropertyChangeReport report = new PropertyChangeReport(); panel.addPropertyChangeListener(report); panel.setTitle("new title"); assertTrue("panel must have fired propertyChange", report.hasEvents()); } /** * SwingX Issue #9: missing notification on title change. * Notification is correct, if a named propertyChangeListener is * registered. */ public void testTitleNotifyNamed() { String title = "starting title"; final JXTitledPanel panel = new JXTitledPanel(title); PropertyChangeReport report = new PropertyChangeReport(); panel.addPropertyChangeListener( "title", report); panel.setTitle("new title"); assertTrue("panel must have fired propertyChange", report.hasEvents()); } /** * incorrect propertyChangeEvent on setTitle(null). * */ public void testTitleNotifyPropertyValue() { String title = "starting title"; final JXTitledPanel panel = new JXTitledPanel(title); PropertyChangeReport report = new PropertyChangeReport(); panel.addPropertyChangeListener( "title", report); panel.setTitle(null); assertTrue("panel must have fired propertyChange", report.hasEvents()); assertEquals("new property value must be equal to getTitle", panel.getTitle(), report.getLastNewValue("title")); } public void interactiveRToL() { String title = "starting title"; JXTitledPanel titledPane = new JXTitledPanel(title); titledPane.addLeftDecoration(new JLabel("Leading")); titledPane.addRightDecoration(new JLabel("Trailing")); // panel.getContentContainer().setLayout(new BoxLayout(panel.getContentContainer(), BoxLayout.PAGE_AXIS)); Icon icon = new ImageIcon(getClass().getResource("resources/images/wellBottom.gif")); final JLabel label = new JLabel(title); label.setIcon(icon); final JPanel panel = new JPanel(new BorderLayout()); panel.add(titledPane, BorderLayout.NORTH); panel.add(label); JXFrame frame = wrapInFrame(panel, "toggle Title"); Action toggleCO = new AbstractAction("toggle orientation") { public void actionPerformed(ActionEvent e) { ComponentOrientation current = panel.getComponentOrientation(); if (current == ComponentOrientation.LEFT_TO_RIGHT) { panel.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); // panel.revalidate(); // panel.repaint(); label.setText("RightToLeft"); } else { panel.applyComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT); // panel.revalidate(); // panel.repaint(); label.setText("LeftToRight"); } } }; addAction(frame, toggleCO); frame.pack(); frame.setVisible(true); } public void interactiveIconAndHtmlTest() { String title = "<html><u>starting title </u></html>"; final JXTitledPanel panel = new JXTitledPanel(title); Icon icon = new ImageIcon(getClass().getResource("resources/images/wellBottom.gif")); panel.addLeftDecoration(new JLabel(icon)); panel.getContentContainer().setLayout(new BoxLayout(panel.getContentContainer(), BoxLayout.Y_AXIS)); panel.getContentContainer().add(new JLabel(title)); JXFrame frame = wrapInFrame(panel, "toggle Title"); frame.setVisible(true); } /** * trying to set divers TitledPanel properties interactively. * can't set titlefont. */ public void interactiveTitleTest() { String title = "starting title"; final JXTitledPanel panel = new JXTitledPanel(title); panel.getContentContainer().setLayout(new BoxLayout(panel.getContentContainer(), BoxLayout.Y_AXIS)); Action toggleLight = new AbstractAction("toggle lightBackground") { public void actionPerformed(ActionEvent e) { Color oldFont = panel.getTitleLightBackground(); panel.setTitleLightBackground(oldFont.darker()); } }; panel.getContentContainer().add(new JButton(toggleLight)); panel.getContentContainer().setLayout(new BoxLayout(panel.getContentContainer(), BoxLayout.Y_AXIS)); Action toggleDark = new AbstractAction("toggle darkbackground") { public void actionPerformed(ActionEvent e) { Color oldFont = panel.getTitleDarkBackground(); panel.setTitleDarkBackground(oldFont.darker()); } }; panel.getContentContainer().add(new JButton(toggleDark)); Action toggleForeground = new AbstractAction("toggle Foreground") { public void actionPerformed(ActionEvent e) { Color oldColor = panel.getTitleForeground(); panel.setTitleForeground(oldColor.darker()); } }; panel.getContentContainer().add(new JButton(toggleForeground)); Action toggleFont = new AbstractAction("toggle Font") { public void actionPerformed(ActionEvent e) { Font oldFont = panel.getTitleFont(); System.out.println("oldfont size: " + oldFont.getSize()); panel.setTitleFont(oldFont.deriveFont(oldFont.getSize()*2.f)); } }; panel.getContentContainer().add(new JButton(toggleFont)); Action toggleTitle = new AbstractAction("toggle title") { int count = 0; public void actionPerformed(ActionEvent e) { panel.setTitle(" * " + count++ + " title"); } }; panel.getContentContainer().add(new JButton(toggleTitle)); JFrame frame = wrapInFrame(panel, "toggle Title"); frame.setVisible(true); } public static void main(String args[]) { JXTitledPanelTest test = new JXTitledPanelTest(); try { test.runInteractiveTests(); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } }
package org.jdesktop.swingx; import java.awt.Color; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.lang.reflect.InvocationTargetException; import java.util.Vector; import java.util.logging.Logger; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.BorderFactory; import javax.swing.DefaultCellEditor; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JTree; import javax.swing.SwingUtilities; import javax.swing.Timer; import javax.swing.UIManager; import javax.swing.border.Border; import javax.swing.event.TableModelEvent; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeCellRenderer; import javax.swing.tree.TreePath; import org.jdesktop.swingx.action.AbstractActionExt; import org.jdesktop.swingx.decorator.Highlighter; import org.jdesktop.swingx.decorator.HighlighterFactory; import org.jdesktop.swingx.hyperlink.AbstractHyperlinkAction; import org.jdesktop.swingx.renderer.CellContext; import org.jdesktop.swingx.renderer.CheckBoxProvider; import org.jdesktop.swingx.renderer.ComponentProvider; import org.jdesktop.swingx.renderer.DefaultTableRenderer; import org.jdesktop.swingx.renderer.DefaultTreeRenderer; import org.jdesktop.swingx.renderer.HyperlinkProvider; import org.jdesktop.swingx.renderer.LabelProvider; import org.jdesktop.swingx.renderer.StringValue; import org.jdesktop.swingx.renderer.StringValues; import org.jdesktop.swingx.renderer.WrappingIconPanel; import org.jdesktop.swingx.renderer.WrappingProvider; import org.jdesktop.swingx.renderer.RendererVisualCheck.TextAreaProvider; import org.jdesktop.swingx.test.ActionMapTreeTableModel; import org.jdesktop.swingx.test.ComponentTreeTableModel; import org.jdesktop.swingx.test.TreeTableUtils; import org.jdesktop.swingx.treetable.AbstractMutableTreeTableNode; import org.jdesktop.swingx.treetable.DefaultMutableTreeTableNode; import org.jdesktop.swingx.treetable.DefaultTreeTableModel; import org.jdesktop.swingx.treetable.FileSystemModel; import org.jdesktop.swingx.treetable.MutableTreeTableNode; import org.jdesktop.swingx.treetable.TreeTableModel; import org.jdesktop.swingx.treetable.TreeTableNode; import org.jdesktop.test.AncientSwingTeam; import org.jdesktop.test.TableModelReport; /** * Test to exposed known issues of <code>JXTreeTable</code>. <p> * * Ideally, there would be at least one failing test method per open * issue in the issue tracker. Plus additional failing test methods for * not fully specified or not yet decided upon features/behaviour.<p> * * Once the issues are fixed and the corresponding methods are passing, they * should be moved over to the XXTest. * * @author Jeanette Winzenburg */ public class JXTreeTableIssues extends InteractiveTestCase { private static final Logger LOG = Logger.getLogger(JXTreeTableIssues.class .getName()); public static void main(String[] args) { setSystemLF(true); JXTreeTableIssues test = new JXTreeTableIssues(); try { // test.runInteractiveTests(); // test.runInteractiveTests(".*ColumnSelection.*"); // test.runInteractiveTests(".*Text.*"); // test.runInteractiveTests(".*TreeExpand.*"); test.runInteractiveTests("interactive.*EditWith.*"); // test.runInteractiveTests("interactive.*CustomColor.*"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } /** * Issue #??: combo editor is closed immediately after starting * * Happens if row is not selected at the moment of starting, okay if selected. */ public void interactiveEditWithComboBox() { // quick for having an editable treeTableModel (non hierarchical column) TreeTableModel model = new ComponentTreeTableModel(new JXFrame()) { @Override public boolean isCellEditable(Object node, int column) { return super.isCellEditable(node, column) || column == 1; } }; JXTreeTable table = new JXTreeTable(model); JComboBox box = new JComboBox(new Object[] {"something", "else", "whatever"}); box.setEditable(true); table.getColumn(1).setCellEditor(new DefaultCellEditor(box)); showWithScrollingInFrame(table, "combo editor in column 1"); } /** * Issue #875-swingx: cell selection incorrect in hierarchical column. * */ public void interactiveColumnSelection() { JXTreeTable treeTable = new JXTreeTable(new FileSystemModel()); treeTable.setColumnSelectionAllowed(true); JXTable table = new JXTable(new AncientSwingTeam()); table.setColumnSelectionAllowed(true); JXFrame frame = wrapWithScrollingInFrame(treeTable, table, "columnSelection in treetable"); show(frame); } /** * Custom renderer colors of Swingx DefaultTreeRenderer not respected. * (same in J/X/Tree). * * A bit surprising - probably due to the half-hearted support (backward * compatibility) of per-provider colors: they are set by the glueing * renderer to the provider's default visuals. Which is useless if the * provider is a wrapping provider - the wrappee's default visuals are unchanged. * * PENDING JW: think about complete removal. Client code should move over * completely to highlighter/renderer separation anyway. * * */ public void interactiveXRendererCustomColor() { JXTreeTable treeTable = new JXTreeTable(new FileSystemModel()); treeTable.addHighlighter(HighlighterFactory.createSimpleStriping()); DefaultTreeRenderer swingx = new DefaultTreeRenderer(); // in a treetable this has no effect: treetable.applyRenderer // internally resets them to the same colors as tree itself // (configured by the table's highlighters swingx.setBackground(Color.YELLOW); treeTable.setTreeCellRenderer(swingx); JTree tree = new JXTree(treeTable.getTreeTableModel()); DefaultTreeRenderer other = new DefaultTreeRenderer(); other.setBackground(Color.YELLOW); // other.setBackgroundSelectionColor(Color.RED); tree.setCellRenderer(other); JXFrame frame = wrapWithScrollingInFrame(treeTable, tree, "swingx renderers - highlight complete cell"); frame.setVisible(true); } /** * Custom renderer colors of core DefaultTreeCellRenderer not respected. * This is intentional: treeTable's highlighters must rule, so the * renderer colors are used to force the treecellrenderer to use the * correct values. */ public void interactiveCoreRendererCustomColor() { JXTreeTable treeTable = new JXTreeTable(new FileSystemModel()); treeTable.addHighlighter(HighlighterFactory.createSimpleStriping()); DefaultTreeCellRenderer legacy = createBackgroundTreeRenderer(); // in a treetable this has no effect: treetable.applyRenderer // internally resets them to the same colors as tree itself // (configured by the table's highlighters legacy.setBackgroundNonSelectionColor(Color.YELLOW); legacy.setBackgroundSelectionColor(Color.RED); treeTable.setTreeCellRenderer(legacy); JTree tree = new JXTree(treeTable.getTreeTableModel()); DefaultTreeCellRenderer other = createBackgroundTreeRenderer(); other.setBackgroundNonSelectionColor(Color.YELLOW); other.setBackgroundSelectionColor(Color.RED); tree.setCellRenderer(other); JXFrame frame = wrapWithScrollingInFrame(treeTable, tree, "legacy renderers - highlight complete cell"); frame.setVisible(true); } private DefaultTreeCellRenderer createBackgroundTreeRenderer() { DefaultTreeCellRenderer legacy = new DefaultTreeCellRenderer() { @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { Component comp = super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); if (sel) { comp.setBackground(getBackgroundSelectionColor()); } else { comp.setBackground(getBackgroundNonSelectionColor()); } return comp; } }; return legacy; } /** * Issue #493-swingx: incorrect table events fired. * Issue #592-swingx: (no structureChanged table events) is a special * case of the former. * * Here: add support to prevent a structureChanged even when setting * the root. May be required if the columns are stable and the * model lazily loaded. Quick hack would be to add a clientProperty? * * @throws InvocationTargetException * @throws InterruptedException */ public void testTableEventOnSetRootNoStructureChange() throws InterruptedException, InvocationTargetException { TreeTableModel model = createCustomTreeTableModelFromDefault(); final JXTreeTable table = new JXTreeTable(model); table.setRootVisible(true); table.expandAll(); final TableModelReport report = new TableModelReport(); table.getModel().addTableModelListener(report); ((DefaultTreeTableModel) model).setRoot(new DefaultMutableTreeTableNode("other")); SwingUtilities.invokeAndWait(new Runnable() { public void run() { assertEquals("tableModel must have fired", 1, report.getEventCount()); assertTrue("event type must be dataChanged " + TableModelReport.printEvent(report.getLastEvent()), report.isDataChanged(report.getLastEvent())); } }); } /** * Issue #576-swingx: sluggish scrolling (?). * Here - use default model */ public void interactiveScrollAlternateHighlightDefaultModel() { final JXTable table = new JXTable(0, 6); DefaultMutableTreeTableNode root = new DefaultMutableTreeTableNode("root"); for (int i = 0; i < 5000; i++) { root.insert(new DefaultMutableTreeTableNode(i), i); } final JXTreeTable treeTable = new JXTreeTable(new DefaultTreeTableModel(root)); treeTable.expandAll(); table.setModel(treeTable.getModel()); final Highlighter hl = HighlighterFactory.createAlternateStriping(UIManager.getColor("Panel.background"), Color.WHITE); treeTable.setHighlighters(hl); table.setHighlighters(hl); final JXFrame frame = wrapWithScrollingInFrame(treeTable, table, "sluggish scrolling"); Action toggleHighlighter = new AbstractActionExt("toggle highlighter") { public void actionPerformed(ActionEvent e) { if (treeTable.getHighlighters().length == 0) { treeTable.addHighlighter(hl); table.addHighlighter(hl); } else { treeTable.removeHighlighter(hl); table.removeHighlighter(hl); } } }; Action scroll = new AbstractActionExt("start scroll") { public void actionPerformed(ActionEvent e) { for (int i = 0; i < table.getRowCount(); i++) { table.scrollRowToVisible(i); treeTable.scrollRowToVisible(i); } } }; addAction(frame, toggleHighlighter); addAction(frame, scroll); frame.setVisible(true); } /** * Issue #576-swingx: sluggish scrolling (?) * * Here: use FileSystemModel */ public void interactiveScrollAlternateHighlight() { final JXTable table = new JXTable(0, 6); final JXTreeTable treeTable = new JXTreeTable(new FileSystemModel()); final Highlighter hl = HighlighterFactory.createAlternateStriping(UIManager.getColor("Panel.background"), Color.WHITE); treeTable.setHighlighters(hl); table.setHighlighters(hl); final JXFrame frame = wrapWithScrollingInFrame(treeTable, table, "sluggish scrolling"); Action expand = new AbstractActionExt("start expand") { public void actionPerformed(ActionEvent e) { for (int i = 0; i < 5000; i++) { treeTable.expandRow(i); } table.setModel(treeTable.getModel()); } }; Action toggleHighlighter = new AbstractActionExt("toggle highlighter") { public void actionPerformed(ActionEvent e) { if (treeTable.getHighlighters().length == 0) { treeTable.addHighlighter(hl); table.addHighlighter(hl); } else { treeTable.removeHighlighter(hl); table.removeHighlighter(hl); } } }; Action scroll = new AbstractActionExt("start scroll") { public void actionPerformed(ActionEvent e) { for (int i = 0; i < table.getRowCount(); i++) { table.scrollRowToVisible(i); treeTable.scrollRowToVisible(i); } } }; addAction(frame, expand); addAction(frame, toggleHighlighter); addAction(frame, scroll); frame.setVisible(true); } /** * Issue #493-swingx: JXTreeTable.TreeTableModelAdapter: Inconsistency * firing update. * * Test update events after updating table. * * from tiberiu@dev.java.net * * @throws InvocationTargetException * @throws InterruptedException */ public void testTableEventUpdateOnTreeTableSetValueForRoot() throws InterruptedException, InvocationTargetException { TreeTableModel model = createCustomTreeTableModelFromDefault(); final JXTreeTable table = new JXTreeTable(model); table.setRootVisible(true); table.expandAll(); final int row = 0; // sanity assertEquals("JTree", table.getValueAt(row, 0).toString()); assertTrue("root must be editable", table.getModel().isCellEditable(0, 0)); final TableModelReport report = new TableModelReport(); table.getModel().addTableModelListener(report); // doesn't fire or isn't detectable? // Problem was: model was not-editable. table.setValueAt("games", row, 0); SwingUtilities.invokeAndWait(new Runnable() { public void run() { assertEquals("tableModel must have fired", 1, report.getEventCount()); assertEquals("the event type must be update " + TableModelReport.printEvent(report.getLastEvent()) , 1, report.getUpdateEventCount()); TableModelEvent event = report.getLastUpdateEvent(); assertEquals("the updated row ", row, event.getFirstRow()); } }); } /** * Issue #493-swingx: JXTreeTable.TreeTableModelAdapter: Inconsistency * firing update on a recursive delete on a parent node. * * By recursive delete on a parent node it is understood that first we * remove its children and then the parent node. After each child removed * we are making an update over the parent. During this update the problem * occurs: the index row for the parent is -1 and hence it is made an update * over the row -1 (the header) and as it can be seen the preffered widths * of column header are not respected anymore and are restored to the default * preferences (all equal). * * from tiberiu@dev.java.net */ public void interactiveTreeTableModelAdapterDeleteUpdate() { final DefaultTreeTableModel customTreeTableModel = (DefaultTreeTableModel) createCustomTreeTableModelFromDefault(); final JXTreeTable table = new JXTreeTable(customTreeTableModel); table.setRootVisible(true); table.expandAll(); table.getColumn("A").setPreferredWidth(100); table.getColumn("A").setMinWidth(100); table.getColumn("A").setMaxWidth(100); JXTree xtree = new JXTree(customTreeTableModel); xtree.setRootVisible(true); xtree.expandAll(); final JXFrame frame = wrapWithScrollingInFrame(table, xtree, "JXTreeTable.TreeTableModelAdapter: Inconsistency firing update on recursive delete"); final MutableTreeTableNode deletedNode = (MutableTreeTableNode) table.getPathForRow(6).getLastPathComponent(); MutableTreeTableNode child1 = (MutableTreeTableNode) table.getPathForRow(6+1).getLastPathComponent(); MutableTreeTableNode child2 = (MutableTreeTableNode) table.getPathForRow(6+2).getLastPathComponent(); MutableTreeTableNode child3 = (MutableTreeTableNode) table.getPathForRow(6+3).getLastPathComponent(); MutableTreeTableNode child4 = (MutableTreeTableNode) table.getPathForRow(6+4).getLastPathComponent(); final MutableTreeTableNode[] children = {child1, child2, child3, child4 }; final String[] values = {"v1", "v2", "v3", "v4"}; final ActionListener l = new ActionListener() { int count = 0; public void actionPerformed(ActionEvent e) { if (count > values.length) return; if (count == values.length) { customTreeTableModel.removeNodeFromParent(deletedNode); count++; } else { // one in each run removeChild(customTreeTableModel, deletedNode, children, values); count++; // all in one // for (int i = 0; i < values.length; i++) { // removeChild(customTreeTableModel, deletedNode, children, values); // count++; } } /** * @param customTreeTableModel * @param deletedNode * @param children * @param values */ private void removeChild(final DefaultTreeTableModel customTreeTableModel, final MutableTreeTableNode deletedNode, final MutableTreeTableNode[] children, final String[] values) { customTreeTableModel.removeNodeFromParent(children[count]); customTreeTableModel.setValueAt(values[count], deletedNode, 0); } }; Action changeValue = new AbstractAction("delete node sports recursively") { Timer timer; public void actionPerformed(ActionEvent e) { if (timer == null) { timer = new Timer(10, l); timer.start(); } else { timer.stop(); setEnabled(false); } } }; addAction(frame, changeValue); frame.setVisible(true); } /** * Issue #493-swingx: JXTreeTable.TreeTableModelAdapter: Inconsistency * firing update. Use the second child of root - first is accidentally okay. * * from tiberiu@dev.java.net * * TODO DefaultMutableTreeTableNodes do not allow value changes, so this * test will never work */ public void interactiveTreeTableModelAdapterUpdate() { TreeTableModel customTreeTableModel = createCustomTreeTableModelFromDefault(); final JXTreeTable table = new JXTreeTable(customTreeTableModel); table.setRootVisible(true); table.expandAll(); table.setLargeModel(true); JXTree xtree = new JXTree(customTreeTableModel); xtree.setRootVisible(true); xtree.expandAll(); final JXFrame frame = wrapWithScrollingInFrame(table, xtree, "JXTreeTable.TreeTableModelAdapter: Inconsistency firing update"); Action changeValue = new AbstractAction("change sports to games") { public void actionPerformed(ActionEvent e) { String newValue = "games"; table.getTreeTableModel().setValueAt(newValue, table.getPathForRow(6).getLastPathComponent(), 0); } }; addAction(frame, changeValue); Action changeRoot = new AbstractAction("change root") { public void actionPerformed(ActionEvent e) { DefaultMutableTreeTableNode newRoot = new DefaultMutableTreeTableNode("new Root"); ((DefaultTreeTableModel) table.getTreeTableModel()).setRoot(newRoot); } }; addAction(frame, changeRoot); frame.pack(); frame.setVisible(true); } /** * Issue #493-swingx: JXTreeTable.TreeTableModelAdapter: Inconsistency * firing delete. * * from tiberiu@dev.java.net */ public void interactiveTreeTableModelAdapterDelete() { final TreeTableModel customTreeTableModel = createCustomTreeTableModelFromDefault(); final JXTreeTable table = new JXTreeTable(customTreeTableModel); table.setRootVisible(true); table.expandAll(); JXTree xtree = new JXTree(customTreeTableModel); xtree.setRootVisible(true); xtree.expandAll(); final JXFrame frame = wrapWithScrollingInFrame(table, xtree, "JXTreeTable.TreeTableModelAdapter: Inconsistency firing update"); Action changeValue = new AbstractAction("delete first child of sports") { public void actionPerformed(ActionEvent e) { MutableTreeTableNode firstChild = (MutableTreeTableNode) table.getPathForRow(6 +1).getLastPathComponent(); ((DefaultTreeTableModel) customTreeTableModel).removeNodeFromParent(firstChild); } }; addAction(frame, changeValue); frame.setVisible(true); } /** * Issue #493-swingx: JXTreeTable.TreeTableModelAdapter: Inconsistency * firing delete. * * from tiberiu@dev.java.net */ public void interactiveTreeTableModelAdapterMutateSelected() { final TreeTableModel customTreeTableModel = createCustomTreeTableModelFromDefault(); final JXTreeTable table = new JXTreeTable(customTreeTableModel); table.setRootVisible(true); table.expandAll(); JXTree xtree = new JXTree(customTreeTableModel); xtree.setRootVisible(true); xtree.expandAll(); final JXFrame frame = wrapWithScrollingInFrame(table, xtree, "JXTreeTable.TreeTableModelAdapter: Inconsistency firing delete expanded folder"); Action changeValue = new AbstractAction("delete selected node") { public void actionPerformed(ActionEvent e) { int row = table.getSelectedRow(); if (row < 0) return; MutableTreeTableNode firstChild = (MutableTreeTableNode) table.getPathForRow(row).getLastPathComponent(); ((DefaultTreeTableModel) customTreeTableModel).removeNodeFromParent(firstChild); } }; addAction(frame, changeValue); Action changeValue1 = new AbstractAction("insert as first child of selected node") { public void actionPerformed(ActionEvent e) { int row = table.getSelectedRow(); if (row < 0) return; MutableTreeTableNode firstChild = (MutableTreeTableNode) table.getPathForRow(row).getLastPathComponent(); MutableTreeTableNode newChild = new DefaultMutableTreeTableNode("inserted"); ((DefaultTreeTableModel) customTreeTableModel) .insertNodeInto(newChild, firstChild, 0); } }; addAction(frame, changeValue1); frame.pack(); frame.setVisible(true); } /** * Issue #493-swingx: JXTreeTable.TreeTableModelAdapter: Inconsistency * firing delete. * * from tiberiu@dev.java.net */ public void interactiveTreeTableModelAdapterMutateSelectedDiscontinous() { final TreeTableModel customTreeTableModel = createCustomTreeTableModelFromDefault(); final JXTreeTable table = new JXTreeTable(customTreeTableModel); table.setRootVisible(true); table.expandAll(); JXTree xtree = new JXTree(customTreeTableModel); xtree.setRootVisible(true); xtree.expandAll(); final JXFrame frame = wrapWithScrollingInFrame(table, xtree, "JXTreeTable.TreeTableModelAdapter: Inconsistency firing delete expanded folder"); Action changeValue = new AbstractAction("delete selected node + sibling") { public void actionPerformed(ActionEvent e) { int row = table.getSelectedRow(); if (row < 0) return; MutableTreeTableNode firstChild = (MutableTreeTableNode) table.getPathForRow(row).getLastPathComponent(); MutableTreeTableNode parent = (MutableTreeTableNode) firstChild.getParent(); MutableTreeTableNode secondNextSibling = null; int firstIndex = parent.getIndex(firstChild); if (firstIndex + 2 < parent.getChildCount()) { secondNextSibling = (MutableTreeTableNode) parent.getChildAt(firstIndex + 2); } if (secondNextSibling != null) { ((DefaultTreeTableModel) customTreeTableModel).removeNodeFromParent(secondNextSibling); } ((DefaultTreeTableModel) customTreeTableModel).removeNodeFromParent(firstChild); } }; addAction(frame, changeValue); Action changeValue1 = new AbstractAction("insert as first child of selected node") { public void actionPerformed(ActionEvent e) { int row = table.getSelectedRow(); if (row < 0) return; MutableTreeTableNode firstChild = (MutableTreeTableNode) table.getPathForRow(row).getLastPathComponent(); MutableTreeTableNode newChild = new DefaultMutableTreeTableNode("inserted"); ((DefaultTreeTableModel) customTreeTableModel) .insertNodeInto(newChild, firstChild, 0); } }; addAction(frame, changeValue1); frame.pack(); frame.setVisible(true); } /** * Creates and returns a custom model from JXTree default model. The model * is of type DefaultTreeModel, allowing for easy insert/remove. * * @return */ private TreeTableModel createCustomTreeTableModelFromDefault() { JXTree tree = new JXTree(); DefaultTreeModel treeModel = (DefaultTreeModel) tree.getModel(); TreeTableModel customTreeTableModel = TreeTableUtils .convertDefaultTreeModel(treeModel); return customTreeTableModel; } /** * A TreeTableModel inheriting from DefaultTreeModel (to ease * insert/delete). */ public static class CustomTreeTableModel extends DefaultTreeTableModel { /** * @param root */ public CustomTreeTableModel(TreeTableNode root) { super(root); } @Override public int getColumnCount() { return 1; } @Override public String getColumnName(int column) { return "User Object"; } @Override public Object getValueAt(Object node, int column) { return ((DefaultMutableTreeNode) node).getUserObject(); } @Override public boolean isCellEditable(Object node, int column) { return true; } @Override public void setValueAt(Object value, Object node, int column) { ((MutableTreeTableNode) node).setUserObject(value); modelSupport.firePathChanged(new TreePath(getPathToRoot((TreeTableNode) node))); } } /** * Issue #??-swingx: hyperlink in JXTreeTable hierarchical column not * active. * */ public void interactiveTreeTableLinkRendererSimpleText() { AbstractHyperlinkAction simpleAction = new AbstractHyperlinkAction<Object>(null) { public void actionPerformed(ActionEvent e) { LOG.info("hit: " + getTarget()); } }; JXTreeTable tree = new JXTreeTable(new FileSystemModel()); HyperlinkProvider provider = new HyperlinkProvider(simpleAction); tree.getColumn(2).setCellRenderer(new DefaultTableRenderer(provider)); tree.setTreeCellRenderer(new DefaultTreeRenderer( //provider)); new WrappingProvider(provider))); // tree.setCellRenderer(new LinkRenderer(simpleAction)); tree.setHighlighters(HighlighterFactory.createSimpleStriping()); JFrame frame = wrapWithScrollingInFrame(tree, "table and simple links"); frame.setVisible(true); } /** * Issue ??-swingx: hyperlink/rollover in hierarchical column. * */ public void testTreeRendererInitialRollover() { JXTreeTable tree = new JXTreeTable(new FileSystemModel()); assertEquals(tree.isRolloverEnabled(), ((JXTree) tree.getCellRenderer(0, 0)).isRolloverEnabled()); } /** * Issue ??-swingx: hyperlink/rollover in hierarchical column. * */ public void testTreeRendererModifiedRollover() { JXTreeTable tree = new JXTreeTable(new FileSystemModel()); tree.setRolloverEnabled(!tree.isRolloverEnabled()); assertEquals(tree.isRolloverEnabled(), ((JXTree) tree.getCellRenderer(0, 0)).isRolloverEnabled()); } /** * example how to use a custom component as * renderer in tree column of TreeTable. * */ public void interactiveTreeTableCustomRenderer() { JXTreeTable tree = new JXTreeTable(new FileSystemModel()); StringValue sv = new StringValue( ){ public String getString(Object value) { return "..." + StringValues.TO_STRING.getString(value); } }; ComponentProvider provider = new CheckBoxProvider(sv); // /** // * custom tooltip: show row. Note: the context is that // * of the rendering tree. No way to get at table state? // */ // @Override // protected void configureState(CellContext context) { // super.configureState(context); // rendererComponent.setToolTipText("Row: " + context.getRow()); tree.setTreeCellRenderer(new DefaultTreeRenderer(provider)); tree.setHighlighters(HighlighterFactory.createSimpleStriping()); JFrame frame = wrapWithScrollingInFrame(tree, "treetable and custom renderer"); frame.setVisible(true); } /** * Quick example to use a TextArea in the hierarchical column * of a treeTable. Not really working .. the wrap is not reliable?. * */ public void interactiveTextAreaTreeTable() { TreeTableModel model = createTreeTableModelWithLongNode(); JXTreeTable treeTable = new JXTreeTable(model); treeTable.setVisibleRowCount(5); treeTable.setRowHeight(50); treeTable.getColumnExt(0).setPreferredWidth(200); TreeCellRenderer renderer = new DefaultTreeRenderer( new WrappingProvider(new TextAreaProvider())); treeTable.setTreeCellRenderer(renderer); showWithScrollingInFrame(treeTable, "TreeTable with text wrapping"); } /** * @return */ private TreeTableModel createTreeTableModelWithLongNode() { MutableTreeTableNode root = createLongNode("some really, maybe really really long text - " + "wrappit .... where needed "); root.insert(createLongNode("another really, maybe really really long text - " + "with nothing but junk. wrappit .... where needed"), 0); root.insert(createLongNode("another really, maybe really really long text - " + "with nothing but junk. wrappit .... where needed"), 0); MutableTreeTableNode node = createLongNode("some really, maybe really really long text - " + "wrappit .... where needed "); node.insert(createLongNode("another really, maybe really really long text - " + "with nothing but junk. wrappit .... where needed"), 0); root.insert(node, 0); root.insert(createLongNode("another really, maybe really really long text - " + "with nothing but junk. wrappit .... where needed"), 0); Vector<String> ids = new Vector<String>(); ids.add("long text"); ids.add("dummy"); return new DefaultTreeTableModel(root, ids); } /** * @param string * @return */ private MutableTreeTableNode createLongNode(final String string) { AbstractMutableTreeTableNode node = new AbstractMutableTreeTableNode() { Object rnd = Math.random(); public int getColumnCount() { return 2; } public Object getValueAt(int column) { if (column == 0) { return string; } return rnd; } }; node.setUserObject(string); return node; } /** * Experiments to try and understand clipping issues: occasionally, the text * in the tree column is clipped even if there is enough space available. * * To visualize the rendering component's size we use a WrappingIconProvider * which sets a red border. * * Calling packxx might pose a problem: for non-large models the node size * is cached. In this case, packing before replacing the renderer will lead * to incorrect sizes which are hard to invalidate (no way except faking a * structural tree event? temporaryly set large model and back, plus repaint * works). * */ public void interactiveTreeTableClipIssueWrappingProvider() { final JXTreeTable treeTable = new JXTreeTable(createActionTreeModel()); treeTable.setHorizontalScrollEnabled(true); treeTable.setColumnControlVisible(true); // BEWARE: do not pack before setting the renderer treeTable.packColumn(0, -1); StringValue format = new StringValue() { public String getString(Object value) { if (value instanceof Action) { return ((Action) value).getValue(Action.NAME) + "xx"; } return StringValues.TO_STRING.getString(value); } }; ComponentProvider tableProvider = new LabelProvider(format); WrappingProvider wrappingProvider = new WrappingProvider(tableProvider) { Border redBorder = BorderFactory.createLineBorder(Color.RED); @Override public WrappingIconPanel getRendererComponent(CellContext context) { super.getRendererComponent(context); rendererComponent.setBorder(redBorder); return rendererComponent; } }; DefaultTreeRenderer treeCellRenderer = new DefaultTreeRenderer( wrappingProvider); treeTable.setTreeCellRenderer(treeCellRenderer); treeTable.setHighlighters(HighlighterFactory.createSimpleStriping()); // at this point a pack is okay, caching will get the correct values // treeTable.packColumn(0, -1); final JXTree tree = new JXTree(treeTable.getTreeTableModel()); tree.setCellRenderer(treeCellRenderer); tree.setScrollsOnExpand(false); JXFrame frame = wrapWithScrollingInFrame(treeTable, tree, "treetable and tree with wrapping provider"); // revalidate doesn't help Action revalidate = new AbstractActionExt("revalidate") { public void actionPerformed(ActionEvent e) { treeTable.revalidate(); tree.revalidate(); treeTable.repaint(); } }; // hack around incorrect cached node sizes Action large = new AbstractActionExt("large-circle") { public void actionPerformed(ActionEvent e) { treeTable.setLargeModel(true); treeTable.setLargeModel(false); treeTable.repaint(); } }; addAction(frame, revalidate); addAction(frame, large); show(frame); } /** * Experiments to try and understand clipping issues: occasionally, the text * in the tree column is clipped even if there is enough space available. * * Here we don't change any renderers. */ public void interactiveTreeTableClipIssueDefaultRenderer() { final JXTreeTable treeTable = new JXTreeTable(createActionTreeModel()); treeTable.setHorizontalScrollEnabled(true); treeTable.setRootVisible(true); treeTable.collapseAll(); treeTable.packColumn(0, -1); final JTree tree = new JTree(treeTable.getTreeTableModel()); tree.collapseRow(0); JXFrame frame = wrapWithScrollingInFrame(treeTable, tree, "JXTreeTable vs. JTree: default renderer"); Action revalidate = new AbstractActionExt("revalidate") { public void actionPerformed(ActionEvent e) { treeTable.revalidate(); tree.revalidate(); } }; addAction(frame, revalidate); frame.setVisible(true); } /** * Experiments to try and understand clipping issues: occasionally, the text * in the tree column is clipped even if there is enough space available. * Here we set a custom (unchanged default) treeCellRenderer which * removes ellipses altogether. * */ public void interactiveTreeTableClipIssueCustomDefaultRenderer() { TreeCellRenderer renderer = new DefaultTreeCellRenderer() { @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { return super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); } }; final JXTreeTable treeTable = new JXTreeTable(createActionTreeModel()); treeTable.setTreeCellRenderer(renderer); treeTable.setHorizontalScrollEnabled(true); treeTable.setRootVisible(true); treeTable.collapseAll(); treeTable.packColumn(0, -1); final JTree tree = new JTree(treeTable.getTreeTableModel()); tree.setCellRenderer(renderer); tree.collapseRow(0); JXFrame frame = wrapWithScrollingInFrame(treeTable, tree, "JXTreeTable vs. JTree: custom default renderer"); Action revalidate = new AbstractActionExt("revalidate") { public void actionPerformed(ActionEvent e) { treeTable.revalidate(); tree.revalidate(); } }; addAction(frame, revalidate); frame.setVisible(true); } /** * Dirty example how to configure a custom renderer to use * treeTableModel.getValueAt(...) for showing. * */ public void interactiveTreeTableGetValueRenderer() { JXTreeTable tree = new JXTreeTable(new ComponentTreeTableModel(new JXFrame())); ComponentProvider provider = new CheckBoxProvider(StringValues.TO_STRING) { @Override protected String getValueAsString(CellContext context) { // this is dirty because the design idea was to keep the renderer // unaware of the context type TreeTableModel model = (TreeTableModel) ((JXTree) context.getComponent()).getModel(); // beware: currently works only if the node is not a DefaultMutableTreeNode // otherwise the WrappingProvider tries to be smart and replaces the node // by the userObject before passing on to the wrappee! Object nodeValue = model.getValueAt(context.getValue(), 0); return formatter.getString(nodeValue); } }; tree.setTreeCellRenderer(new DefaultTreeRenderer(provider)); tree.expandAll(); tree.setHighlighters(HighlighterFactory.createSimpleStriping()); JFrame frame = wrapWithScrollingInFrame(tree, "treeTable and getValueAt renderer"); frame.setVisible(true); } /** * Issue #399-swingx: editing terminated by selecting editing row. * */ public void testSelectionKeepsEditingWithExpandsTrue() { JXTreeTable treeTable = new JXTreeTable(new FileSystemModel()) { @Override public boolean isCellEditable(int row, int column) { return true; } }; // sanity: default value of expandsSelectedPath assertTrue(treeTable.getExpandsSelectedPaths()); boolean canEdit = treeTable.editCellAt(1, 2); // sanity: editing started assertTrue(canEdit); // sanity: nothing selected assertTrue(treeTable.getSelectionModel().isSelectionEmpty()); int editingRow = treeTable.getEditingRow(); treeTable.setRowSelectionInterval(editingRow, editingRow); assertEquals("after selection treeTable editing state must be unchanged", canEdit, treeTable.isEditing()); } /** * Issue #212-jdnc: reuse editor, install only once. * */ public void testReuseEditor() { //TODO rework this test, since we no longer use TreeTableModel.class // JXTreeTable treeTable = new JXTreeTable(treeTableModel); // CellEditor editor = treeTable.getDefaultEditor(TreeTableModel.class); // assertTrue(editor instanceof TreeTableCellEditor); // treeTable.setTreeTableModel(simpleTreeTableModel); // assertSame("hierarchical editor must be unchanged", editor, // treeTable.getDefaultEditor(TreeTableModel.class)); fail("#212-jdnc - must be revisited after treeTableModel overhaul"); } /** * sanity: toggling select/unselect via mouse the lead is * always painted, doing unselect via model (clear/remove path) * seems to clear the lead? * */ public void testBasicTreeLeadSelection() { JXTree tree = new JXTree(); TreePath path = tree.getPathForRow(0); tree.setSelectionPath(path); assertEquals(0, tree.getSelectionModel().getLeadSelectionRow()); assertEquals(path, tree.getLeadSelectionPath()); tree.removeSelectionPath(path); assertNotNull(tree.getLeadSelectionPath()); assertEquals(0, tree.getSelectionModel().getLeadSelectionRow()); } /** * Issue #341-swingx: missing synch of lead. * test lead after setting selection via table. * * PENDING: this passes locally, fails on server */ public void testLeadSelectionFromTable() { JXTreeTable treeTable = prepareTreeTable(false); assertEquals(-1, treeTable.getSelectionModel().getLeadSelectionIndex()); assertEquals(-1, treeTable.getTreeSelectionModel().getLeadSelectionRow()); treeTable.setRowSelectionInterval(0, 0); assertEquals(treeTable.getSelectionModel().getLeadSelectionIndex(), treeTable.getTreeSelectionModel().getLeadSelectionRow()); fail("lead selection synch passes locally, fails on server"); } /** * Issue #341-swingx: missing synch of lead. * test lead after setting selection via treeSelection. * PENDING: this passes locally, fails on server * */ public void testLeadSelectionFromTree() { JXTreeTable treeTable = prepareTreeTable(false); assertEquals(-1, treeTable.getSelectionModel().getLeadSelectionIndex()); assertEquals(-1, treeTable.getTreeSelectionModel().getLeadSelectionRow()); treeTable.getTreeSelectionModel().setSelectionPath(treeTable.getPathForRow(0)); assertEquals(treeTable.getSelectionModel().getLeadSelectionIndex(), treeTable.getTreeSelectionModel().getLeadSelectionRow()); assertEquals(0, treeTable.getTreeSelectionModel().getLeadSelectionRow()); fail("lead selection synch passes locally, fails on server"); } /** * Issue #341-swingx: missing synch of lead. * test lead after remove selection via tree. * */ public void testLeadAfterRemoveSelectionFromTree() { JXTreeTable treeTable = prepareTreeTable(true); treeTable.getTreeSelectionModel().removeSelectionPath( treeTable.getTreeSelectionModel().getLeadSelectionPath()); assertEquals(treeTable.getSelectionModel().getLeadSelectionIndex(), treeTable.getTreeSelectionModel().getLeadSelectionRow()); } /** * Issue #341-swingx: missing synch of lead. * test lead after clear selection via table. * */ public void testLeadAfterClearSelectionFromTable() { JXTreeTable treeTable = prepareTreeTable(true); treeTable.clearSelection(); assertEquals(treeTable.getSelectionModel().getLeadSelectionIndex(), treeTable.getTreeSelectionModel().getLeadSelectionRow()); } /** * Issue #341-swingx: missing synch of lead. * test lead after clear selection via table. * */ public void testLeadAfterClearSelectionFromTree() { JXTreeTable treeTable = prepareTreeTable(true); treeTable.getTreeSelectionModel().clearSelection(); assertEquals(treeTable.getSelectionModel().getLeadSelectionIndex(), treeTable.getTreeSelectionModel().getLeadSelectionRow()); } /** * creates and configures a treetable for usage in selection tests. * * @param selectFirstRow boolean to indicate if the first row should * be selected. * @return */ protected JXTreeTable prepareTreeTable(boolean selectFirstRow) { JXTreeTable treeTable = new JXTreeTable(new ComponentTreeTableModel(new JXFrame())); treeTable.setRootVisible(true); // sanity: assert that we have at least two rows to change selection assertTrue(treeTable.getRowCount() > 1); if (selectFirstRow) { treeTable.setRowSelectionInterval(0, 0); } return treeTable; } public void testDummy() { } /** * @return */ private TreeTableModel createActionTreeModel() { JXTable table = new JXTable(10, 10); table.setHorizontalScrollEnabled(true); return new ActionMapTreeTableModel(table); } }
package com.rehivetech.beeeon.gui.activity; import android.animation.Animator; import android.animation.AnimatorInflater; import android.animation.AnimatorListenerAdapter; import android.animation.ArgbEvaluator; import android.animation.ObjectAnimator; import android.content.SharedPreferences; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.ActionBar; import android.support.v7.widget.AppCompatCheckBox; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.CompoundButton; import android.widget.TextView; import android.widget.Toast; import com.rehivetech.beeeon.R; import com.rehivetech.beeeon.controller.Controller; import com.rehivetech.beeeon.gui.fragment.ModuleGraphFragment; import com.rehivetech.beeeon.gui.view.Slider; import com.rehivetech.beeeon.household.device.Module; import com.rehivetech.beeeon.household.device.ModuleLog; import com.rehivetech.beeeon.household.device.values.BaseValue; import com.rehivetech.beeeon.household.device.values.EnumValue; import com.rehivetech.beeeon.util.ChartHelper; import com.rehivetech.beeeon.util.UnitsHelper; import com.rehivetech.beeeon.util.Utils; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * @author martin on 18.8.2015. */ public class ModuleGraphActivity extends BaseApplicationActivity { private final static String TAG = ModuleGraphActivity.class.getSimpleName(); public static final String EXTRA_GATE_ID = "gate_id"; public static final String EXTRA_DEVICE_ID = "device_id"; public static final String EXTRA_MODULE_ID = "module_id"; private static final String OUT_STATE_CHECK_BOX_MIN = "check_box_min"; private static final String OUT_STATE_CHECK_BOX_MAX = "check_box_max"; private static final String OUT_STET_CHECK_BOX_AVG = "check_box_avg"; private static final String OUT_STATE_SLIDER_PROGRESS = "slider_progress"; private boolean mRequestRedrawActiveFragmentCalled = false; private String mGateId; private String mDeviceId; private String mModuleId; private TextView mMinValue; private TextView mMaxValue; private TextView mActValue; private TextView mMinValueLabel; private TextView mMaxValuelabel; private TabLayout mTabLayout; private ViewPager mViewPager; private Slider mSlider; private AppCompatCheckBox mCheckBoxMin; private AppCompatCheckBox mCheckBoxAvg; private AppCompatCheckBox mCheckBoxMax; private FloatingActionButton mFab; private Button mShowLegendButton; private String mModuleUnit; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_module_graph); Bundle bundle = getIntent().getExtras(); if (bundle != null) { mGateId = bundle.getString(EXTRA_GATE_ID); mDeviceId = bundle.getString(EXTRA_DEVICE_ID); mModuleId = bundle.getString(EXTRA_MODULE_ID); } if (mGateId == null || mModuleId == null) { Toast.makeText(this, R.string.module_detail_toast_not_specified_gate_or_module, Toast.LENGTH_LONG).show(); finish(); return; } Controller controller = Controller.getInstance(this); Module module = controller.getDevicesModel().getDevice(mGateId, mDeviceId).getModuleById(mModuleId); SharedPreferences prefs = controller.getUserSettings(); UnitsHelper unitsHelper = new UnitsHelper(prefs, this); mModuleUnit = unitsHelper.getStringUnit(module.getValue()); Toolbar toolbar = (Toolbar) findViewById(R.id.beeeon_toolbar); toolbar.setTitle(module.getName(this)); setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setDisplayShowTitleEnabled(true); } mMinValue = (TextView) findViewById(R.id.module_graph_min_value); mMaxValue = (TextView) findViewById(R.id.module_graph_max_value); mActValue = (TextView) findViewById(R.id.module_graph_act_value); mMinValueLabel = (TextView) findViewById(R.id.module_graph_min_label); mMaxValuelabel = (TextView) findViewById(R.id.module_graph_max_label); mTabLayout = (TabLayout) findViewById(R.id.module_graph_tab_layoout); mViewPager = (ViewPager) findViewById(R.id.module_graph_view_pager); mCheckBoxMin = (AppCompatCheckBox) findViewById(R.id.module_graph_checkbox_min); mCheckBoxAvg = (AppCompatCheckBox) findViewById(R.id.module_graph_checkbox_avg); mCheckBoxMax = (AppCompatCheckBox) findViewById(R.id.module_graph_checkbox_max); mCheckBoxAvg.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (!isChecked) { if (!mCheckBoxMin.isChecked() && !mCheckBoxMax.isChecked()) { mCheckBoxAvg.setChecked(true); } } } }); mCheckBoxMin.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (!isChecked) { if (!mCheckBoxAvg.isChecked() && !mCheckBoxMax.isChecked()) { mCheckBoxMin.setChecked(true); } } } }); mCheckBoxMax.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (!isChecked) { if (!mCheckBoxMin.isChecked() && !mCheckBoxAvg.isChecked()) { mCheckBoxMax.setChecked(true); } } } }); mSlider = (Slider) findViewById(R.id.module_graph_slider); mSlider.setProgressChangeLister(new Slider.OnProgressChangeLister() { @Override public void onProgressChanged(int progress) { if (progress == 0) { mCheckBoxMin.setChecked(false); mCheckBoxAvg.setChecked(true); mCheckBoxMax.setChecked(false); mCheckBoxMin.setEnabled(false); mCheckBoxAvg.setEnabled(false); mCheckBoxMax.setEnabled(false); } else { mCheckBoxMin.setEnabled(true); mCheckBoxAvg.setEnabled(true); mCheckBoxMax.setEnabled(true); } } }); TextView textMin = ((TextView) findViewById(R.id.module_graph_text_min)); textMin.setTextColor(Utils.getGraphColor(this, 1)); textMin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mCheckBoxMin.isEnabled()) { mCheckBoxMin.setChecked(!mCheckBoxMin.isChecked()); } } }); TextView textAvg = ((TextView) findViewById(R.id.module_graph_text_avg)); textAvg.setTextColor(Utils.getGraphColor(this, 0)); textAvg.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mCheckBoxAvg.isEnabled()) { mCheckBoxAvg.setChecked(!mCheckBoxAvg.isChecked()); } } }); TextView textMax = ((TextView) findViewById(R.id.module_graph_text_max)); textMax.setTextColor(Utils.getGraphColor(this, 2)); textMax.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mCheckBoxMax.isEnabled()) { mCheckBoxMax.setChecked(!mCheckBoxMax.isChecked()); } } }); mFab = (FloatingActionButton) findViewById(R.id.module_graph_fab); Button buttonDone = (Button) findViewById(R.id.module_graph_button_done); mShowLegendButton = (Button) findViewById(R.id.module_graph_show_legend_btn); setupViewPager(); Map<ModuleLog.DataInterval, String> intervals = getIntervalString(ModuleLog.DataInterval.values()); mSlider.setValues(new ArrayList<>(intervals.values())); if (module.getValue() instanceof EnumValue) { mFab.setVisibility(View.GONE); } else { mSlider.setProgress(2); // default dataInterval 5 minutes } final View graphSettingsBackground = findViewById(R.id.module_graph_settings_background); final View graphSettings = findViewById(R.id.module_graph_graph_settings); graphSettings.setVisibility(View.GONE); final Animation animDown = AnimationUtils.loadAnimation(this, R.anim.graph_settings_anim_down); final Animation animUp = AnimationUtils.loadAnimation(this, R.anim.graph_settings_anim_up); final ObjectAnimator backgroundAnimUp = (ObjectAnimator) AnimatorInflater.loadAnimator(this, R.animator.graph_settings_background_animator_up); backgroundAnimUp.setTarget(graphSettingsBackground); backgroundAnimUp.setEvaluator(new ArgbEvaluator()); backgroundAnimUp.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationStart(Animator animation) { super.onAnimationStart(animation); graphSettingsBackground.setVisibility(View.VISIBLE); } }); final ObjectAnimator backgroundAnimDownDone = (ObjectAnimator) AnimatorInflater.loadAnimator(this, R.animator.graph_settings_background_animator_down); backgroundAnimDownDone.setTarget(graphSettingsBackground); backgroundAnimDownDone.setEvaluator(new ArgbEvaluator()); final ObjectAnimator backgroundAnimDownCancel = (ObjectAnimator) AnimatorInflater.loadAnimator(this, R.animator.graph_settings_background_animator_down); backgroundAnimDownCancel.setTarget(graphSettingsBackground); backgroundAnimDownCancel.setEvaluator(new ArgbEvaluator()); final FloatingActionButton.OnVisibilityChangedListener onVisibilityChangedListener = new FloatingActionButton.OnVisibilityChangedListener() { @Override public void onShown(FloatingActionButton fab) { super.onShown(fab); redrawActiveFragment(); } @Override public void onHidden(FloatingActionButton fab) { super.onHidden(fab); graphSettings.setVisibility(View.VISIBLE); graphSettings.startAnimation(animUp); backgroundAnimUp.start(); } }; backgroundAnimDownDone.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); graphSettingsBackground.setVisibility(View.GONE); mFab.show(onVisibilityChangedListener); } }); backgroundAnimDownCancel.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationStart(Animator animation) { super.onAnimationStart(animation); graphSettingsBackground.setClickable(false); } @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); graphSettingsBackground.setVisibility(View.GONE); graphSettingsBackground.setClickable(true); mFab.show(); } }); mFab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mFab.hide(onVisibilityChangedListener); graphSettingsBackground.setVisibility(View.VISIBLE); } }); buttonDone.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { backgroundAnimDownDone.start(); graphSettings.startAnimation(animDown); graphSettings.setVisibility(View.GONE); } }); graphSettingsBackground.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { backgroundAnimDownCancel.start(); graphSettings.startAnimation(animDown); graphSettings.setVisibility(View.GONE); } }); if (savedInstanceState != null) { mCheckBoxMin.setChecked(savedInstanceState.getBoolean(OUT_STATE_CHECK_BOX_MIN)); mCheckBoxAvg.setChecked(savedInstanceState.getBoolean(OUT_STET_CHECK_BOX_AVG)); mCheckBoxMax.setChecked(savedInstanceState.getBoolean(OUT_STATE_CHECK_BOX_MAX)); mSlider.setProgress(savedInstanceState.getInt(OUT_STATE_SLIDER_PROGRESS)); } else { mCheckBoxAvg.setChecked(true); } updateActValue(); } @Override public void onResume() { super.onResume(); if (!mRequestRedrawActiveFragmentCalled) { mRequestRedrawActiveFragmentCalled = true; mViewPager.post(new Runnable() { @Override public void run() { redrawActiveFragment(); } }); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: callbackTaskManager.cancelAndRemoveAll(); finish(); break; } return false; } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putBoolean(OUT_STATE_CHECK_BOX_MIN, mCheckBoxMin.isChecked()); outState.putBoolean(OUT_STET_CHECK_BOX_AVG, mCheckBoxAvg.isChecked()); outState.putBoolean(OUT_STATE_CHECK_BOX_MAX, mCheckBoxMax.isChecked()); outState.putInt(OUT_STATE_SLIDER_PROGRESS, mSlider.getProgress()); } private void setupViewPager() { GraphPagerAdapter adapter = new GraphPagerAdapter(getSupportFragmentManager()); for (int dataRange : ChartHelper.ALL_RANGES) { ModuleGraphFragment fragment = ModuleGraphFragment.newInstance(mGateId, mDeviceId, mModuleId, dataRange); adapter.addFragment(fragment, getString(ChartHelper.getIntervalString(dataRange))); } mViewPager.setAdapter(adapter); mTabLayout.setupWithViewPager(mViewPager); mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { if (!mRequestRedrawActiveFragmentCalled) { mRequestRedrawActiveFragmentCalled = true; } callbackTaskManager.cancelAndRemoveAll(); redrawActiveFragment(); } @Override public void onPageScrollStateChanged(int state) { } }); } private void setupGraphSettings(int fragmentIndex) { switch (fragmentIndex) { case 0: mSlider.setMaxValue(4); break; case 1: mSlider.setMaxValue(5); break; case 2: mSlider.setMaxValue(6); break; case 3: mSlider.setMaxValue(7); break; } } private void updateActValue() { BaseValue value = Controller.getInstance(this).getDevicesModel().getDevice(mGateId, mDeviceId).getModuleById(mModuleId).getValue(); if (value instanceof EnumValue) { mActValue.setText(((EnumValue) value).getStateStringResource()); mMinValue.setVisibility(View.GONE); mMinValueLabel.setVisibility(View.GONE); mMaxValue.setVisibility(View.GONE); mMaxValuelabel.setVisibility(View.GONE); } else { mActValue.setText(String.format("%.2f %s", value.getDoubleValue(), mModuleUnit)); mShowLegendButton.setVisibility(View.GONE); } } private Map<ModuleLog.DataInterval, String> getIntervalString(ModuleLog.DataInterval[] intervals) { Map<ModuleLog.DataInterval, String> intervalStringMap = new LinkedHashMap<>(); for (ModuleLog.DataInterval interval : intervals) { switch (interval) { case RAW: intervalStringMap.put(interval, getString(R.string.data_interval_raw)); break; case MINUTE: intervalStringMap.put(interval, getString(R.string.data_interval_minute)); break; case FIVE_MINUTES: intervalStringMap.put(interval, getString(R.string.data_interval_five_minutes)); break; case TEN_MINUTES: intervalStringMap.put(interval, getString(R.string.data_interval_ten_minutes)); break; case HALF_HOUR: intervalStringMap.put(interval, getString(R.string.data_interval_half_hour)); break; case HOUR: intervalStringMap.put(interval, getString(R.string.data_interval_hour)); break; case DAY: intervalStringMap.put(interval, getString(R.string.data_interval_day)); break; case WEEK: intervalStringMap.put(interval, getString(R.string.data_interval_week)); break; case MONTH: intervalStringMap.put(interval, getString(R.string.data_interval_month)); break; } } return intervalStringMap; } private ModuleLog.DataInterval getIntervalBySliderProgress() { switch (mSlider.getProgress()) { case 1: return ModuleLog.DataInterval.MINUTE; case 2: return ModuleLog.DataInterval.FIVE_MINUTES; case 3: return ModuleLog.DataInterval.TEN_MINUTES; case 4: return ModuleLog.DataInterval.HALF_HOUR; case 5: return ModuleLog.DataInterval.HOUR; case 6: return ModuleLog.DataInterval.DAY; case 7: return ModuleLog.DataInterval.WEEK; case 8: return ModuleLog.DataInterval.MONTH; } return ModuleLog.DataInterval.RAW; } private void redrawActiveFragment() { ModuleGraphFragment currentFragment = (ModuleGraphFragment) ((GraphPagerAdapter) mViewPager.getAdapter()).getActiveFragment(mViewPager, mViewPager.getCurrentItem()); currentFragment.onChartSettingChanged(mCheckBoxMin.isChecked(), mCheckBoxAvg.isChecked(), mCheckBoxMax.isChecked(), getIntervalBySliderProgress()); setupGraphSettings(mViewPager.getCurrentItem()); } public void setMinValue(String minValue) { if (minValue.length() == 0) { mMinValueLabel.setVisibility(View.INVISIBLE); mMinValue.setText(""); } else { mMinValueLabel.setVisibility(View.VISIBLE); mMinValue.setText(String.format("%s %s", minValue, mModuleUnit)); } } public void setMaxValue(String maxValue) { if (maxValue.length() == 0) { mMaxValuelabel.setVisibility(View.INVISIBLE); mMaxValue.setText(""); } else { mMaxValuelabel.setVisibility(View.VISIBLE); mMaxValue.setText(String.format("%s %s", maxValue, mModuleUnit)); } } public void setShowLegendButtonOnClickListener(View.OnClickListener onClickListener) { mShowLegendButton.setOnClickListener(onClickListener); } public void setRequestRedrawActiveFragmentCalled(boolean requestRedrawActiveFragmentCalled) { mRequestRedrawActiveFragmentCalled = requestRedrawActiveFragmentCalled; } private static class GraphPagerAdapter extends FragmentPagerAdapter { private final List<Fragment> mFragments = new ArrayList<>(); private final List<String> mFragmentTitles = new ArrayList<>(); private final FragmentManager mFragmentManager; public GraphPagerAdapter(FragmentManager fm) { super(fm); mFragmentManager = fm; } @Override public Fragment getItem(int position) { return mFragments.get(position); } @Override public CharSequence getPageTitle(int position) { return mFragmentTitles.get(position); } @Override public int getCount() { return mFragments.size(); } public void addFragment(Fragment fragment, String title) { mFragments.add(fragment); mFragmentTitles.add(title); } public Fragment getActiveFragment(ViewPager container, int position) { String name = makeFragmentName(container.getId(), position); return mFragmentManager.findFragmentByTag(name); } private static String makeFragmentName(int viewId, int index) { return "android:switcher:" + viewId + ":" + index; } } public interface ChartSettingListener { void onChartSettingChanged(boolean drawMin, boolean drawAvg, boolean drawMax, ModuleLog.DataInterval dataGranularity); } }
package com.ibm.bi.dml.parser; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import com.ibm.bi.dml.hops.Hops; import com.ibm.bi.dml.lops.Lops; import com.ibm.bi.dml.parser.Expression.DataType; import com.ibm.bi.dml.parser.Expression.FormatType; import com.ibm.bi.dml.runtime.instructions.CPInstructions.FunctionCallCPInstruction; import com.ibm.bi.dml.utils.HopsException; import com.ibm.bi.dml.utils.LanguageException; public class StatementBlock extends LiveVariableAnalysis{ protected DMLProgram _dmlProg; protected ArrayList<Statement> _statements; ArrayList<Hops> _hops = null; ArrayList<Lops> _lops = null; HashMap<String,ConstIdentifier> _constVarsIn; HashMap<String,ConstIdentifier> _constVarsOut; // this stores the function call instruction private FunctionCallCPInstruction _functionCallInst; public StatementBlock(){ _dmlProg = null; _statements = new ArrayList<Statement>(); _read = new VariableSet(); _updated = new VariableSet(); _gen = new VariableSet(); _kill = new VariableSet(); _warnSet = new VariableSet(); _initialized = true; _constVarsIn = new HashMap<String,ConstIdentifier>(); _constVarsOut = new HashMap<String,ConstIdentifier>(); _functionCallInst = null; } public void setFunctionCallInst(FunctionCallCPInstruction fci){ _functionCallInst = fci; } public FunctionCallCPInstruction getFunctionCallInst(){ return _functionCallInst; } public void setDMLProg(DMLProgram dmlProg){ _dmlProg = dmlProg; } public DMLProgram getDMLProg(){ return _dmlProg; } public void addStatement(Statement s){ _statements.add(s); if (_statements.size() == 1){ this._beginLine = s.getBeginLine(); this._beginColumn = s.getBeginColumn(); } this._endLine = s.getEndLine(); this._endColumn = s.getEndColumn(); } /** * replace statement */ public void replaceStatement(int index, Statement passedStmt){ this._statements.set(index, passedStmt); if (index == 0){ this._beginLine = passedStmt.getBeginLine(); this._beginColumn = passedStmt.getBeginColumn(); } else if (index == this._statements.size() -1){ this._endLine = passedStmt.getEndLine(); this._endColumn = passedStmt.getEndColumn(); } } public void addStatementBlock(StatementBlock s){ for (int i = 0; i < s.getNumStatements(); i++){ _statements.add(s.getStatement(i)); } this._beginLine = _statements.get(0).getBeginLine(); this._beginColumn = _statements.get(0).getBeginColumn(); this._endLine = _statements.get(_statements.size() - 1).getEndLine(); this._endColumn = _statements.get(_statements.size() - 1).getEndColumn(); } public int getNumStatements(){ return _statements.size(); } public Statement getStatement(int i){ return _statements.get(i); } public ArrayList<Statement> getStatements() { return _statements; } public ArrayList<Hops> get_hops() throws HopsException { return _hops; } public ArrayList<Lops> get_lops() { return _lops; } public void set_hops(ArrayList<Hops> hops) { _hops = hops; } public void set_lops(ArrayList<Lops> lops) { _lops = lops; } public boolean mergeable(){ for (Statement s : _statements){ if (s.controlStatement()) return false; } return true; } public boolean isMergeableFunctionCallBlock(DMLProgram dmlProg) throws LanguageException{ // check whether targetIndex stmt block is for a mergable function call Statement stmt = this.getStatement(0); // Check whether targetIndex block is: control stmt block or stmt block for un-mergable function call if (stmt instanceof WhileStatement || stmt instanceof IfStatement || stmt instanceof ForStatement || stmt instanceof FunctionStatement || stmt instanceof CVStatement || stmt instanceof ELStatement) return false; // for regular stmt block, check if this is a function call stmt block if (stmt instanceof AssignmentStatement || stmt instanceof MultiAssignmentStatement){ Expression sourceExpr = null; if (stmt instanceof AssignmentStatement) sourceExpr = ((AssignmentStatement)stmt).getSource(); else sourceExpr = ((MultiAssignmentStatement)stmt).getSource(); if (sourceExpr instanceof FunctionCallIdentifier){ FunctionCallIdentifier fcall = (FunctionCallIdentifier) sourceExpr; FunctionStatementBlock fblock = dmlProg.getFunctionStatementBlock(fcall.getNamespace(), fcall.getName()); if (fblock == null) throw new LanguageException(sourceExpr.printErrorLocation() + "function " + fcall.getName() + " is undefined in namespace " + fcall.getNamespace()); if (fblock.getStatement(0) instanceof ExternalFunctionStatement || ((FunctionStatement)fblock.getStatement(0)).getBody().size() > 1 ){ return false; } else { // check if statement block is a control block StatementBlock stmtBlock = ((FunctionStatement)fblock.getStatement(0)).getBody().get(0); if (stmtBlock instanceof IfStatementBlock || stmtBlock instanceof WhileStatementBlock || stmtBlock instanceof ForStatementBlock){ return false; } else { return true; } } } } // regular function block return true; } public boolean isRewritableFunctionCall(Statement stmt, DMLProgram dmlProg) throws LanguageException{ // for regular stmt, check if this is a function call stmt block if (stmt instanceof AssignmentStatement || stmt instanceof MultiAssignmentStatement){ Expression sourceExpr = null; if (stmt instanceof AssignmentStatement) sourceExpr = ((AssignmentStatement)stmt).getSource(); else sourceExpr = ((MultiAssignmentStatement)stmt).getSource(); if (sourceExpr instanceof FunctionCallIdentifier){ FunctionCallIdentifier fcall = (FunctionCallIdentifier) sourceExpr; FunctionStatementBlock fblock = dmlProg.getFunctionStatementBlock(fcall.getNamespace(),fcall.getName()); if (fblock == null) throw new LanguageException(sourceExpr.printErrorLocation() + "function " + fcall.getName() + " is undefined in namespace " + fcall.getNamespace()); if (fblock.getStatement(0) instanceof ExternalFunctionStatement || ((FunctionStatement)fblock.getStatement(0)).getBody().size() > 1){ return false; } else { // check if statement block is a control block StatementBlock stmtBlock = ((FunctionStatement)fblock.getStatement(0)).getBody().get(0); if (stmtBlock instanceof IfStatementBlock || stmtBlock instanceof WhileStatementBlock || stmtBlock instanceof ForStatementBlock) return false; else return true; } } } // regular statement return false; } public boolean isNonRewritableFunctionCall(Statement stmt, DMLProgram dmlProg) throws LanguageException{ // for regular stmt, check if this is a function call stmt block if (stmt instanceof AssignmentStatement || stmt instanceof MultiAssignmentStatement){ Expression sourceExpr = null; if (stmt instanceof AssignmentStatement) sourceExpr = ((AssignmentStatement)stmt).getSource(); else sourceExpr = ((MultiAssignmentStatement)stmt).getSource(); if (sourceExpr instanceof FunctionCallIdentifier){ FunctionCallIdentifier fcall = (FunctionCallIdentifier) sourceExpr; FunctionStatementBlock fblock = dmlProg.getFunctionStatementBlock(fcall.getNamespace(), fcall.getName()); if (fblock == null) throw new LanguageException(sourceExpr.printErrorLocation() + "function " + fcall.getName() + " is undefined in namespace " + fcall.getNamespace()); if (fblock.getStatement(0) instanceof ExternalFunctionStatement || ((FunctionStatement)fblock.getStatement(0)).getBody().size() > 1 ){ return true; } else { return false; } } } // regular statement return false; } public static ArrayList<StatementBlock> mergeFunctionCalls(ArrayList<StatementBlock> body, DMLProgram dmlProg) throws LanguageException { for(int i = 0; i <body.size(); i++){ StatementBlock currBlock = body.get(i); // recurse to children function statement blocks if (currBlock instanceof WhileStatementBlock){ WhileStatement wstmt = (WhileStatement)((WhileStatementBlock)currBlock).getStatement(0); wstmt.setBody(mergeFunctionCalls(wstmt.getBody(),dmlProg)); } else if (currBlock instanceof ForStatementBlock){ ForStatement fstmt = (ForStatement)((ForStatementBlock)currBlock).getStatement(0); fstmt.setBody(mergeFunctionCalls(fstmt.getBody(),dmlProg)); } else if (currBlock instanceof IfStatementBlock){ IfStatement ifstmt = (IfStatement)((IfStatementBlock)currBlock).getStatement(0); ifstmt.setIfBody(mergeFunctionCalls(ifstmt.getIfBody(),dmlProg)); ifstmt.setElseBody(mergeFunctionCalls(ifstmt.getElseBody(),dmlProg)); } else if (currBlock instanceof FunctionStatementBlock){ FunctionStatement functStmt = (FunctionStatement)((FunctionStatementBlock)currBlock).getStatement(0); functStmt.setBody(mergeFunctionCalls(functStmt.getBody(),dmlProg)); } } ArrayList<StatementBlock> result = new ArrayList<StatementBlock>(); StatementBlock currentBlock = null; for (int i = 0; i < body.size(); i++){ StatementBlock current = body.get(i); if (current.isMergeableFunctionCallBlock(dmlProg)){ if (currentBlock != null) { currentBlock.addStatementBlock(current); } else { currentBlock = current; } } else { if (currentBlock != null) { result.add(currentBlock); } result.add(current); currentBlock = null; } } if (currentBlock != null) { result.add(currentBlock); } return result; } public String toString(){ StringBuffer sb = new StringBuffer(); sb.append("statements\n"); for (Statement s : _statements){ sb.append(s); sb.append("\n"); } if (_liveOut != null) sb.append("liveout " + _liveOut.toString() + "\n"); if (_liveIn!= null) sb.append("livein " + _liveIn.toString()+ "\n"); if (_gen != null) sb.append("gen " + _gen.toString()+ "\n"); if (_kill != null) sb.append("kill " + _kill.toString()+ "\n"); if (_read != null) sb.append("read " + _read.toString()+ "\n"); if (_updated != null) sb.append("updated " + _updated.toString()+ "\n"); return sb.toString(); } public static ArrayList<StatementBlock> mergeStatementBlocks(ArrayList<StatementBlock> sb){ ArrayList<StatementBlock> result = new ArrayList<StatementBlock>(); if (sb.size() == 0) { return new ArrayList<StatementBlock>(); } StatementBlock currentBlock = null; for (int i = 0; i < sb.size(); i++){ StatementBlock current = sb.get(i); if (current.mergeable()){ if (currentBlock != null) { currentBlock.addStatementBlock(current); } else { currentBlock = current; } } else { if (currentBlock != null) { result.add(currentBlock); } result.add(current); currentBlock = null; } } if (currentBlock != null) { result.add(currentBlock); } return result; } public ArrayList<Statement> rewriteFunctionCallStatements (DMLProgram dmlProg, ArrayList<Statement> statements) throws LanguageException { ArrayList<Statement> newStatements = new ArrayList<Statement>(); for (Statement current : statements){ if (isRewritableFunctionCall(current, dmlProg)){ Expression sourceExpr = null; if (current instanceof AssignmentStatement) sourceExpr = ((AssignmentStatement)current).getSource(); else sourceExpr = ((MultiAssignmentStatement)current).getSource(); FunctionCallIdentifier fcall = (FunctionCallIdentifier) sourceExpr; FunctionStatementBlock fblock = dmlProg.getFunctionStatementBlock(fcall.getNamespace(), fcall.getName()); if (fblock == null) throw new LanguageException(fcall.printErrorLocation() + "function " + fcall.getName() + " is undefined in namespace " + fcall.getNamespace()); FunctionStatement fstmt = (FunctionStatement)fblock.getStatement(0); String prefix = new Integer(fblock.hashCode()).toString() + "_"; if (fstmt.getBody().size() > 1) throw new LanguageException(sourceExpr.printErrorLocation() + "rewritable function can only have 1 statement block"); StatementBlock sblock = fstmt.getBody().get(0); for (int i =0; i < fstmt.getInputParams().size(); i++){ DataIdentifier currFormalParam = fstmt.getInputParams().get(i); // create new assignment statement String newFormalParameterName = prefix + currFormalParam.getName(); DataIdentifier newTarget = new DataIdentifier(currFormalParam); newTarget.setName(newFormalParameterName); Expression currCallParam = null; if (fcall.getParamExpressions().size() > i){ // function call has value for parameter currCallParam = fcall.getParamExpressions().get(i); } else { // use default value for parameter if (fstmt.getInputParams().get(i).getDefaultValue() == null) throw new LanguageException(currFormalParam.printErrorLocation() + "default parameter for " + currFormalParam + " is undefined"); currCallParam = new DataIdentifier(fstmt.getInputParams().get(i).getDefaultValue()); currCallParam.setAllPositions( fstmt.getInputParams().get(i).getBeginLine(), fstmt.getInputParams().get(i).getBeginColumn(), fstmt.getInputParams().get(i).getEndLine(), fstmt.getInputParams().get(i).getEndColumn()); } // create the assignment statement to bind the call parameter to formal parameter AssignmentStatement binding = new AssignmentStatement(newTarget, currCallParam, newTarget._beginLine, newTarget._beginColumn, newTarget._endLine, newTarget._endColumn); newStatements.add(binding); } for (Statement stmt : sblock._statements){ // rewrite the statement to use the "rewritten" name Statement rewrittenStmt = stmt.rewriteStatement(prefix); newStatements.add(rewrittenStmt); } // handle the return values for (int i = 0; i < fstmt.getOutputParams().size(); i++){ // get the target (return parameter from function) DataIdentifier currReturnParam = fstmt.getOutputParams().get(i); String newSourceName = prefix + currReturnParam.getName(); DataIdentifier newSource = new DataIdentifier(currReturnParam); newSource.setName(newSourceName); // get binding DataIdentifier newTarget = null; if (current instanceof AssignmentStatement){ if (i > 0) throw new LanguageException(current.printErrorLocation() + "Assignment statement cannot return multiple values"); newTarget = new DataIdentifier(((AssignmentStatement)current).getTarget()); } else{ newTarget = new DataIdentifier(((MultiAssignmentStatement)current).getTargetList().get(i)); } // create the assignment statement to bind the call parameter to formal parameter AssignmentStatement binding = new AssignmentStatement(newTarget, newSource, newTarget._beginLine, newTarget._beginColumn, newTarget._endLine, newTarget._endColumn); newStatements.add(binding); } } // end if (isRewritableFunctionCall(current, dmlProg) else { newStatements.add(current); } } return newStatements; } public VariableSet validate(DMLProgram dmlProg, VariableSet ids, HashMap<String, ConstIdentifier> constVars) throws LanguageException, ParseException, IOException { _constVarsIn.putAll(constVars); HashMap<String, ConstIdentifier> currConstVars = new HashMap<String,ConstIdentifier>(); currConstVars.putAll(constVars); _statements = rewriteFunctionCallStatements(dmlProg, _statements); _dmlProg = dmlProg; for (Statement current : _statements){ if (current instanceof InputStatement){ InputStatement is = (InputStatement)current; DataIdentifier target = is.getIdentifier(); Expression source = is.getSource(); source.setOutput(target); source.validateExpression(ids.getVariables(), currConstVars); setStatementFormatType(is); // use existing size and properties information for LHS IndexedIdentifier if (target instanceof IndexedIdentifier){ DataIdentifier targetAsSeen = ids.getVariable(target.getName()); if (targetAsSeen == null) throw new LanguageException(target.printErrorLocation() + "cannot assign value to indexed identifier " + target.toString() + " without initializing " + is.getIdentifier().getName()); target.setProperties(targetAsSeen); } ids.addVariable(target.getName(),target); } else if (current instanceof OutputStatement){ OutputStatement os = (OutputStatement)current; // validate variable being written by output statement exists DataIdentifier target = (DataIdentifier)os.getIdentifier(); if (ids.getVariable(target.getName()) == null){ //throwUndefinedVar ( target.getName(), os ); throw new LanguageException(os.printErrorLocation() + "Undefined Variable (" + target.getName() + ") used in statement", LanguageException.LanguageErrorCodes.INVALID_PARAMETERS); } if ( ids.getVariable(target.getName()).getDataType() == DataType.SCALAR) { boolean paramsOkay = true; for (String key : os._paramsExpr.getVarParams().keySet()){ if (!key.equals(Statement.IO_FILENAME)) paramsOkay = false; } if (paramsOkay == false) throw new LanguageException(os.printErrorLocation() + "Invalid parameters in write statement: " + os.toString()); } Expression source = os.getSource(); source.setOutput(target); source.validateExpression(ids.getVariables(), currConstVars); setStatementFormatType(os); target.setDimensionValueProperties(ids.getVariable(target.getName())); } else if (current instanceof AssignmentStatement){ AssignmentStatement as = (AssignmentStatement)current; DataIdentifier target = as.getTarget(); Expression source = as.getSource(); if (source instanceof FunctionCallIdentifier) ((FunctionCallIdentifier) source).validateExpression(dmlProg, ids.getVariables(),currConstVars); else source.validateExpression(ids.getVariables(), currConstVars); // Handle const vars: Basic Constant propagation currConstVars.remove(target.getName()); if (source instanceof ConstIdentifier && !(target instanceof IndexedIdentifier)){ currConstVars.put(target.getName(), (ConstIdentifier)source); } if (source instanceof BuiltinFunctionExpression){ BuiltinFunctionExpression bife = (BuiltinFunctionExpression)source; if ((bife.getOpCode() == Expression.BuiltinFunctionOp.NROW) || (bife.getOpCode() == Expression.BuiltinFunctionOp.NCOL)){ DataIdentifier id = (DataIdentifier)bife.getFirstExpr(); DataIdentifier currVal = ids.getVariable(id.getName()); if (currVal == null){ //throwUndefinedVar ( id.getName(), bife.toString() ); throw new LanguageException(bife.printErrorLocation() + "Undefined Variable (" + id.getName() + ") used in statement", LanguageException.LanguageErrorCodes.INVALID_PARAMETERS); } IntIdentifier intid = null; if (bife.getOpCode() == Expression.BuiltinFunctionOp.NROW){ intid = new IntIdentifier((int)currVal.getDim1()); } else { intid = new IntIdentifier((int)currVal.getDim2()); } // handle case when nrow / ncol called on variable with size unknown (dims == -1) // --> const prop NOT possible if (intid.getValue() != -1){ currConstVars.put(target.getName(), intid); } } } // CASE: target NOT indexed identifier if (!(target instanceof IndexedIdentifier)){ target.setProperties(source.getOutput()); if (source.getOutput() instanceof IndexedIdentifier){ target.setDimensions(source.getOutput().getDim1(), source.getOutput().getDim2()); } } // CASE: target is indexed identifier else { // process the "target" being indexed DataIdentifier targetAsSeen = ids.getVariable(target.getName()); if (targetAsSeen == null) throw new LanguageException(target.printErrorLocation() + "cannot assign value to indexed identifier " + target.toString() + " without first initializing " + target.getName()); target.setProperties(targetAsSeen); // process the expressions for the indexing if ( ((IndexedIdentifier)target).getRowLowerBound() != null ) ((IndexedIdentifier)target).getRowLowerBound().validateExpression(ids.getVariables(), currConstVars); if ( ((IndexedIdentifier)target).getRowUpperBound() != null ) ((IndexedIdentifier)target).getRowUpperBound().validateExpression(ids.getVariables(), currConstVars); if ( ((IndexedIdentifier)target).getColLowerBound() != null ) ((IndexedIdentifier)target).getColLowerBound().validateExpression(ids.getVariables(), currConstVars); if ( ((IndexedIdentifier)target).getColUpperBound() != null ) ((IndexedIdentifier)target).getColUpperBound().validateExpression(ids.getVariables(), currConstVars); // validate that LHS indexed identifier is being assigned a matrix value if (source.getOutput().getDataType() != Expression.DataType.MATRIX){ throw new LanguageException(target.printErrorLocation() + "Indexed expression " + target.toString() + " can only be assigned matrix value"); } // validate that size of LHS index ranges is being assigned: // (a) a matrix value of same size as LHS // (b) singleton value (semantics: initialize enitre submatrix with this value) IndexPair targetSize = ((IndexedIdentifier)target).calculateIndexedDimensions(currConstVars); if (targetSize._row >= 1 && source.getOutput().getDim1() > 1 && targetSize._row != source.getOutput().getDim1()){ throw new LanguageException(target.printErrorLocation() + "Dimension mismatch. Indexed expression " + target.toString() + " can only be assigned matrix with dimensions " + targetSize._row + " rows and " + targetSize._col + " cols. Attempted to assign matrix with dimensions " + source.getOutput().getDim1() + " rows and " + source.getOutput().getDim2() + " cols " ); } if (targetSize._col >= 1 && source.getOutput().getDim2() > 1 && targetSize._col != source.getOutput().getDim2()){ throw new LanguageException(target.printErrorLocation() + "Dimension mismatch. Indexed expression " + target.toString() + " can only be assigned matrix with dimensions " + targetSize._row + " rows and " + targetSize._col + " cols. Attempted to assign matrix with dimensions " + source.getOutput().getDim1() + " rows and " + source.getOutput().getDim2() + " cols " ); } ((IndexedIdentifier)target).setDimensions(targetSize._row, targetSize._col); } ids.addVariable(target.getName(), target); } else if (current instanceof MultiAssignmentStatement){ MultiAssignmentStatement mas = (MultiAssignmentStatement) current; ArrayList<DataIdentifier> targetList = mas.getTargetList(); // perform validation of source expression Expression source = mas.getSource(); if (!(source instanceof FunctionCallIdentifier)){ throw new LanguageException(source.printErrorLocation() + "can only use user-defined functions with multi-assignment statement"); } else { FunctionCallIdentifier fci = (FunctionCallIdentifier)source; fci.validateExpression(dmlProg, ids.getVariables(), currConstVars); } for (int j =0; j< targetList.size(); j++){ // set target properties (based on type info in function call statement return params) DataIdentifier target = targetList.get(j); FunctionCallIdentifier fci = (FunctionCallIdentifier)source; FunctionStatement fstmt = (FunctionStatement)_dmlProg.getFunctionStatementBlock(fci.getNamespace(), fci.getName()).getStatement(0); if (fstmt == null) throw new LanguageException(fci.printErrorLocation() + " function " + fci.getName() + " is undefined in namespace " + fci.getNamespace()); if (!(target instanceof IndexedIdentifier)){ target.setProperties(fstmt.getOutputParams().get(j)); } else{ DataIdentifier targetAsSeen = ids.getVariable(target.getName()); if (targetAsSeen == null) throw new LanguageException(target.printErrorLocation() + "cannot assign value to indexed identifier " + target.toString() + " without first initializing " + target.getName()); target.setProperties(targetAsSeen); } ids.addVariable(target.getName(), target); } } else if(current instanceof RandStatement) { RandStatement rs = (RandStatement) current; // perform constant propagation by replacing exprParams which are DataIdentifier (but NOT IndexedIdentifier) variables with constant values. // Also perform "best-effort" validation of parameter values (i.e., for parameter values which are constant expressions) rs.performConstantPropagation(currConstVars); // update properties of RandStatement target identifier rs.setIdentifierProperties(); // add RandStatement target to available variables list ids.addVariable(rs.getIdentifier().getName(), rs.getIdentifier()); } else if(current instanceof CVStatement || current instanceof ELStatement || current instanceof ForStatement || current instanceof IfStatement || current instanceof WhileStatement ){ throw new LanguageException(current.printErrorLocation() + "control statement (CVStatement, ELStatement, WhileStatement, IfStatement, ForStatement) should not be in genreric statement block. Likely a parsing error"); } else if (current instanceof PrintStatement){ PrintStatement pstmt = (PrintStatement) current; Expression expr = pstmt.getExpression(); expr.validateExpression(ids.getVariables(), currConstVars); // check that variables referenced in print statement expression are scalars if (expr.getOutput().getDataType() != Expression.DataType.SCALAR){ throw new LanguageException(current.printErrorLocation() + "print statement can only print scalars"); } } // no work to perform for PathStatement or ImportStatement else if (current instanceof PathStatement){} else if (current instanceof ImportStatement){} else { throw new LanguageException(current.printErrorLocation() + "cannot process statement of type " + current.getClass().getSimpleName()); } } // end for (Statement current : _statements){ _constVarsOut.putAll(currConstVars); return ids; } public void setStatementFormatType(IOStatement s) throws LanguageException, ParseException{ if (s.getExprParam(Statement.FORMAT_TYPE)!= null ){ Expression formatTypeExpr = s.getExprParam(Statement.FORMAT_TYPE); if (!(formatTypeExpr instanceof StringIdentifier)) throw new LanguageException(s.printErrorLocation() + "input statement parameter " + Statement.FORMAT_TYPE + " can only be a string with one of following values: binary, text", LanguageException.LanguageErrorCodes.INVALID_PARAMETERS); String ft = formatTypeExpr.toString(); if (ft.equalsIgnoreCase("binary")){ s._id.setFormatType(FormatType.BINARY); } else if (ft.equalsIgnoreCase("text")){ s._id.setFormatType(FormatType.TEXT); } else throw new LanguageException(s.printErrorLocation() + "input statement parameter " + Statement.FORMAT_TYPE + " can only be a string with one of following values: binary, text", LanguageException.LanguageErrorCodes.INVALID_PARAMETERS); } else { s.addExprParam(Statement.FORMAT_TYPE, new StringIdentifier(FormatType.TEXT.toString()),true); s._id.setFormatType(FormatType.TEXT); } } /** * For each statement: * * gen rule: for each variable read in current statement but not updated in any PRIOR statement, add to gen * Handles case where variable both read and updated in same statement (i = i + 1, i needs to be added to gen) * * kill rule: for each variable updated in current statement but not read in this or any PRIOR statement, * add to kill. * */ public VariableSet initializeforwardLV(VariableSet activeIn) throws LanguageException { for (Statement s : _statements){ s.initializeforwardLV(activeIn); VariableSet read = s.variablesRead(); VariableSet updated = s.variablesUpdated(); if (s instanceof WhileStatement || s instanceof IfStatement || s instanceof ForStatement){ throw new LanguageException(s.printErrorLocation() + "control statement (while / for / if) cannot be in generic statement block"); } if (read != null){ // for each variable read in this statement but not updated in // any prior statement, add to sb._gen for (String var : read.getVariableNames()) { if (!_updated.containsVariable(var)){ _gen.addVariable(var, read.getVariable(var)); } } } _read.addVariables(read); _updated.addVariables(updated); if (updated != null) { // for each updated variable that is not read for (String var : updated.getVariableNames()){ if (!_read.containsVariable(var)) { _kill.addVariable(var, _updated.getVariable(var)); } } } } _liveOut = new VariableSet(); _liveOut.addVariables(activeIn); _liveOut.addVariables(_updated); return _liveOut; } public VariableSet initializebackwardLV(VariableSet loPassed) throws LanguageException{ int numStatements = _statements.size(); VariableSet lo = new VariableSet(); lo.addVariables(loPassed); for (int i = numStatements-1; i>=0; i lo = _statements.get(i).initializebackwardLV(lo); } VariableSet loReturn = new VariableSet(); loReturn.addVariables(lo); return loReturn; } public HashMap<String, ConstIdentifier> getConstIn(){ return _constVarsIn; } public HashMap<String, ConstIdentifier> getConstOut(){ return _constVarsOut; } public VariableSet analyze(VariableSet loPassed) throws LanguageException{ VariableSet candidateLO = new VariableSet(); candidateLO.addVariables(loPassed); //candidateLO.addVariables(_gen); VariableSet origLiveOut = new VariableSet(); origLiveOut.addVariables(_liveOut); _liveOut = new VariableSet(); for (String name : candidateLO.getVariableNames()){ if (origLiveOut.containsVariable(name)){ _liveOut.addVariable(name, candidateLO.getVariable(name)); } } initializebackwardLV(_liveOut); _liveIn = new VariableSet(); _liveIn.addVariables(_liveOut); _liveIn.removeVariables(_kill); _liveIn.addVariables(_gen); VariableSet liveInReturn = new VariableSet(); liveInReturn.addVariables(_liveIn); return liveInReturn; } // store position information for statement blocks public int _beginLine = 0, _beginColumn = 0; public int _endLine = 0, _endColumn = 0; public void setBeginLine(int passed) { _beginLine = passed; } public void setBeginColumn(int passed) { _beginColumn = passed; } public void setEndLine(int passed) { _endLine = passed; } public void setEndColumn(int passed) { _endColumn = passed; } public void setAllPositions(int blp, int bcp, int elp, int ecp){ _beginLine = blp; _beginColumn = bcp; _endLine = elp; _endColumn = ecp; } public int getBeginLine() { return _beginLine; } public int getBeginColumn() { return _beginColumn; } public int getEndLine() { return _endLine; } public int getEndColumn() { return _endColumn; } public String printErrorLocation(){ return "ERROR: line " + _beginLine + ", column " + _beginColumn + " } public String printBlockErrorLocation(){ return "ERROR: statement block between lines " + _beginLine + " and " + _endLine + " } public String printWarningLocation(){ return "WARNING: line " + _beginLine + ", column " + _beginColumn + " } /** * * @param asb * @param upVars */ public void rFindUpdatedVariables( ArrayList<StatementBlock> asb, HashSet<String> upVars ) { for(StatementBlock sb : asb ) // foreach statementblock for( Statement s : sb._statements ) // foreach statement in statement block { if( s instanceof ForStatement || s instanceof ParForStatement ) { rFindUpdatedVariables(((ForStatement)s).getBody(), upVars); } else if( s instanceof WhileStatement ) { rFindUpdatedVariables(((WhileStatement)s).getBody(), upVars); } else if( s instanceof IfStatement ) { rFindUpdatedVariables(((IfStatement)s).getIfBody(), upVars); rFindUpdatedVariables(((IfStatement)s).getElseBody(), upVars); } else if( s instanceof FunctionStatement ) { rFindUpdatedVariables(((FunctionStatement)s).getBody(), upVars); } else { //evaluate assignment statements Collection<DataIdentifier> tmp = null; if( s instanceof AssignmentStatement ) { tmp = ((AssignmentStatement)s).getTargetList(); } else if (s instanceof FunctionStatement) { tmp = ((FunctionStatement)s).getOutputParams(); } else if (s instanceof MultiAssignmentStatement) { tmp = ((MultiAssignmentStatement)s).getTargetList(); } //add names of updated data identifiers to results if( tmp!=null ) for( DataIdentifier di : tmp ) upVars.add( di.getName() ); } } } } // end class
package io.tetrapod.core.registry; import io.tetrapod.protocol.core.Subscriber; import java.util.*; /** * A data structure to manage a Topic for pub/sub. Topics have an owner, a reference ID, and a list of subscribers. If the same client * subscribes to the topic multiple times, we increment a reference counter. A subscription is fully unsubscribed if the counter drops to * zero. */ public class Topic { public final int topicId; public final int ownerId; private final Map<Integer, Subscriber> subscribers = new HashMap<>(); private final Map<Integer, Subscriber> parents = new HashMap<>(); private final Map<Integer, Subscriber> children = new HashMap<>(); public Topic(int ownerId, int topicId) { this.topicId = topicId; this.ownerId = ownerId; } /** * Add a client as a subscriber. * * @return true if the client was not already subscribed */ public synchronized boolean subscribe(final EntityInfo publisher, final EntityInfo e, final int parentId) { Subscriber sub = subscribers.get(e.entityId); if (sub == null) { sub = new Subscriber(e.entityId, 0); subscribers.put(e.entityId, sub); if (e.isTetrapod()) { if (publisher.parentId == parentId) { // if they are a tetrapod and this topic is owned by us, we can deliver directly children.put(e.entityId, sub); } } else { if (e.parentId != parentId) { // if we aren't their parent, add them to a proxy subscription for their parent Subscriber psub = parents.get(e.parentId); if (psub == null) { psub = new Subscriber(e.parentId, 0); parents.put(e.parentId, psub); } psub.counter++; } else { // we are their parent, so we can deliver messages directly children.put(e.entityId, sub); } } } sub.counter++; return sub.counter == 1; } /** * Unsubscribe a client from this topic. We decrement their counter, and only unsubscribe if it drops to zero. * * @return true if we fully unsubscribed the client */ public synchronized boolean unsubscribe(int entityId, int parentId, boolean proxy, boolean all) { final Subscriber sub = subscribers.get(entityId); if (sub != null) { sub.counter if (sub.counter == 0 || all) { subscribers.remove(entityId); children.remove(entityId); if (proxy) { Subscriber psub = parents.get(parentId); if (psub != null) { psub.counter if (psub.counter == 0) { parents.remove(parentId); } } } return true; } } return false; } @Override public String toString() { return String.format("Topic-%d-%d", ownerId, topicId); } /** * Get the total number of unique subscribers to this topic */ public synchronized int getNumSubscribers() { return subscribers.size(); } public synchronized Collection<Subscriber> getChildSubscribers() { return children.values(); } public synchronized Collection<Subscriber> getProxySubscribers() { return parents.values(); } public synchronized Collection<Subscriber> getSubscribers() { return subscribers.values(); } public long key() { return ((long) (ownerId) << 32) | (long) topicId; } }
package com.msjBand.kraftscangradle.kraftscan; import android.content.res.Configuration; import android.graphics.Color; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarActivity; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.RelativeLayout; import java.util.ArrayList; public class EventListActivity extends ActionBarActivity { public ArrayList<String> mSettings; private DrawerLayout mDrawerLayout; private RelativeLayout mDrawerRelativeLayout; public ListView mDrawerList; private ActionBarDrawerToggle mDrawerToggle; private ArrayAdapter<String> adapter; public class DrawerAdapter extends ArrayAdapter<String> { @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = getLayoutInflater().inflate(R.layout.settings_item); } } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_events_list); Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar); toolbar.setTitleTextColor(Color.WHITE); setSupportActionBar(toolbar); FragmentManager fm = getSupportFragmentManager(); Fragment fragment = fm.findFragmentById(R.id.content_frame); if (fragment == null) { fragment = new EventListFragment(); fm.beginTransaction() .add(R.id.content_frame, fragment) .commit(); } mSettings = new ArrayList<String>(); if (EventsLab.get(getApplicationContext()).getStudentName() == null) mSettings.add("Set Name"); else mSettings.add(EventsLab.get(getApplicationContext()).getStudentName()); adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mSettings); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mDrawerLayout.setStatusBarBackgroundColor(getResources().getColor(R.color.primary_dark)); mDrawerList = (ListView) findViewById(R.id.left_drawer); mDrawerList.setAdapter(adapter); mDrawerList.setOnItemClickListener(new ListView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { FragmentManager fm = getSupportFragmentManager(); if ((position == 0) && fm.getBackStackEntryCount() < 1) { Fragment fragment = new SetFlightFragment(); fm = getSupportFragmentManager(); fm.beginTransaction().setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right, android.R.anim.slide_in_left, android.R.anim.slide_out_right).replace(R.id.content_frame, fragment).addToBackStack("detail").commit(); mDrawerList.setItemChecked(position, true); mDrawerLayout.closeDrawers(); } if ((position == 0) && fm.getBackStackEntryCount() >= 1) { fm.popBackStack(); Fragment fragment = new SetFlightFragment(); fm = getSupportFragmentManager(); fm.beginTransaction().setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right, android.R.anim.slide_in_left, android.R.anim.slide_out_right).replace(R.id.content_frame, fragment).addToBackStack("detail").commit(); mDrawerList.setItemChecked(position, true); mDrawerLayout.closeDrawers(); } } }); mDrawerToggle = new ActionBarDrawerToggle( this, mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close ) { @Override public void onDrawerSlide(View drawerView, float slideOffset) { if (EventsLab.get(getApplicationContext()).getStudentName() == null) mSettings.set(0, "Set Name"); else mSettings.set(0, EventsLab.get(getApplicationContext()).getStudentName()); adapter.notifyDataSetChanged(); super.onDrawerSlide(drawerView, slideOffset); } public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); } public void onDrawerClosed(View view) { super.onDrawerClosed(view); } }; mDrawerLayout.setDrawerListener(mDrawerToggle); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Sync the toggle state after onRestoreInstanceState has occurred. mDrawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); mDrawerToggle.onConfigurationChanged(newConfig); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Pass the event to ActionBarDrawerToggle, if it returns // true, then it has handled the app icon touch event if (mDrawerToggle.onOptionsItemSelected(item)) { return true; } // Handle your other action bar items... return super.onOptionsItemSelected(item); } }
package nl.fontys.sofa.limo.view.custom; import com.jgoodies.forms.layout.CellConstraints; import com.jgoodies.forms.layout.FormLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.ArrayList; import java.util.List; import javax.swing.DefaultCellEditor; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; import nl.fontys.sofa.limo.api.dao.ProcedureCategoryDAO; import nl.fontys.sofa.limo.domain.component.procedure.Procedure; import nl.fontys.sofa.limo.domain.component.procedure.ProcedureCategory; import nl.fontys.sofa.limo.domain.component.procedure.ProcedureResponsibilityDirection; import nl.fontys.sofa.limo.domain.component.procedure.TimeType; import nl.fontys.sofa.limo.domain.component.procedure.value.RangeValue; import nl.fontys.sofa.limo.domain.component.procedure.value.SingleValue; import nl.fontys.sofa.limo.domain.component.procedure.value.Value; import nl.fontys.sofa.limo.view.custom.table.DragNDropTable; import nl.fontys.sofa.limo.view.custom.table.DragNDropTableModel; import nl.fontys.sofa.limo.view.util.IconUtil; import org.openide.util.Lookup; public class ProcedureComponent extends JPanel implements ActionListener, MouseListener { private DragNDropTable table; private DragNDropTableModel model; private JButton btn_add, btn_delete; private JScrollPane sc_pane; private ProcedureCategoryDAO procedureCategoryDao = Lookup.getDefault().lookup(ProcedureCategoryDAO.class); private Value changedValue; CellConstraints cc; public ProcedureComponent() { this(null); } public ProcedureComponent(List<Procedure> procedures) { //LAYOUT cc = new CellConstraints(); FormLayout layout = new FormLayout("5px, pref:grow, 5px, pref, 5px", "5px, pref, 10px, pref, pref:grow, 5px"); this.setLayout(layout); //TABLEMODEL List<List<Object>> valueList = new ArrayList<>(); if (procedures != null) { for (Procedure p : procedures) { ArrayList<Object> values = new ArrayList<>(); values.add(p.getName()); values.add(p.getCategory()); values.add(p.getTimeType()); values.add(p.getTime()); values.add(p.getCost()); values.add(p.getDirection()); valueList.add(values); } } model = new DragNDropTableModel(new String[]{"Name", "Category", "Time Type", "Time Cost", "Money Cost", "Direction"}, valueList, new Class[]{String.class, String.class, TimeType.class, Value.class, Value.class, ProcedureResponsibilityDirection.class}); //TABLE table = new DragNDropTable(model); try { table.getColumnModel().getColumn(1).setCellEditor(new DefaultCellEditor(new JComboBox(procedureCategoryDao.findAll().toArray()))); } catch (Exception e) { table.getColumnModel().getColumn(1).setCellEditor(new DefaultCellEditor(new JComboBox(new ProcedureCategory[]{}))); } table.getColumnModel().getColumn(2).setCellEditor(new DefaultCellEditor(new JComboBox(TimeType.values()))); table.getColumnModel().getColumn(5).setCellEditor(new DefaultCellEditor(new JComboBox(ProcedureResponsibilityDirection.values()))); //OTHER COMPONENTS sc_pane = new JScrollPane(table); btn_add = new JButton(new ImageIcon(IconUtil.getIcon(IconUtil.UI_ICON.ADD))); btn_delete = new JButton(new ImageIcon(IconUtil.getIcon(IconUtil.UI_ICON.TRASH))); //ADD COMPONENTS TO PANEL this.add(sc_pane, cc.xywh(2, 2, 1, 4)); this.add(btn_add, cc.xy(4, 2)); this.add(btn_delete, cc.xy(4, 4)); //ADD COMPONENTS TO LISTENER btn_add.addActionListener(this); btn_delete.addActionListener(this); table.addMouseListener(this); this.setVisible(true); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource().equals(btn_delete)) { int rowToDelete = table.getSelectedRow(); if (rowToDelete > -1) { deleteProcedure(rowToDelete); } } else if (e.getSource().equals(btn_add)) { addProcedure(); } } @Override public void mouseClicked(MouseEvent e) { if (e.getSource().equals(table)) { System.out.println(getActiveTableState()); if (e.getClickCount() > 1) { editProcedure(); } } } public List<Procedure> getActiveTableState() { List<List<Object>> values = ((DragNDropTableModel) table.getModel()).getValues(); ArrayList<Procedure> procedures = new ArrayList<>(); for (List<Object> value : values) { Procedure p = new Procedure(); p.setName((String) value.get(0)); p.setCategory((String) value.get(1)); p.setTimeType((TimeType) value.get(2)); p.setTime((Value) value.get(3)); p.setCost((Value) value.get(4)); p.setDirection((ProcedureResponsibilityDirection) value.get(5)); procedures.add(p); } return procedures; } public void setProcedureTable(List<Procedure> procedures) { List<List<Object>> valueList = new ArrayList<>(); if (procedures != null) { for (Procedure p : procedures) { ArrayList<Object> values = new ArrayList<>(); values.add(p.getName()); values.add(p.getCategory()); values.add(p.getTimeType()); values.add(p.getTime()); values.add(p.getCost()); values.add(p.getDirection()); valueList.add(values); } } model = new DragNDropTableModel(new String[]{"Name", "Category", "Time Type", "Time Cost", "Money Cost", "Direction"}, valueList, new Class[]{String.class, String.class, TimeType.class, Value.class, Value.class, ProcedureResponsibilityDirection.class}); table.setModel(model); model.fireTableDataChanged(); this.revalidate(); this.repaint(); } private void addProcedure() { new AddProcedureDialog(); } private void deleteProcedure(int row) { ((DragNDropTableModel) table.getModel()).removeRow(row); this.revalidate(); this.repaint(); } private void editProcedure() { changedValue = (Value) table.getValueAt(table.getSelectedRow(), table.getSelectedColumn()); new EditValueDialog((Value) table.getValueAt(table.getSelectedRow(), table.getSelectedColumn())); table.setValueAt(changedValue, table.getSelectedRow(), table.getSelectedColumn()); this.revalidate(); this.repaint(); } // <editor-fold desc="UNUSED LISTENER METHODS" defaultstate="collapsed"> @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } //</editor-fold> private class AddProcedureDialog extends JDialog implements ActionListener { private final JButton btn_addSave, btn_addCancel, btn_addTime, btn_addCost; private final JLabel lbl_name, lbl_category, lbl_timeType, lbl_time, lbl_cost, lbl_direction; private final JTextField tf_name, tf_cost, tf_time; private final JComboBox cbox_timeType, cbox_direction; private JComboBox cbox_category; private Value timeValue, costValue; private Procedure newProcedure; public AddProcedureDialog() { //LAYOUT FormLayout layout = new FormLayout("5px, pref, 5px, pref, pref:grow, 5px, pref, 5px", "5px, pref, 5px, pref, 5px, pref, 5px, pref, 5px, pref, 5px, pref, 5px, pref, 5px"); this.setLayout(layout); //COMPONENTS lbl_name = new JLabel("Name:"); tf_name = new JTextField(); lbl_category = new JLabel("Category:"); try { cbox_category = new JComboBox(procedureCategoryDao.findAll().toArray()); } catch (Exception e) { cbox_category = new JComboBox(new ProcedureCategory[]{}); } lbl_timeType = new JLabel("Time Type:"); cbox_timeType = new JComboBox(TimeType.values()); lbl_time = new JLabel("Time Cost:"); timeValue = new SingleValue(0.0); tf_time = new JTextField(timeValue.toString()); tf_time.setEditable(false); btn_addTime = new JButton("..."); costValue = new SingleValue(0.0); lbl_cost = new JLabel("Money Cost:"); tf_cost = new JTextField(costValue.toString()); tf_cost.setEditable(false); btn_addCost = new JButton("..."); lbl_direction = new JLabel("Direction:"); cbox_direction = new JComboBox(ProcedureResponsibilityDirection.values()); btn_addSave = new JButton("Save"); btn_addCancel = new JButton("Cancel"); //ADD COMPONENTS this.add(lbl_name, cc.xy(2, 2)); this.add(tf_name, cc.xyw(4, 2, 2)); this.add(lbl_category, cc.xy(2, 4)); this.add(cbox_category, cc.xyw(4, 4, 2)); this.add(lbl_timeType, cc.xy(2, 6)); this.add(cbox_timeType, cc.xyw(4, 6, 2)); this.add(lbl_time, cc.xy(2, 8)); this.add(tf_time, cc.xyw(4, 8, 2)); this.add(btn_addTime, cc.xy(7, 8)); this.add(lbl_cost, cc.xy(2, 10)); this.add(tf_cost, cc.xyw(4, 10, 2)); this.add(btn_addCost, cc.xy(7, 10)); this.add(lbl_direction, cc.xy(2, 12)); this.add(cbox_direction, cc.xyw(4, 12, 2)); this.add(btn_addSave, cc.xy(2, 14)); this.add(btn_addCancel, cc.xy(4, 14)); //ADD COMPONENTS TO LISTENER btn_addCancel.addActionListener(this); btn_addSave.addActionListener(this); btn_addCost.addActionListener(this); btn_addTime.addActionListener(this); //DIALOG OPTIONS this.setSize(250, 300); this.setModal(true); this.setAlwaysOnTop(true); Toolkit toolkit = Toolkit.getDefaultToolkit(); Dimension screenSize = toolkit.getScreenSize(); int x = (screenSize.width - this.getWidth()) / 2; int y = (screenSize.height - this.getHeight()) / 2; this.setLocation(x, y); this.setDefaultCloseOperation(DISPOSE_ON_CLOSE); this.setVisible(true); } private boolean isValidProcedure() { return !(tf_name.getText().equals("") || tf_name.getText().equals("") || tf_cost.getText().equals("")); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource().equals(btn_addCost)) { new EditValueDialog(costValue); if (costValue != null) { costValue = changedValue; tf_cost.setText(costValue.toString()); this.revalidate(); this.repaint(); } } if (e.getSource().equals(btn_addTime)) { new EditValueDialog(timeValue); if (timeValue != null) { timeValue = changedValue; tf_time.setText(timeValue.toString()); this.revalidate(); this.repaint(); } } if (e.getSource().equals(btn_addCancel)) { this.dispose(); } if (e.getSource().equals(btn_addSave)) { if (isValidProcedure()) { String name = tf_name.getText(); String category = ""; try { category = cbox_category.getSelectedItem().toString(); } catch (Exception ex) { } TimeType timeType = (TimeType) cbox_timeType.getSelectedItem(); ProcedureResponsibilityDirection direction = (ProcedureResponsibilityDirection) cbox_direction.getSelectedItem(); newProcedure = new Procedure(name, category, costValue, timeValue, timeType, direction); List<Object> newRow = new ArrayList<>(); newRow.add(newProcedure.getName()); newRow.add(newProcedure.getCategory()); newRow.add(newProcedure.getTimeType()); newRow.add(newProcedure.getTime()); newRow.add(newProcedure.getCost()); newRow.add(newProcedure.getDirection()); ((DragNDropTableModel) table.getModel()).addRow(newRow); ((DragNDropTableModel) table.getModel()).fireTableDataChanged(); table.revalidate(); table.repaint(); this.dispose(); } } } } private class EditValueDialog extends JDialog implements ActionListener { private final JButton btn_dialogSave, btn_dialogCancel; private final JComboBox<String> cbox_valueType; private final JTextField tf_value, tf_min, tf_max; private final JPanel singlePanel, rangePanel; private final JLabel lbl_type, lbl_value, lbl_min, lbl_max, lbl_error; private int activeType = 0; public EditValueDialog(Value value) { //LAYOUT FormLayout mainLayout = new FormLayout("5px, pref, 5px, pref, 5px, pref:grow, 5px", "5px, pref, 5px, pref, 5px, pref, 5px, pref, 5px"); FormLayout rangeLayout = new FormLayout("5px, pref, 5px, pref:grow, 5px", "5px, pref, 5px, pref, 5px"); FormLayout singleLayout = new FormLayout("5px, pref, 5px, pref:grow, 5px", "5px, pref, 5px"); this.setLayout(mainLayout); //COMPONENTS tf_value = new JTextField(); tf_min = new JTextField(); tf_max = new JTextField(); singlePanel = new JPanel(); rangePanel = new JPanel(); lbl_type = new JLabel("Type: "); lbl_value = new JLabel("Value: "); lbl_min = new JLabel("Min: "); lbl_max = new JLabel("Max: "); lbl_error = new JLabel(); lbl_error.setForeground(Color.RED); btn_dialogCancel = new JButton("Cancel"); btn_dialogSave = new JButton("Save"); cbox_valueType = new JComboBox<>(new String[]{"Single", "Range"}); //ADD COMPONENTS TO SINGLE PANEL singlePanel.setLayout(singleLayout); singlePanel.add(lbl_value, cc.xy(2, 2)); singlePanel.add(tf_value, cc.xy(4, 2)); //ADD COMPONENTS TO RANGE PANEL rangePanel.setLayout(rangeLayout); rangePanel.add(lbl_min, cc.xy(2, 2)); rangePanel.add(tf_min, cc.xy(4, 2)); rangePanel.add(lbl_max, cc.xy(2, 4)); rangePanel.add(tf_max, cc.xy(4, 4)); //ADD COMPONENTS TO DIALOG this.add(lbl_type, cc.xy(2, 2)); this.add(cbox_valueType, cc.xyw(4, 2, 3)); if (value != null) { if (value instanceof SingleValue) { this.add(singlePanel, cc.xyw(2, 4, 5)); cbox_valueType.setSelectedIndex(0); tf_value.setText(value.getValue() + ""); activeType = 0; } else { this.add(rangePanel, cc.xyw(2, 4, 5)); cbox_valueType.setSelectedIndex(1); tf_min.setText(value.getMin() + ""); tf_max.setText(value.getMax() + ""); activeType = 1; } } else { this.add(singlePanel, cc.xyw(2, 4, 5)); cbox_valueType.setSelectedIndex(0); activeType = 0; } this.add(btn_dialogSave, cc.xy(2, 6)); this.add(btn_dialogCancel, cc.xy(4, 6)); this.add(lbl_error, cc.xyw(2, 8, 5)); //ADD COMPONENTS TO LISTENER btn_dialogCancel.addActionListener(this); btn_dialogSave.addActionListener(this); cbox_valueType.addActionListener(this); //DIALOG OPTIONS this.setModal(true); this.setSize(200, 250); this.setAlwaysOnTop(true); Toolkit toolkit = Toolkit.getDefaultToolkit(); Dimension screenSize = toolkit.getScreenSize(); int x = (screenSize.width - this.getWidth()) / 2; int y = (screenSize.height - this.getHeight()) / 2; this.setLocation(x, y); this.setDefaultCloseOperation(DISPOSE_ON_CLOSE); this.setVisible(true); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource().equals(cbox_valueType)) { if (activeType != cbox_valueType.getSelectedIndex()) { double activeValue; if (activeType == 0) { activeValue = 0; try { activeValue = Double.parseDouble(tf_value.getText()); } catch (NumberFormatException ex) { } this.remove(singlePanel); this.add(rangePanel, cc.xyw(2, 4, 5)); tf_min.setText(activeValue + ""); lbl_error.setText(""); } else { activeValue = 0; try { activeValue = Double.parseDouble(tf_min.getText()); } catch (NumberFormatException ex) { } this.remove(rangePanel); this.add(singlePanel, cc.xyw(2, 4, 5)); tf_value.setText(activeValue + ""); lbl_error.setText(""); } activeType = cbox_valueType.getSelectedIndex(); this.revalidate(); this.repaint(); } } if (e.getSource().equals(btn_dialogCancel)) { this.dispose(); } if (e.getSource().equals(btn_dialogSave)) { if (activeType == 0) { try { changedValue = new SingleValue(Double.parseDouble(tf_value.getText())); this.dispose(); } catch (NumberFormatException ex) { lbl_error.setText("NOT A NUMBER"); } } else { try { double min = Double.parseDouble(tf_min.getText()); double max = Double.parseDouble(tf_max.getText()); if (max > min) { changedValue = new RangeValue(min, max); this.dispose(); } else { lbl_error.setText("MAX MUST BE BIGGER THAN MIN"); } } catch (NumberFormatException ex) { lbl_error.setText("NOT A NUMBER"); } } } } } }